reflection.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # http://code.google.com/p/protobuf/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. # This code is meant to work on Python 2.4 and above only.
  31. #
  32. # TODO(robinson): Helpers for verbose, common checks like seeing if a
  33. # descriptor's cpp_type is CPPTYPE_MESSAGE.
  34. """Contains a metaclass and helper functions used to create
  35. protocol message classes from Descriptor objects at runtime.
  36. Recall that a metaclass is the "type" of a class.
  37. (A class is to a metaclass what an instance is to a class.)
  38. In this case, we use the GeneratedProtocolMessageType metaclass
  39. to inject all the useful functionality into the classes
  40. output by the protocol compiler at compile-time.
  41. The upshot of all this is that the real implementation
  42. details for ALL pure-Python protocol buffers are *here in
  43. this file*.
  44. """
  45. __author__ = 'robinson@google.com (Will Robinson)'
  46. import heapq
  47. import threading
  48. import weakref
  49. # We use "as" to avoid name collisions with variables.
  50. from google.protobuf.internal import containers
  51. from google.protobuf.internal import decoder
  52. from google.protobuf.internal import encoder
  53. from google.protobuf.internal import message_listener as message_listener_mod
  54. from google.protobuf.internal import type_checkers
  55. from google.protobuf.internal import wire_format
  56. from google.protobuf import descriptor as descriptor_mod
  57. from google.protobuf import message as message_mod
  58. _FieldDescriptor = descriptor_mod.FieldDescriptor
  59. class GeneratedProtocolMessageType(type):
  60. """Metaclass for protocol message classes created at runtime from Descriptors.
  61. We add implementations for all methods described in the Message class. We
  62. also create properties to allow getting/setting all fields in the protocol
  63. message. Finally, we create slots to prevent users from accidentally
  64. "setting" nonexistent fields in the protocol message, which then wouldn't get
  65. serialized / deserialized properly.
  66. The protocol compiler currently uses this metaclass to create protocol
  67. message classes at runtime. Clients can also manually create their own
  68. classes at runtime, as in this example:
  69. mydescriptor = Descriptor(.....)
  70. class MyProtoClass(Message):
  71. __metaclass__ = GeneratedProtocolMessageType
  72. DESCRIPTOR = mydescriptor
  73. myproto_instance = MyProtoClass()
  74. myproto.foo_field = 23
  75. ...
  76. """
  77. # Must be consistent with the protocol-compiler code in
  78. # proto2/compiler/internal/generator.*.
  79. _DESCRIPTOR_KEY = 'DESCRIPTOR'
  80. def __new__(cls, name, bases, dictionary):
  81. """Custom allocation for runtime-generated class types.
  82. We override __new__ because this is apparently the only place
  83. where we can meaningfully set __slots__ on the class we're creating(?).
  84. (The interplay between metaclasses and slots is not very well-documented).
  85. Args:
  86. name: Name of the class (ignored, but required by the
  87. metaclass protocol).
  88. bases: Base classes of the class we're constructing.
  89. (Should be message.Message). We ignore this field, but
  90. it's required by the metaclass protocol
  91. dictionary: The class dictionary of the class we're
  92. constructing. dictionary[_DESCRIPTOR_KEY] must contain
  93. a Descriptor object describing this protocol message
  94. type.
  95. Returns:
  96. Newly-allocated class.
  97. """
  98. descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]
  99. _AddSlots(descriptor, dictionary)
  100. _AddClassAttributesForNestedExtensions(descriptor, dictionary)
  101. superclass = super(GeneratedProtocolMessageType, cls)
  102. return superclass.__new__(cls, name, bases, dictionary)
  103. def __init__(cls, name, bases, dictionary):
  104. """Here we perform the majority of our work on the class.
  105. We add enum getters, an __init__ method, implementations
  106. of all Message methods, and properties for all fields
  107. in the protocol type.
  108. Args:
  109. name: Name of the class (ignored, but required by the
  110. metaclass protocol).
  111. bases: Base classes of the class we're constructing.
  112. (Should be message.Message). We ignore this field, but
  113. it's required by the metaclass protocol
  114. dictionary: The class dictionary of the class we're
  115. constructing. dictionary[_DESCRIPTOR_KEY] must contain
  116. a Descriptor object describing this protocol message
  117. type.
  118. """
  119. descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]
  120. # We act as a "friend" class of the descriptor, setting
  121. # its _concrete_class attribute the first time we use a
  122. # given descriptor to initialize a concrete protocol message
  123. # class.
  124. concrete_class_attr_name = '_concrete_class'
  125. if not hasattr(descriptor, concrete_class_attr_name):
  126. setattr(descriptor, concrete_class_attr_name, cls)
  127. cls._known_extensions = []
  128. _AddEnumValues(descriptor, cls)
  129. _AddInitMethod(descriptor, cls)
  130. _AddPropertiesForFields(descriptor, cls)
  131. _AddPropertiesForExtensions(descriptor, cls)
  132. _AddStaticMethods(cls)
  133. _AddMessageMethods(descriptor, cls)
  134. _AddPrivateHelperMethods(cls)
  135. superclass = super(GeneratedProtocolMessageType, cls)
  136. superclass.__init__(name, bases, dictionary)
  137. # Stateless helpers for GeneratedProtocolMessageType below.
  138. # Outside clients should not access these directly.
  139. #
  140. # I opted not to make any of these methods on the metaclass, to make it more
  141. # clear that I'm not really using any state there and to keep clients from
  142. # thinking that they have direct access to these construction helpers.
  143. def _PropertyName(proto_field_name):
  144. """Returns the name of the public property attribute which
  145. clients can use to get and (in some cases) set the value
  146. of a protocol message field.
  147. Args:
  148. proto_field_name: The protocol message field name, exactly
  149. as it appears (or would appear) in a .proto file.
  150. """
  151. # TODO(robinson): Escape Python keywords (e.g., yield), and test this support.
  152. # nnorwitz makes my day by writing:
  153. # """
  154. # FYI. See the keyword module in the stdlib. This could be as simple as:
  155. #
  156. # if keyword.iskeyword(proto_field_name):
  157. # return proto_field_name + "_"
  158. # return proto_field_name
  159. # """
  160. return proto_field_name
  161. def _ValueFieldName(proto_field_name):
  162. """Returns the name of the (internal) instance attribute which objects
  163. should use to store the current value for a given protocol message field.
  164. Args:
  165. proto_field_name: The protocol message field name, exactly
  166. as it appears (or would appear) in a .proto file.
  167. """
  168. return '_value_' + proto_field_name
  169. def _HasFieldName(proto_field_name):
  170. """Returns the name of the (internal) instance attribute which
  171. objects should use to store a boolean telling whether this field
  172. is explicitly set or not.
  173. Args:
  174. proto_field_name: The protocol message field name, exactly
  175. as it appears (or would appear) in a .proto file.
  176. """
  177. return '_has_' + proto_field_name
  178. def _AddSlots(message_descriptor, dictionary):
  179. """Adds a __slots__ entry to dictionary, containing the names of all valid
  180. attributes for this message type.
  181. Args:
  182. message_descriptor: A Descriptor instance describing this message type.
  183. dictionary: Class dictionary to which we'll add a '__slots__' entry.
  184. """
  185. field_names = [_ValueFieldName(f.name) for f in message_descriptor.fields]
  186. field_names.extend(_HasFieldName(f.name) for f in message_descriptor.fields
  187. if f.label != _FieldDescriptor.LABEL_REPEATED)
  188. field_names.extend(('Extensions',
  189. '_cached_byte_size',
  190. '_cached_byte_size_dirty',
  191. '_called_transition_to_nonempty',
  192. '_listener',
  193. '_lock', '__weakref__'))
  194. dictionary['__slots__'] = field_names
  195. def _AddClassAttributesForNestedExtensions(descriptor, dictionary):
  196. extension_dict = descriptor.extensions_by_name
  197. for extension_name, extension_field in extension_dict.iteritems():
  198. assert extension_name not in dictionary
  199. dictionary[extension_name] = extension_field
  200. def _AddEnumValues(descriptor, cls):
  201. """Sets class-level attributes for all enum fields defined in this message.
  202. Args:
  203. descriptor: Descriptor object for this message type.
  204. cls: Class we're constructing for this message type.
  205. """
  206. for enum_type in descriptor.enum_types:
  207. for enum_value in enum_type.values:
  208. setattr(cls, enum_value.name, enum_value.number)
  209. def _DefaultValueForField(message, field):
  210. """Returns a default value for a field.
  211. Args:
  212. message: Message instance containing this field, or a weakref proxy
  213. of same.
  214. field: FieldDescriptor object for this field.
  215. Returns: A default value for this field. May refer back to |message|
  216. via a weak reference.
  217. """
  218. # TODO(robinson): Only the repeated fields need a reference to 'message' (so
  219. # that they can set the 'has' bit on the containing Message when someone
  220. # append()s a value). We could special-case this, and avoid an extra
  221. # function call on __init__() and Clear() for non-repeated fields.
  222. # TODO(robinson): Find a better place for the default value assertion in this
  223. # function. No need to repeat them every time the client calls Clear('foo').
  224. # (We should probably just assert these things once and as early as possible,
  225. # by tightening checking in the descriptor classes.)
  226. if field.label == _FieldDescriptor.LABEL_REPEATED:
  227. if field.default_value != []:
  228. raise ValueError('Repeated field default value not empty list: %s' % (
  229. field.default_value))
  230. listener = _Listener(message, None)
  231. if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  232. # We can't look at _concrete_class yet since it might not have
  233. # been set. (Depends on order in which we initialize the classes).
  234. return containers.RepeatedCompositeFieldContainer(
  235. listener, field.message_type)
  236. else:
  237. return containers.RepeatedScalarFieldContainer(
  238. listener, type_checkers.GetTypeChecker(field.cpp_type, field.type))
  239. if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  240. assert field.default_value is None
  241. return field.default_value
  242. def _AddInitMethod(message_descriptor, cls):
  243. """Adds an __init__ method to cls."""
  244. fields = message_descriptor.fields
  245. def init(self):
  246. self._cached_byte_size = 0
  247. self._cached_byte_size_dirty = False
  248. self._listener = message_listener_mod.NullMessageListener()
  249. self._called_transition_to_nonempty = False
  250. # TODO(robinson): We should only create a lock if we really need one
  251. # in this class.
  252. self._lock = threading.Lock()
  253. for field in fields:
  254. default_value = _DefaultValueForField(self, field)
  255. python_field_name = _ValueFieldName(field.name)
  256. setattr(self, python_field_name, default_value)
  257. if field.label != _FieldDescriptor.LABEL_REPEATED:
  258. setattr(self, _HasFieldName(field.name), False)
  259. self.Extensions = _ExtensionDict(self, cls._known_extensions)
  260. init.__module__ = None
  261. init.__doc__ = None
  262. cls.__init__ = init
  263. def _AddPropertiesForFields(descriptor, cls):
  264. """Adds properties for all fields in this protocol message type."""
  265. for field in descriptor.fields:
  266. _AddPropertiesForField(field, cls)
  267. def _AddPropertiesForField(field, cls):
  268. """Adds a public property for a protocol message field.
  269. Clients can use this property to get and (in the case
  270. of non-repeated scalar fields) directly set the value
  271. of a protocol message field.
  272. Args:
  273. field: A FieldDescriptor for this field.
  274. cls: The class we're constructing.
  275. """
  276. # Catch it if we add other types that we should
  277. # handle specially here.
  278. assert _FieldDescriptor.MAX_CPPTYPE == 10
  279. constant_name = field.name.upper() + "_FIELD_NUMBER"
  280. setattr(cls, constant_name, field.number)
  281. if field.label == _FieldDescriptor.LABEL_REPEATED:
  282. _AddPropertiesForRepeatedField(field, cls)
  283. elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  284. _AddPropertiesForNonRepeatedCompositeField(field, cls)
  285. else:
  286. _AddPropertiesForNonRepeatedScalarField(field, cls)
  287. def _AddPropertiesForRepeatedField(field, cls):
  288. """Adds a public property for a "repeated" protocol message field. Clients
  289. can use this property to get the value of the field, which will be either a
  290. _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see
  291. below).
  292. Note that when clients add values to these containers, we perform
  293. type-checking in the case of repeated scalar fields, and we also set any
  294. necessary "has" bits as a side-effect.
  295. Args:
  296. field: A FieldDescriptor for this field.
  297. cls: The class we're constructing.
  298. """
  299. proto_field_name = field.name
  300. python_field_name = _ValueFieldName(proto_field_name)
  301. property_name = _PropertyName(proto_field_name)
  302. def getter(self):
  303. return getattr(self, python_field_name)
  304. getter.__module__ = None
  305. getter.__doc__ = 'Getter for %s.' % proto_field_name
  306. # We define a setter just so we can throw an exception with a more
  307. # helpful error message.
  308. def setter(self, new_value):
  309. raise AttributeError('Assignment not allowed to repeated field '
  310. '"%s" in protocol message object.' % proto_field_name)
  311. doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name
  312. setattr(cls, property_name, property(getter, setter, doc=doc))
  313. def _AddPropertiesForNonRepeatedScalarField(field, cls):
  314. """Adds a public property for a nonrepeated, scalar protocol message field.
  315. Clients can use this property to get and directly set the value of the field.
  316. Note that when the client sets the value of a field by using this property,
  317. all necessary "has" bits are set as a side-effect, and we also perform
  318. type-checking.
  319. Args:
  320. field: A FieldDescriptor for this field.
  321. cls: The class we're constructing.
  322. """
  323. proto_field_name = field.name
  324. python_field_name = _ValueFieldName(proto_field_name)
  325. has_field_name = _HasFieldName(proto_field_name)
  326. property_name = _PropertyName(proto_field_name)
  327. type_checker = type_checkers.GetTypeChecker(field.cpp_type, field.type)
  328. def getter(self):
  329. return getattr(self, python_field_name)
  330. getter.__module__ = None
  331. getter.__doc__ = 'Getter for %s.' % proto_field_name
  332. def setter(self, new_value):
  333. type_checker.CheckValue(new_value)
  334. setattr(self, has_field_name, True)
  335. self._MarkByteSizeDirty()
  336. self._MaybeCallTransitionToNonemptyCallback()
  337. setattr(self, python_field_name, new_value)
  338. setter.__module__ = None
  339. setter.__doc__ = 'Setter for %s.' % proto_field_name
  340. # Add a property to encapsulate the getter/setter.
  341. doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name
  342. setattr(cls, property_name, property(getter, setter, doc=doc))
  343. def _AddPropertiesForNonRepeatedCompositeField(field, cls):
  344. """Adds a public property for a nonrepeated, composite protocol message field.
  345. A composite field is a "group" or "message" field.
  346. Clients can use this property to get the value of the field, but cannot
  347. assign to the property directly.
  348. Args:
  349. field: A FieldDescriptor for this field.
  350. cls: The class we're constructing.
  351. """
  352. # TODO(robinson): Remove duplication with similar method
  353. # for non-repeated scalars.
  354. proto_field_name = field.name
  355. python_field_name = _ValueFieldName(proto_field_name)
  356. has_field_name = _HasFieldName(proto_field_name)
  357. property_name = _PropertyName(proto_field_name)
  358. message_type = field.message_type
  359. def getter(self):
  360. # TODO(robinson): Appropriately scary note about double-checked locking.
  361. field_value = getattr(self, python_field_name)
  362. if field_value is None:
  363. self._lock.acquire()
  364. try:
  365. field_value = getattr(self, python_field_name)
  366. if field_value is None:
  367. field_class = message_type._concrete_class
  368. field_value = field_class()
  369. field_value._SetListener(_Listener(self, has_field_name))
  370. setattr(self, python_field_name, field_value)
  371. finally:
  372. self._lock.release()
  373. return field_value
  374. getter.__module__ = None
  375. getter.__doc__ = 'Getter for %s.' % proto_field_name
  376. # We define a setter just so we can throw an exception with a more
  377. # helpful error message.
  378. def setter(self, new_value):
  379. raise AttributeError('Assignment not allowed to composite field '
  380. '"%s" in protocol message object.' % proto_field_name)
  381. # Add a property to encapsulate the getter.
  382. doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name
  383. setattr(cls, property_name, property(getter, setter, doc=doc))
  384. def _AddPropertiesForExtensions(descriptor, cls):
  385. """Adds properties for all fields in this protocol message type."""
  386. extension_dict = descriptor.extensions_by_name
  387. for extension_name, extension_field in extension_dict.iteritems():
  388. constant_name = extension_name.upper() + "_FIELD_NUMBER"
  389. setattr(cls, constant_name, extension_field.number)
  390. def _AddStaticMethods(cls):
  391. # TODO(robinson): This probably needs to be thread-safe(?)
  392. def RegisterExtension(extension_handle):
  393. extension_handle.containing_type = cls.DESCRIPTOR
  394. cls._known_extensions.append(extension_handle)
  395. cls.RegisterExtension = staticmethod(RegisterExtension)
  396. def FromString(s):
  397. message = cls()
  398. message.MergeFromString(s)
  399. return message
  400. cls.FromString = staticmethod(FromString)
  401. def _AddListFieldsMethod(message_descriptor, cls):
  402. """Helper for _AddMessageMethods()."""
  403. # Ensure that we always list in ascending field-number order.
  404. # For non-extension fields, we can do the sort once, here, at import-time.
  405. # For extensions, we sort on each ListFields() call, though
  406. # we could do better if we have to.
  407. fields = sorted(message_descriptor.fields, key=lambda f: f.number)
  408. has_field_names = (_HasFieldName(f.name) for f in fields)
  409. value_field_names = (_ValueFieldName(f.name) for f in fields)
  410. triplets = zip(has_field_names, value_field_names, fields)
  411. def ListFields(self):
  412. # We need to list all extension and non-extension fields
  413. # together, in sorted order by field number.
  414. # Step 0: Get an iterator over all "set" non-extension fields,
  415. # sorted by field number.
  416. # This iterator yields (field_number, field_descriptor, value) tuples.
  417. def SortedSetFieldsIter():
  418. # Note that triplets is already sorted by field number.
  419. for has_field_name, value_field_name, field_descriptor in triplets:
  420. if field_descriptor.label == _FieldDescriptor.LABEL_REPEATED:
  421. value = getattr(self, _ValueFieldName(field_descriptor.name))
  422. if len(value) > 0:
  423. yield (field_descriptor.number, field_descriptor, value)
  424. elif getattr(self, _HasFieldName(field_descriptor.name)):
  425. value = getattr(self, _ValueFieldName(field_descriptor.name))
  426. yield (field_descriptor.number, field_descriptor, value)
  427. sorted_fields = SortedSetFieldsIter()
  428. # Step 1: Get an iterator over all "set" extension fields,
  429. # sorted by field number.
  430. # This iterator ALSO yields (field_number, field_descriptor, value) tuples.
  431. # TODO(robinson): It's not necessary to repeat this with each
  432. # serialization call. We can do better.
  433. sorted_extension_fields = sorted(
  434. [(f.number, f, v) for f, v in self.Extensions._ListSetExtensions()])
  435. # Step 2: Create a composite iterator that merges the extension-
  436. # and non-extension fields, and that still yields fields in
  437. # sorted order.
  438. all_set_fields = _ImergeSorted(sorted_fields, sorted_extension_fields)
  439. # Step 3: Strip off the field numbers and return.
  440. return [field[1:] for field in all_set_fields]
  441. cls.ListFields = ListFields
  442. def _AddHasFieldMethod(cls):
  443. """Helper for _AddMessageMethods()."""
  444. def HasField(self, field_name):
  445. try:
  446. return getattr(self, _HasFieldName(field_name))
  447. except AttributeError:
  448. raise ValueError('Protocol message has no "%s" field.' % field_name)
  449. cls.HasField = HasField
  450. def _AddClearFieldMethod(cls):
  451. """Helper for _AddMessageMethods()."""
  452. def ClearField(self, field_name):
  453. try:
  454. field = self.DESCRIPTOR.fields_by_name[field_name]
  455. except KeyError:
  456. raise ValueError('Protocol message has no "%s" field.' % field_name)
  457. proto_field_name = field.name
  458. python_field_name = _ValueFieldName(proto_field_name)
  459. has_field_name = _HasFieldName(proto_field_name)
  460. default_value = _DefaultValueForField(self, field)
  461. if field.label == _FieldDescriptor.LABEL_REPEATED:
  462. self._MarkByteSizeDirty()
  463. else:
  464. if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  465. old_field_value = getattr(self, python_field_name)
  466. if old_field_value is not None:
  467. # Snip the old object out of the object tree.
  468. old_field_value._SetListener(None)
  469. if getattr(self, has_field_name):
  470. setattr(self, has_field_name, False)
  471. # Set dirty bit on ourself and parents only if
  472. # we're actually changing state.
  473. self._MarkByteSizeDirty()
  474. setattr(self, python_field_name, default_value)
  475. cls.ClearField = ClearField
  476. def _AddClearExtensionMethod(cls):
  477. """Helper for _AddMessageMethods()."""
  478. def ClearExtension(self, extension_handle):
  479. self.Extensions._ClearExtension(extension_handle)
  480. cls.ClearExtension = ClearExtension
  481. def _AddClearMethod(cls):
  482. """Helper for _AddMessageMethods()."""
  483. def Clear(self):
  484. # Clear fields.
  485. fields = self.DESCRIPTOR.fields
  486. for field in fields:
  487. self.ClearField(field.name)
  488. # Clear extensions.
  489. extensions = self.Extensions._ListSetExtensions()
  490. for extension in extensions:
  491. self.ClearExtension(extension[0])
  492. cls.Clear = Clear
  493. def _AddHasExtensionMethod(cls):
  494. """Helper for _AddMessageMethods()."""
  495. def HasExtension(self, extension_handle):
  496. return self.Extensions._HasExtension(extension_handle)
  497. cls.HasExtension = HasExtension
  498. def _AddEqualsMethod(message_descriptor, cls):
  499. """Helper for _AddMessageMethods()."""
  500. def __eq__(self, other):
  501. if (not isinstance(other, message_mod.Message) or
  502. other.DESCRIPTOR != self.DESCRIPTOR):
  503. return False
  504. if self is other:
  505. return True
  506. # Compare all fields contained directly in this message.
  507. for field_descriptor in message_descriptor.fields:
  508. label = field_descriptor.label
  509. property_name = _PropertyName(field_descriptor.name)
  510. # Non-repeated field equality requires matching "has" bits as well
  511. # as having an equal value.
  512. if label != _FieldDescriptor.LABEL_REPEATED:
  513. self_has = self.HasField(property_name)
  514. other_has = other.HasField(property_name)
  515. if self_has != other_has:
  516. return False
  517. if not self_has:
  518. # If the "has" bit for this field is False, we must stop here.
  519. # Otherwise we will recurse forever on recursively-defined protos.
  520. continue
  521. if getattr(self, property_name) != getattr(other, property_name):
  522. return False
  523. # Compare the extensions present in both messages.
  524. return self.Extensions == other.Extensions
  525. cls.__eq__ = __eq__
  526. def _AddSetListenerMethod(cls):
  527. """Helper for _AddMessageMethods()."""
  528. def SetListener(self, listener):
  529. if listener is None:
  530. self._listener = message_listener_mod.NullMessageListener()
  531. else:
  532. self._listener = listener
  533. cls._SetListener = SetListener
  534. def _BytesForNonRepeatedElement(value, field_number, field_type):
  535. """Returns the number of bytes needed to serialize a non-repeated element.
  536. The returned byte count includes space for tag information and any
  537. other additional space associated with serializing value.
  538. Args:
  539. value: Value we're serializing.
  540. field_number: Field number of this value. (Since the field number
  541. is stored as part of a varint-encoded tag, this has an impact
  542. on the total bytes required to serialize the value).
  543. field_type: The type of the field. One of the TYPE_* constants
  544. within FieldDescriptor.
  545. """
  546. try:
  547. fn = type_checkers.TYPE_TO_BYTE_SIZE_FN[field_type]
  548. return fn(field_number, value)
  549. except KeyError:
  550. raise message_mod.EncodeError('Unrecognized field type: %d' % field_type)
  551. def _AddByteSizeMethod(message_descriptor, cls):
  552. """Helper for _AddMessageMethods()."""
  553. def BytesForField(message, field, value):
  554. """Returns the number of bytes required to serialize a single field
  555. in message. The field may be repeated or not, composite or not.
  556. Args:
  557. message: The Message instance containing a field of the given type.
  558. field: A FieldDescriptor describing the field of interest.
  559. value: The value whose byte size we're interested in.
  560. Returns: The number of bytes required to serialize the current value
  561. of "field" in "message", including space for tags and any other
  562. necessary information.
  563. """
  564. if _MessageSetField(field):
  565. return wire_format.MessageSetItemByteSize(field.number, value)
  566. field_number, field_type = field.number, field.type
  567. # Repeated fields.
  568. if field.label == _FieldDescriptor.LABEL_REPEATED:
  569. elements = value
  570. else:
  571. elements = [value]
  572. if field.GetOptions().packed:
  573. content_size = _ContentBytesForPackedField(message, field, elements)
  574. if content_size:
  575. tag_size = wire_format.TagByteSize(field_number)
  576. length_size = wire_format.Int32ByteSizeNoTag(content_size)
  577. return tag_size + length_size + content_size
  578. else:
  579. return 0
  580. else:
  581. return sum(_BytesForNonRepeatedElement(element, field_number, field_type)
  582. for element in elements)
  583. def _ContentBytesForPackedField(self, field, value):
  584. """Returns the number of bytes required to serialize the actual
  585. content of a packed field (not including the tag or the encoding
  586. of the length.
  587. Args:
  588. self: The Message instance containing a field of the given type.
  589. field: A FieldDescriptor describing the field of interest.
  590. value: The value whose byte size we're interested in.
  591. Returns: The number of bytes required to serialize the current value
  592. of the packed "field" in "message", excluding space for tags and the
  593. length encoding.
  594. """
  595. size = sum(_BytesForNonRepeatedElement(element, field.number, field.type)
  596. for element in value)
  597. # In the packed case, there are no per element tags.
  598. return size - wire_format.TagByteSize(field.number) * len(value)
  599. fields = message_descriptor.fields
  600. has_field_names = (_HasFieldName(f.name) for f in fields)
  601. zipped = zip(has_field_names, fields)
  602. def ByteSize(self):
  603. if not self._cached_byte_size_dirty:
  604. return self._cached_byte_size
  605. size = 0
  606. # Hardcoded fields first.
  607. for has_field_name, field in zipped:
  608. if (field.label == _FieldDescriptor.LABEL_REPEATED
  609. or getattr(self, has_field_name)):
  610. value = getattr(self, _ValueFieldName(field.name))
  611. size += BytesForField(self, field, value)
  612. # Extensions next.
  613. for field, value in self.Extensions._ListSetExtensions():
  614. size += BytesForField(self, field, value)
  615. self._cached_byte_size = size
  616. self._cached_byte_size_dirty = False
  617. return size
  618. cls._ContentBytesForPackedField = _ContentBytesForPackedField
  619. cls.ByteSize = ByteSize
  620. def _MessageSetField(field_descriptor):
  621. """Checks if a field should be serialized using the message set wire format.
  622. Args:
  623. field_descriptor: Descriptor of the field.
  624. Returns:
  625. True if the field should be serialized using the message set wire format,
  626. false otherwise.
  627. """
  628. return (field_descriptor.is_extension and
  629. field_descriptor.label != _FieldDescriptor.LABEL_REPEATED and
  630. field_descriptor.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
  631. field_descriptor.containing_type.GetOptions().message_set_wire_format)
  632. def _SerializeValueToEncoder(value, field_number, field_descriptor, encoder):
  633. """Appends the serialization of a single value to encoder.
  634. Args:
  635. value: Value to serialize.
  636. field_number: Field number of this value.
  637. field_descriptor: Descriptor of the field to serialize.
  638. encoder: encoder.Encoder object to which we should serialize this value.
  639. """
  640. if _MessageSetField(field_descriptor):
  641. encoder.AppendMessageSetItem(field_number, value)
  642. return
  643. try:
  644. method = type_checkers.TYPE_TO_SERIALIZE_METHOD[field_descriptor.type]
  645. method(encoder, field_number, value)
  646. except KeyError:
  647. raise message_mod.EncodeError('Unrecognized field type: %d' %
  648. field_descriptor.type)
  649. def _ImergeSorted(*streams):
  650. """Merges N sorted iterators into a single sorted iterator.
  651. Each element in streams must be an iterable that yields
  652. its elements in sorted order, and the elements contained
  653. in each stream must all be comparable.
  654. There may be repeated elements in the component streams or
  655. across the streams; the repeated elements will all be repeated
  656. in the merged iterator as well.
  657. I believe that the heapq module at HEAD in the Python
  658. sources has a method like this, but for now we roll our own.
  659. """
  660. iters = [iter(stream) for stream in streams]
  661. heap = []
  662. for index, it in enumerate(iters):
  663. try:
  664. heap.append((it.next(), index))
  665. except StopIteration:
  666. pass
  667. heapq.heapify(heap)
  668. while heap:
  669. smallest_value, idx = heap[0]
  670. yield smallest_value
  671. try:
  672. next_element = iters[idx].next()
  673. heapq.heapreplace(heap, (next_element, idx))
  674. except StopIteration:
  675. heapq.heappop(heap)
  676. def _AddSerializeToStringMethod(message_descriptor, cls):
  677. """Helper for _AddMessageMethods()."""
  678. def SerializeToString(self):
  679. # Check if the message has all of its required fields set.
  680. errors = []
  681. if not _InternalIsInitialized(self, errors):
  682. raise message_mod.EncodeError('\n'.join(errors))
  683. return self.SerializePartialToString()
  684. cls.SerializeToString = SerializeToString
  685. def _AddSerializePartialToStringMethod(message_descriptor, cls):
  686. """Helper for _AddMessageMethods()."""
  687. Encoder = encoder.Encoder
  688. def SerializePartialToString(self):
  689. encoder = Encoder()
  690. # We need to serialize all extension and non-extension fields
  691. # together, in sorted order by field number.
  692. for field_descriptor, field_value in self.ListFields():
  693. if field_descriptor.label == _FieldDescriptor.LABEL_REPEATED:
  694. repeated_value = field_value
  695. else:
  696. repeated_value = [field_value]
  697. if field_descriptor.GetOptions().packed:
  698. # First, write the field number and WIRETYPE_LENGTH_DELIMITED.
  699. field_number = field_descriptor.number
  700. encoder.AppendTag(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  701. # Next, write the number of bytes.
  702. content_bytes = self._ContentBytesForPackedField(
  703. field_descriptor, field_value)
  704. encoder.AppendInt32NoTag(content_bytes)
  705. # Finally, write the actual values.
  706. try:
  707. method = type_checkers.TYPE_TO_NOTAG_SERIALIZE_METHOD[
  708. field_descriptor.type]
  709. for value in repeated_value:
  710. method(encoder, value)
  711. except KeyError:
  712. raise message_mod.EncodeError('Unrecognized field type: %d' %
  713. field_descriptor.type)
  714. else:
  715. for element in repeated_value:
  716. _SerializeValueToEncoder(element, field_descriptor.number,
  717. field_descriptor, encoder)
  718. return encoder.ToString()
  719. cls.SerializePartialToString = SerializePartialToString
  720. def _WireTypeForFieldType(field_type):
  721. """Given a field type, returns the expected wire type."""
  722. try:
  723. return type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_type]
  724. except KeyError:
  725. raise message_mod.DecodeError('Unknown field type: %d' % field_type)
  726. def _WireTypeForField(field_descriptor):
  727. """Given a field descriptor, returns the expected wire type."""
  728. if field_descriptor.GetOptions().packed:
  729. return wire_format.WIRETYPE_LENGTH_DELIMITED
  730. else:
  731. return _WireTypeForFieldType(field_descriptor.type)
  732. def _RecursivelyMerge(field_number, field_type, decoder, message):
  733. """Decodes a message from decoder into message.
  734. message is either a group or a nested message within some containing
  735. protocol message. If it's a group, we use the group protocol to
  736. deserialize, and if it's a nested message, we use the nested-message
  737. protocol.
  738. Args:
  739. field_number: The field number of message in its enclosing protocol buffer.
  740. field_type: The field type of message. Must be either TYPE_MESSAGE
  741. or TYPE_GROUP.
  742. decoder: Decoder to read from.
  743. message: Message to deserialize into.
  744. """
  745. if field_type == _FieldDescriptor.TYPE_MESSAGE:
  746. decoder.ReadMessageInto(message)
  747. elif field_type == _FieldDescriptor.TYPE_GROUP:
  748. decoder.ReadGroupInto(field_number, message)
  749. else:
  750. raise message_mod.DecodeError('Unexpected field type: %d' % field_type)
  751. def _DeserializeScalarFromDecoder(field_type, decoder):
  752. """Deserializes a scalar of the requested type from decoder. field_type must
  753. be a scalar (non-group, non-message) FieldDescriptor.FIELD_* constant.
  754. """
  755. try:
  756. method = type_checkers.TYPE_TO_DESERIALIZE_METHOD[field_type]
  757. return method(decoder)
  758. except KeyError:
  759. raise message_mod.DecodeError('Unrecognized field type: %d' % field_type)
  760. def _SkipField(field_number, wire_type, decoder):
  761. """Skips a field with the specified wire type.
  762. Args:
  763. field_number: Tag number of the field to skip.
  764. wire_type: Wire type of the field to skip.
  765. decoder: Decoder used to deserialize the messsage. It must be positioned
  766. just after reading the the tag and wire type of the field.
  767. """
  768. if wire_type == wire_format.WIRETYPE_VARINT:
  769. decoder.ReadUInt64()
  770. elif wire_type == wire_format.WIRETYPE_FIXED64:
  771. decoder.ReadFixed64()
  772. elif wire_type == wire_format.WIRETYPE_LENGTH_DELIMITED:
  773. decoder.SkipBytes(decoder.ReadInt32())
  774. elif wire_type == wire_format.WIRETYPE_START_GROUP:
  775. _SkipGroup(field_number, decoder)
  776. elif wire_type == wire_format.WIRETYPE_END_GROUP:
  777. pass
  778. elif wire_type == wire_format.WIRETYPE_FIXED32:
  779. decoder.ReadFixed32()
  780. else:
  781. raise message_mod.DecodeError('Unexpected wire type: %d' % wire_type)
  782. def _SkipGroup(group_number, decoder):
  783. """Skips a nested group from the decoder.
  784. Args:
  785. group_number: Tag number of the group to skip.
  786. decoder: Decoder used to deserialize the message. It must be positioned
  787. exactly at the beginning of the message that should be skipped.
  788. """
  789. while True:
  790. field_number, wire_type = decoder.ReadFieldNumberAndWireType()
  791. if (wire_type == wire_format.WIRETYPE_END_GROUP and
  792. field_number == group_number):
  793. return
  794. _SkipField(field_number, wire_type, decoder)
  795. def _DeserializeMessageSetItem(message, decoder):
  796. """Deserializes a message using the message set wire format.
  797. Args:
  798. message: Message to be parsed to.
  799. decoder: The decoder to be used to deserialize encoded data. Note that the
  800. decoder should be positioned just after reading the START_GROUP tag that
  801. began the messageset item.
  802. """
  803. field_number, wire_type = decoder.ReadFieldNumberAndWireType()
  804. if wire_type != wire_format.WIRETYPE_VARINT or field_number != 2:
  805. raise message_mod.DecodeError(
  806. 'Incorrect message set wire format. '
  807. 'wire_type: %d, field_number: %d' % (wire_type, field_number))
  808. type_id = decoder.ReadInt32()
  809. field_number, wire_type = decoder.ReadFieldNumberAndWireType()
  810. if wire_type != wire_format.WIRETYPE_LENGTH_DELIMITED or field_number != 3:
  811. raise message_mod.DecodeError(
  812. 'Incorrect message set wire format. '
  813. 'wire_type: %d, field_number: %d' % (wire_type, field_number))
  814. extension_dict = message.Extensions
  815. extensions_by_number = extension_dict._AllExtensionsByNumber()
  816. if type_id not in extensions_by_number:
  817. _SkipField(field_number, wire_type, decoder)
  818. return
  819. field_descriptor = extensions_by_number[type_id]
  820. value = extension_dict[field_descriptor]
  821. decoder.ReadMessageInto(value)
  822. # Read the END_GROUP tag.
  823. field_number, wire_type = decoder.ReadFieldNumberAndWireType()
  824. if wire_type != wire_format.WIRETYPE_END_GROUP or field_number != 1:
  825. raise message_mod.DecodeError(
  826. 'Incorrect message set wire format. '
  827. 'wire_type: %d, field_number: %d' % (wire_type, field_number))
  828. def _DeserializeOneEntity(message_descriptor, message, decoder):
  829. """Deserializes the next wire entity from decoder into message.
  830. The next wire entity is either a scalar or a nested message, an
  831. element in a repeated field (the wire encoding in this case is the
  832. same), or a packed repeated field (in this case, the entire repeated
  833. field is read by a single call to _DeserializeOneEntity).
  834. Args:
  835. message_descriptor: A Descriptor instance describing all fields
  836. in message.
  837. message: The Message instance into which we're decoding our fields.
  838. decoder: The Decoder we're using to deserialize encoded data.
  839. Returns: The number of bytes read from decoder during this method.
  840. """
  841. initial_position = decoder.Position()
  842. field_number, wire_type = decoder.ReadFieldNumberAndWireType()
  843. extension_dict = message.Extensions
  844. extensions_by_number = extension_dict._AllExtensionsByNumber()
  845. if field_number in message_descriptor.fields_by_number:
  846. # Non-extension field.
  847. field_descriptor = message_descriptor.fields_by_number[field_number]
  848. value = getattr(message, _PropertyName(field_descriptor.name))
  849. def nonextension_setter_fn(scalar):
  850. setattr(message, _PropertyName(field_descriptor.name), scalar)
  851. scalar_setter_fn = nonextension_setter_fn
  852. elif field_number in extensions_by_number:
  853. # Extension field.
  854. field_descriptor = extensions_by_number[field_number]
  855. value = extension_dict[field_descriptor]
  856. def extension_setter_fn(scalar):
  857. extension_dict[field_descriptor] = scalar
  858. scalar_setter_fn = extension_setter_fn
  859. elif wire_type == wire_format.WIRETYPE_END_GROUP:
  860. # We assume we're being parsed as the group that's ended.
  861. return 0
  862. elif (wire_type == wire_format.WIRETYPE_START_GROUP and
  863. field_number == 1 and
  864. message_descriptor.GetOptions().message_set_wire_format):
  865. # A Message Set item.
  866. _DeserializeMessageSetItem(message, decoder)
  867. return decoder.Position() - initial_position
  868. else:
  869. _SkipField(field_number, wire_type, decoder)
  870. return decoder.Position() - initial_position
  871. # If we reach this point, we've identified the field as either
  872. # hardcoded or extension, and set |field_descriptor|, |scalar_setter_fn|,
  873. # and |value| appropriately. Now actually deserialize the thing.
  874. #
  875. # field_descriptor: Describes the field we're deserializing.
  876. # value: The value currently stored in the field to deserialize.
  877. # Used only if the field is composite and/or repeated.
  878. # scalar_setter_fn: A function F such that F(scalar) will
  879. # set a nonrepeated scalar value for this field. Used only
  880. # if this field is a nonrepeated scalar.
  881. field_number = field_descriptor.number
  882. expected_wire_type = _WireTypeForField(field_descriptor)
  883. if wire_type != expected_wire_type:
  884. # Need to fill in uninterpreted_bytes. Work for the next CL.
  885. raise RuntimeError('TODO(robinson): Wiretype mismatches not handled.')
  886. property_name = _PropertyName(field_descriptor.name)
  887. label = field_descriptor.label
  888. field_type = field_descriptor.type
  889. cpp_type = field_descriptor.cpp_type
  890. # Nonrepeated scalar. Just set the field directly.
  891. if (label != _FieldDescriptor.LABEL_REPEATED
  892. and cpp_type != _FieldDescriptor.CPPTYPE_MESSAGE):
  893. scalar_setter_fn(_DeserializeScalarFromDecoder(field_type, decoder))
  894. return decoder.Position() - initial_position
  895. # Nonrepeated composite. Recursively deserialize.
  896. if label != _FieldDescriptor.LABEL_REPEATED:
  897. composite = value
  898. _RecursivelyMerge(field_number, field_type, decoder, composite)
  899. return decoder.Position() - initial_position
  900. # Now we know we're dealing with a repeated field of some kind.
  901. element_list = value
  902. if cpp_type != _FieldDescriptor.CPPTYPE_MESSAGE:
  903. # Repeated scalar.
  904. if not field_descriptor.GetOptions().packed:
  905. element_list.append(_DeserializeScalarFromDecoder(field_type, decoder))
  906. return decoder.Position() - initial_position
  907. else:
  908. # Packed repeated field.
  909. length = _DeserializeScalarFromDecoder(
  910. _FieldDescriptor.TYPE_INT32, decoder)
  911. content_start = decoder.Position()
  912. while decoder.Position() - content_start < length:
  913. element_list.append(_DeserializeScalarFromDecoder(field_type, decoder))
  914. return decoder.Position() - content_start
  915. else:
  916. # Repeated composite.
  917. composite = element_list.add()
  918. _RecursivelyMerge(field_number, field_type, decoder, composite)
  919. return decoder.Position() - initial_position
  920. def _FieldOrExtensionValues(message, field_or_extension):
  921. """Retrieves the list of values for the specified field or extension.
  922. The target field or extension can be optional, required or repeated, but it
  923. must have value(s) set. The assumption is that the target field or extension
  924. is set (e.g. _HasFieldOrExtension holds true).
  925. Args:
  926. message: Message which contains the target field or extension.
  927. field_or_extension: Field or extension for which the list of values is
  928. required. Must be an instance of FieldDescriptor.
  929. Returns:
  930. A list of values for the specified field or extension. This list will only
  931. contain a single element if the field is non-repeated.
  932. """
  933. if field_or_extension.is_extension:
  934. value = message.Extensions[field_or_extension]
  935. else:
  936. value = getattr(message, _ValueFieldName(field_or_extension.name))
  937. if field_or_extension.label != _FieldDescriptor.LABEL_REPEATED:
  938. return [value]
  939. else:
  940. # In this case value is a list or repeated values.
  941. return value
  942. def _HasFieldOrExtension(message, field_or_extension):
  943. """Checks if a message has the specified field or extension set.
  944. The field or extension specified can be optional, required or repeated. If
  945. it is repeated, this function returns True. Otherwise it checks the has bit
  946. of the field or extension.
  947. Args:
  948. message: Message which contains the target field or extension.
  949. field_or_extension: Field or extension to check. This must be a
  950. FieldDescriptor instance.
  951. Returns:
  952. True if the message has a value set for the specified field or extension,
  953. or if the field or extension is repeated.
  954. """
  955. if field_or_extension.label == _FieldDescriptor.LABEL_REPEATED:
  956. return True
  957. if field_or_extension.is_extension:
  958. return message.HasExtension(field_or_extension)
  959. else:
  960. return message.HasField(field_or_extension.name)
  961. def _IsFieldOrExtensionInitialized(message, field, errors=None):
  962. """Checks if a message field or extension is initialized.
  963. Args:
  964. message: The message which contains the field or extension.
  965. field: Field or extension to check. This must be a FieldDescriptor instance.
  966. errors: Errors will be appended to it, if set to a meaningful value.
  967. Returns:
  968. True if the field/extension can be considered initialized.
  969. """
  970. # If the field is required and is not set, it isn't initialized.
  971. if field.label == _FieldDescriptor.LABEL_REQUIRED:
  972. if not _HasFieldOrExtension(message, field):
  973. if errors is not None:
  974. errors.append('Required field %s is not set.' % field.full_name)
  975. return False
  976. # If the field is optional and is not set, or if it
  977. # isn't a submessage then the field is initialized.
  978. if field.label == _FieldDescriptor.LABEL_OPTIONAL:
  979. if not _HasFieldOrExtension(message, field):
  980. return True
  981. if field.cpp_type != _FieldDescriptor.CPPTYPE_MESSAGE:
  982. return True
  983. # The field is set and is either a single or a repeated submessage.
  984. messages = _FieldOrExtensionValues(message, field)
  985. # If all submessages in this field are initialized, the field is
  986. # considered initialized.
  987. for message in messages:
  988. if not _InternalIsInitialized(message, errors):
  989. return False
  990. return True
  991. def _InternalIsInitialized(message, errors=None):
  992. """Checks if all required fields of a message are set.
  993. Args:
  994. message: The message to check.
  995. errors: If set, initialization errors will be appended to it.
  996. Returns:
  997. True iff the specified message has all required fields set.
  998. """
  999. fields_and_extensions = []
  1000. fields_and_extensions.extend(message.DESCRIPTOR.fields)
  1001. fields_and_extensions.extend(
  1002. [extension[0] for extension in message.Extensions._ListSetExtensions()])
  1003. for field_or_extension in fields_and_extensions:
  1004. if not _IsFieldOrExtensionInitialized(message, field_or_extension, errors):
  1005. return False
  1006. return True
  1007. def _AddMergeFromStringMethod(message_descriptor, cls):
  1008. """Helper for _AddMessageMethods()."""
  1009. Decoder = decoder.Decoder
  1010. def MergeFromString(self, serialized):
  1011. decoder = Decoder(serialized)
  1012. byte_count = 0
  1013. while not decoder.EndOfStream():
  1014. bytes_read = _DeserializeOneEntity(message_descriptor, self, decoder)
  1015. if not bytes_read:
  1016. break
  1017. byte_count += bytes_read
  1018. return byte_count
  1019. cls.MergeFromString = MergeFromString
  1020. def _AddIsInitializedMethod(cls):
  1021. """Adds the IsInitialized method to the protocol message class."""
  1022. cls.IsInitialized = _InternalIsInitialized
  1023. def _MergeFieldOrExtension(destination_msg, field, value):
  1024. """Merges a specified message field into another message."""
  1025. property_name = _PropertyName(field.name)
  1026. is_extension = field.is_extension
  1027. if not is_extension:
  1028. destination = getattr(destination_msg, property_name)
  1029. elif (field.label == _FieldDescriptor.LABEL_REPEATED or
  1030. field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE):
  1031. destination = destination_msg.Extensions[field]
  1032. # Case 1 - a composite field.
  1033. if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  1034. if field.label == _FieldDescriptor.LABEL_REPEATED:
  1035. for v in value:
  1036. destination.add().MergeFrom(v)
  1037. else:
  1038. destination.MergeFrom(value)
  1039. return
  1040. # Case 2 - a repeated field.
  1041. if field.label == _FieldDescriptor.LABEL_REPEATED:
  1042. for v in value:
  1043. destination.append(v)
  1044. return
  1045. # Case 3 - a singular field.
  1046. if is_extension:
  1047. destination_msg.Extensions[field] = value
  1048. else:
  1049. setattr(destination_msg, property_name, value)
  1050. def _AddMergeFromMethod(cls):
  1051. def MergeFrom(self, msg):
  1052. assert msg is not self
  1053. for field in msg.ListFields():
  1054. _MergeFieldOrExtension(self, field[0], field[1])
  1055. cls.MergeFrom = MergeFrom
  1056. def _AddMessageMethods(message_descriptor, cls):
  1057. """Adds implementations of all Message methods to cls."""
  1058. _AddListFieldsMethod(message_descriptor, cls)
  1059. _AddHasFieldMethod(cls)
  1060. _AddClearFieldMethod(cls)
  1061. _AddClearExtensionMethod(cls)
  1062. _AddClearMethod(cls)
  1063. _AddHasExtensionMethod(cls)
  1064. _AddEqualsMethod(message_descriptor, cls)
  1065. _AddSetListenerMethod(cls)
  1066. _AddByteSizeMethod(message_descriptor, cls)
  1067. _AddSerializeToStringMethod(message_descriptor, cls)
  1068. _AddSerializePartialToStringMethod(message_descriptor, cls)
  1069. _AddMergeFromStringMethod(message_descriptor, cls)
  1070. _AddIsInitializedMethod(cls)
  1071. _AddMergeFromMethod(cls)
  1072. def _AddPrivateHelperMethods(cls):
  1073. """Adds implementation of private helper methods to cls."""
  1074. def MaybeCallTransitionToNonemptyCallback(self):
  1075. """Calls self._listener.TransitionToNonempty() the first time this
  1076. method is called. On all subsequent calls, this is a no-op.
  1077. """
  1078. if not self._called_transition_to_nonempty:
  1079. self._listener.TransitionToNonempty()
  1080. self._called_transition_to_nonempty = True
  1081. cls._MaybeCallTransitionToNonemptyCallback = (
  1082. MaybeCallTransitionToNonemptyCallback)
  1083. def MarkByteSizeDirty(self):
  1084. """Sets the _cached_byte_size_dirty bit to true,
  1085. and propagates this to our listener iff this was a state change.
  1086. """
  1087. if not self._cached_byte_size_dirty:
  1088. self._cached_byte_size_dirty = True
  1089. self._listener.ByteSizeDirty()
  1090. cls._MarkByteSizeDirty = MarkByteSizeDirty
  1091. class _Listener(object):
  1092. """MessageListener implementation that a parent message registers with its
  1093. child message.
  1094. In order to support semantics like:
  1095. foo.bar.baz = 23
  1096. assert foo.HasField('bar')
  1097. ...child objects must have back references to their parents.
  1098. This helper class is at the heart of this support.
  1099. """
  1100. def __init__(self, parent_message, has_field_name):
  1101. """Args:
  1102. parent_message: The message whose _MaybeCallTransitionToNonemptyCallback()
  1103. and _MarkByteSizeDirty() methods we should call when we receive
  1104. TransitionToNonempty() and ByteSizeDirty() messages.
  1105. has_field_name: The name of the "has" field that we should set in
  1106. the parent message when we receive a TransitionToNonempty message,
  1107. or None if there's no "has" field to set. (This will be the case
  1108. for child objects in "repeated" fields).
  1109. """
  1110. # This listener establishes a back reference from a child (contained) object
  1111. # to its parent (containing) object. We make this a weak reference to avoid
  1112. # creating cyclic garbage when the client finishes with the 'parent' object
  1113. # in the tree.
  1114. if isinstance(parent_message, weakref.ProxyType):
  1115. self._parent_message_weakref = parent_message
  1116. else:
  1117. self._parent_message_weakref = weakref.proxy(parent_message)
  1118. self._has_field_name = has_field_name
  1119. def TransitionToNonempty(self):
  1120. try:
  1121. if self._has_field_name is not None:
  1122. setattr(self._parent_message_weakref, self._has_field_name, True)
  1123. # Propagate the signal to our parents iff this is the first field set.
  1124. self._parent_message_weakref._MaybeCallTransitionToNonemptyCallback()
  1125. except ReferenceError:
  1126. # We can get here if a client has kept a reference to a child object,
  1127. # and is now setting a field on it, but the child's parent has been
  1128. # garbage-collected. This is not an error.
  1129. pass
  1130. def ByteSizeDirty(self):
  1131. try:
  1132. self._parent_message_weakref._MarkByteSizeDirty()
  1133. except ReferenceError:
  1134. # Same as above.
  1135. pass
  1136. # TODO(robinson): Move elsewhere? This file is getting pretty ridiculous...
  1137. # TODO(robinson): Unify error handling of "unknown extension" crap.
  1138. # TODO(robinson): There's so much similarity between the way that
  1139. # extensions behave and the way that normal fields behave that it would
  1140. # be really nice to unify more code. It's not immediately obvious
  1141. # how to do this, though, and I'd rather get the full functionality
  1142. # implemented (and, crucially, get all the tests and specs fleshed out
  1143. # and passing), and then come back to this thorny unification problem.
  1144. # TODO(robinson): Support iteritems()-style iteration over all
  1145. # extensions with the "has" bits turned on?
  1146. class _ExtensionDict(object):
  1147. """Dict-like container for supporting an indexable "Extensions"
  1148. field on proto instances.
  1149. Note that in all cases we expect extension handles to be
  1150. FieldDescriptors.
  1151. """
  1152. class _ExtensionListener(object):
  1153. """Adapts an _ExtensionDict to behave as a MessageListener."""
  1154. def __init__(self, extension_dict, handle_id):
  1155. self._extension_dict = extension_dict
  1156. self._handle_id = handle_id
  1157. def TransitionToNonempty(self):
  1158. self._extension_dict._SubmessageTransitionedToNonempty(self._handle_id)
  1159. def ByteSizeDirty(self):
  1160. self._extension_dict._SubmessageByteSizeBecameDirty()
  1161. # TODO(robinson): Somewhere, we need to blow up if people
  1162. # try to register two extensions with the same field number.
  1163. # (And we need a test for this of course).
  1164. def __init__(self, extended_message, known_extensions):
  1165. """extended_message: Message instance for which we are the Extensions dict.
  1166. known_extensions: Iterable of known extension handles.
  1167. These must be FieldDescriptors.
  1168. """
  1169. # We keep a weak reference to extended_message, since
  1170. # it has a reference to this instance in turn.
  1171. self._extended_message = weakref.proxy(extended_message)
  1172. # We make a deep copy of known_extensions to avoid any
  1173. # thread-safety concerns, since the argument passed in
  1174. # is the global (class-level) dict of known extensions for
  1175. # this type of message, which could be modified at any time
  1176. # via a RegisterExtension() call.
  1177. #
  1178. # This dict maps from handle id to handle (a FieldDescriptor).
  1179. #
  1180. # XXX
  1181. # TODO(robinson): This isn't good enough. The client could
  1182. # instantiate an object in module A, then afterward import
  1183. # module B and pass the instance to B.Foo(). If B imports
  1184. # an extender of this proto and then tries to use it, B
  1185. # will get a KeyError, even though the extension *is* registered
  1186. # at the time of use.
  1187. # XXX
  1188. self._known_extensions = dict((id(e), e) for e in known_extensions)
  1189. # Read lock around self._values, which may be modified by multiple
  1190. # concurrent readers in the conceptually "const" __getitem__ method.
  1191. # So, we grab this lock in every "read-only" method to ensure
  1192. # that concurrent read access is safe without external locking.
  1193. self._lock = threading.Lock()
  1194. # Maps from extension handle ID to current value of that extension.
  1195. self._values = {}
  1196. # Maps from extension handle ID to a boolean "has" bit, but only
  1197. # for non-repeated extension fields.
  1198. keys = (id for id, extension in self._known_extensions.iteritems()
  1199. if extension.label != _FieldDescriptor.LABEL_REPEATED)
  1200. self._has_bits = dict.fromkeys(keys, False)
  1201. def __getitem__(self, extension_handle):
  1202. """Returns the current value of the given extension handle."""
  1203. # We don't care as much about keeping critical sections short in the
  1204. # extension support, since it's presumably much less of a common case.
  1205. self._lock.acquire()
  1206. try:
  1207. handle_id = id(extension_handle)
  1208. if handle_id not in self._known_extensions:
  1209. raise KeyError('Extension not known to this class')
  1210. if handle_id not in self._values:
  1211. self._AddMissingHandle(extension_handle, handle_id)
  1212. return self._values[handle_id]
  1213. finally:
  1214. self._lock.release()
  1215. def __eq__(self, other):
  1216. # We have to grab read locks since we're accessing _values
  1217. # in a "const" method. See the comment in the constructor.
  1218. if self is other:
  1219. return True
  1220. self._lock.acquire()
  1221. try:
  1222. other._lock.acquire()
  1223. try:
  1224. if self._has_bits != other._has_bits:
  1225. return False
  1226. # If there's a "has" bit, then only compare values where it is true.
  1227. for k, v in self._values.iteritems():
  1228. if self._has_bits.get(k, False) and v != other._values[k]:
  1229. return False
  1230. return True
  1231. finally:
  1232. other._lock.release()
  1233. finally:
  1234. self._lock.release()
  1235. def __ne__(self, other):
  1236. return not self == other
  1237. # Note that this is only meaningful for non-repeated, scalar extension
  1238. # fields. Note also that we may have to call
  1239. # MaybeCallTransitionToNonemptyCallback() when we do successfully set a field
  1240. # this way, to set any necssary "has" bits in the ancestors of the extended
  1241. # message.
  1242. def __setitem__(self, extension_handle, value):
  1243. """If extension_handle specifies a non-repeated, scalar extension
  1244. field, sets the value of that field.
  1245. """
  1246. handle_id = id(extension_handle)
  1247. if handle_id not in self._known_extensions:
  1248. raise KeyError('Extension not known to this class')
  1249. field = extension_handle # Just shorten the name.
  1250. if (field.label == _FieldDescriptor.LABEL_OPTIONAL
  1251. and field.cpp_type != _FieldDescriptor.CPPTYPE_MESSAGE):
  1252. # It's slightly wasteful to lookup the type checker each time,
  1253. # but we expect this to be a vanishingly uncommon case anyway.
  1254. type_checker = type_checkers.GetTypeChecker(field.cpp_type, field.type)
  1255. type_checker.CheckValue(value)
  1256. self._values[handle_id] = value
  1257. self._has_bits[handle_id] = True
  1258. self._extended_message._MarkByteSizeDirty()
  1259. self._extended_message._MaybeCallTransitionToNonemptyCallback()
  1260. else:
  1261. raise TypeError('Extension is repeated and/or a composite type.')
  1262. def _AddMissingHandle(self, extension_handle, handle_id):
  1263. """Helper internal to ExtensionDict."""
  1264. # Special handling for non-repeated message extensions, which (like
  1265. # normal fields of this kind) are initialized lazily.
  1266. # REQUIRES: _lock already held.
  1267. cpp_type = extension_handle.cpp_type
  1268. label = extension_handle.label
  1269. if (cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE
  1270. and label != _FieldDescriptor.LABEL_REPEATED):
  1271. self._AddMissingNonRepeatedCompositeHandle(extension_handle, handle_id)
  1272. else:
  1273. self._values[handle_id] = _DefaultValueForField(
  1274. self._extended_message, extension_handle)
  1275. def _AddMissingNonRepeatedCompositeHandle(self, extension_handle, handle_id):
  1276. """Helper internal to ExtensionDict."""
  1277. # REQUIRES: _lock already held.
  1278. value = extension_handle.message_type._concrete_class()
  1279. value._SetListener(_ExtensionDict._ExtensionListener(self, handle_id))
  1280. self._values[handle_id] = value
  1281. def _SubmessageTransitionedToNonempty(self, handle_id):
  1282. """Called when a submessage with a given handle id first transitions to
  1283. being nonempty. Called by _ExtensionListener.
  1284. """
  1285. assert handle_id in self._has_bits
  1286. self._has_bits[handle_id] = True
  1287. self._extended_message._MaybeCallTransitionToNonemptyCallback()
  1288. def _SubmessageByteSizeBecameDirty(self):
  1289. """Called whenever a submessage's cached byte size becomes invalid
  1290. (goes from being "clean" to being "dirty"). Called by _ExtensionListener.
  1291. """
  1292. self._extended_message._MarkByteSizeDirty()
  1293. # We may wish to widen the public interface of Message.Extensions
  1294. # to expose some of this private functionality in the future.
  1295. # For now, we make all this functionality module-private and just
  1296. # implement what we need for serialization/deserialization,
  1297. # HasField()/ClearField(), etc.
  1298. def _HasExtension(self, extension_handle):
  1299. """Method for internal use by this module.
  1300. Returns true iff we "have" this extension in the sense of the
  1301. "has" bit being set.
  1302. """
  1303. handle_id = id(extension_handle)
  1304. # Note that this is different from the other checks.
  1305. if handle_id not in self._has_bits:
  1306. raise KeyError('Extension not known to this class, or is repeated field.')
  1307. return self._has_bits[handle_id]
  1308. # Intentionally pretty similar to ClearField() above.
  1309. def _ClearExtension(self, extension_handle):
  1310. """Method for internal use by this module.
  1311. Clears the specified extension, unsetting its "has" bit.
  1312. """
  1313. handle_id = id(extension_handle)
  1314. if handle_id not in self._known_extensions:
  1315. raise KeyError('Extension not known to this class')
  1316. default_value = _DefaultValueForField(self._extended_message,
  1317. extension_handle)
  1318. if extension_handle.label == _FieldDescriptor.LABEL_REPEATED:
  1319. self._extended_message._MarkByteSizeDirty()
  1320. else:
  1321. cpp_type = extension_handle.cpp_type
  1322. if cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  1323. if handle_id in self._values:
  1324. # Future modifications to this object shouldn't set any
  1325. # "has" bits here.
  1326. self._values[handle_id]._SetListener(None)
  1327. if self._has_bits[handle_id]:
  1328. self._has_bits[handle_id] = False
  1329. self._extended_message._MarkByteSizeDirty()
  1330. if handle_id in self._values:
  1331. del self._values[handle_id]
  1332. def _ListSetExtensions(self):
  1333. """Method for internal use by this module.
  1334. Returns an sequence of all extensions that are currently "set"
  1335. in this extension dict. A "set" extension is a repeated extension,
  1336. or a non-repeated extension with its "has" bit set.
  1337. The returned sequence contains (field_descriptor, value) pairs,
  1338. where value is the current value of the extension with the given
  1339. field descriptor.
  1340. The sequence values are in arbitrary order.
  1341. """
  1342. self._lock.acquire() # Read-only methods must lock around self._values.
  1343. try:
  1344. set_extensions = []
  1345. for handle_id, value in self._values.iteritems():
  1346. handle = self._known_extensions[handle_id]
  1347. if (handle.label == _FieldDescriptor.LABEL_REPEATED
  1348. or self._has_bits[handle_id]):
  1349. set_extensions.append((handle, value))
  1350. return set_extensions
  1351. finally:
  1352. self._lock.release()
  1353. def _AllExtensionsByNumber(self):
  1354. """Method for internal use by this module.
  1355. Returns: A dict mapping field_number to (handle, field_descriptor),
  1356. for *all* registered extensions for this dict.
  1357. """
  1358. # TODO(robinson): Precompute and store this away. Note that we'll have to
  1359. # be careful when we move away from having _known_extensions as a
  1360. # deep-copied member of this object.
  1361. return dict((f.number, f) for f in self._known_extensions.itervalues())