reflection.py 62 KB

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