python_message.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # https://developers.google.com/protocol-buffers/
  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. # Keep it Python2.5 compatible for GAE.
  31. #
  32. # Copyright 2007 Google Inc. All Rights Reserved.
  33. #
  34. # This code is meant to work on Python 2.4 and above only.
  35. #
  36. # TODO(robinson): Helpers for verbose, common checks like seeing if a
  37. # descriptor's cpp_type is CPPTYPE_MESSAGE.
  38. """Contains a metaclass and helper functions used to create
  39. protocol message classes from Descriptor objects at runtime.
  40. Recall that a metaclass is the "type" of a class.
  41. (A class is to a metaclass what an instance is to a class.)
  42. In this case, we use the GeneratedProtocolMessageType metaclass
  43. to inject all the useful functionality into the classes
  44. output by the protocol compiler at compile-time.
  45. The upshot of all this is that the real implementation
  46. details for ALL pure-Python protocol buffers are *here in
  47. this file*.
  48. """
  49. __author__ = 'robinson@google.com (Will Robinson)'
  50. import sys
  51. if sys.version_info[0] < 3:
  52. try:
  53. from cStringIO import StringIO as BytesIO
  54. except ImportError:
  55. from StringIO import StringIO as BytesIO
  56. import copy_reg as copyreg
  57. _basestring = basestring
  58. else:
  59. from io import BytesIO
  60. import copyreg
  61. _basestring = str
  62. import struct
  63. import weakref
  64. # We use "as" to avoid name collisions with variables.
  65. from google.protobuf.internal import containers
  66. from google.protobuf.internal import decoder
  67. from google.protobuf.internal import encoder
  68. from google.protobuf.internal import enum_type_wrapper
  69. from google.protobuf.internal import message_listener as message_listener_mod
  70. from google.protobuf.internal import type_checkers
  71. from google.protobuf.internal import wire_format
  72. from google.protobuf import descriptor as descriptor_mod
  73. from google.protobuf import message as message_mod
  74. from google.protobuf import symbol_database
  75. from google.protobuf import text_format
  76. _FieldDescriptor = descriptor_mod.FieldDescriptor
  77. def NewMessage(bases, descriptor, dictionary):
  78. _AddClassAttributesForNestedExtensions(descriptor, dictionary)
  79. _AddSlots(descriptor, dictionary)
  80. return bases
  81. def InitMessage(descriptor, cls):
  82. cls._decoders_by_tag = {}
  83. cls._extensions_by_name = {}
  84. cls._extensions_by_number = {}
  85. if (descriptor.has_options and
  86. descriptor.GetOptions().message_set_wire_format):
  87. cls._decoders_by_tag[decoder.MESSAGE_SET_ITEM_TAG] = (
  88. decoder.MessageSetItemDecoder(cls._extensions_by_number), None)
  89. # Attach stuff to each FieldDescriptor for quick lookup later on.
  90. for field in descriptor.fields:
  91. _AttachFieldHelpers(cls, field)
  92. descriptor._concrete_class = cls # pylint: disable=protected-access
  93. _AddEnumValues(descriptor, cls)
  94. _AddInitMethod(descriptor, cls)
  95. _AddPropertiesForFields(descriptor, cls)
  96. _AddPropertiesForExtensions(descriptor, cls)
  97. _AddStaticMethods(cls)
  98. _AddMessageMethods(descriptor, cls)
  99. _AddPrivateHelperMethods(descriptor, cls)
  100. copyreg.pickle(cls, lambda obj: (cls, (), obj.__getstate__()))
  101. # Stateless helpers for GeneratedProtocolMessageType below.
  102. # Outside clients should not access these directly.
  103. #
  104. # I opted not to make any of these methods on the metaclass, to make it more
  105. # clear that I'm not really using any state there and to keep clients from
  106. # thinking that they have direct access to these construction helpers.
  107. def _PropertyName(proto_field_name):
  108. """Returns the name of the public property attribute which
  109. clients can use to get and (in some cases) set the value
  110. of a protocol message field.
  111. Args:
  112. proto_field_name: The protocol message field name, exactly
  113. as it appears (or would appear) in a .proto file.
  114. """
  115. # TODO(robinson): Escape Python keywords (e.g., yield), and test this support.
  116. # nnorwitz makes my day by writing:
  117. # """
  118. # FYI. See the keyword module in the stdlib. This could be as simple as:
  119. #
  120. # if keyword.iskeyword(proto_field_name):
  121. # return proto_field_name + "_"
  122. # return proto_field_name
  123. # """
  124. # Kenton says: The above is a BAD IDEA. People rely on being able to use
  125. # getattr() and setattr() to reflectively manipulate field values. If we
  126. # rename the properties, then every such user has to also make sure to apply
  127. # the same transformation. Note that currently if you name a field "yield",
  128. # you can still access it just fine using getattr/setattr -- it's not even
  129. # that cumbersome to do so.
  130. # TODO(kenton): Remove this method entirely if/when everyone agrees with my
  131. # position.
  132. return proto_field_name
  133. def _VerifyExtensionHandle(message, extension_handle):
  134. """Verify that the given extension handle is valid."""
  135. if not isinstance(extension_handle, _FieldDescriptor):
  136. raise KeyError('HasExtension() expects an extension handle, got: %s' %
  137. extension_handle)
  138. if not extension_handle.is_extension:
  139. raise KeyError('"%s" is not an extension.' % extension_handle.full_name)
  140. if not extension_handle.containing_type:
  141. raise KeyError('"%s" is missing a containing_type.'
  142. % extension_handle.full_name)
  143. if extension_handle.containing_type is not message.DESCRIPTOR:
  144. raise KeyError('Extension "%s" extends message type "%s", but this '
  145. 'message is of type "%s".' %
  146. (extension_handle.full_name,
  147. extension_handle.containing_type.full_name,
  148. message.DESCRIPTOR.full_name))
  149. def _AddSlots(message_descriptor, dictionary):
  150. """Adds a __slots__ entry to dictionary, containing the names of all valid
  151. attributes for this message type.
  152. Args:
  153. message_descriptor: A Descriptor instance describing this message type.
  154. dictionary: Class dictionary to which we'll add a '__slots__' entry.
  155. """
  156. dictionary['__slots__'] = ['_cached_byte_size',
  157. '_cached_byte_size_dirty',
  158. '_fields',
  159. '_unknown_fields',
  160. '_is_present_in_parent',
  161. '_listener',
  162. '_listener_for_children',
  163. '__weakref__',
  164. '_oneofs']
  165. def _IsMessageSetExtension(field):
  166. return (field.is_extension and
  167. field.containing_type.has_options and
  168. field.containing_type.GetOptions().message_set_wire_format and
  169. field.type == _FieldDescriptor.TYPE_MESSAGE and
  170. field.message_type == field.extension_scope and
  171. field.label == _FieldDescriptor.LABEL_OPTIONAL)
  172. def _IsMapField(field):
  173. return (field.type == _FieldDescriptor.TYPE_MESSAGE and
  174. field.message_type.has_options and
  175. field.message_type.GetOptions().map_entry)
  176. def _IsMessageMapField(field):
  177. value_type = field.message_type.fields_by_name["value"]
  178. return value_type.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE
  179. def _AttachFieldHelpers(cls, field_descriptor):
  180. is_repeated = (field_descriptor.label == _FieldDescriptor.LABEL_REPEATED)
  181. is_packable = (is_repeated and
  182. wire_format.IsTypePackable(field_descriptor.type))
  183. if not is_packable:
  184. is_packed = False
  185. elif field_descriptor.containing_type.syntax == "proto2":
  186. is_packed = (field_descriptor.has_options and
  187. field_descriptor.GetOptions().packed)
  188. else:
  189. has_packed_false = (field_descriptor.has_options and
  190. field_descriptor.GetOptions().HasField("packed") and
  191. field_descriptor.GetOptions().packed == False)
  192. is_packed = not has_packed_false
  193. is_map_entry = _IsMapField(field_descriptor)
  194. if is_map_entry:
  195. field_encoder = encoder.MapEncoder(field_descriptor)
  196. sizer = encoder.MapSizer(field_descriptor)
  197. elif _IsMessageSetExtension(field_descriptor):
  198. field_encoder = encoder.MessageSetItemEncoder(field_descriptor.number)
  199. sizer = encoder.MessageSetItemSizer(field_descriptor.number)
  200. else:
  201. field_encoder = type_checkers.TYPE_TO_ENCODER[field_descriptor.type](
  202. field_descriptor.number, is_repeated, is_packed)
  203. sizer = type_checkers.TYPE_TO_SIZER[field_descriptor.type](
  204. field_descriptor.number, is_repeated, is_packed)
  205. field_descriptor._encoder = field_encoder
  206. field_descriptor._sizer = sizer
  207. field_descriptor._default_constructor = _DefaultValueConstructorForField(
  208. field_descriptor)
  209. def AddDecoder(wiretype, is_packed):
  210. tag_bytes = encoder.TagBytes(field_descriptor.number, wiretype)
  211. decode_type = field_descriptor.type
  212. if (decode_type == _FieldDescriptor.TYPE_ENUM and
  213. type_checkers.SupportsOpenEnums(field_descriptor)):
  214. decode_type = _FieldDescriptor.TYPE_INT32
  215. oneof_descriptor = None
  216. if field_descriptor.containing_oneof is not None:
  217. oneof_descriptor = field_descriptor
  218. if is_map_entry:
  219. is_message_map = _IsMessageMapField(field_descriptor)
  220. field_decoder = decoder.MapDecoder(
  221. field_descriptor, _GetInitializeDefaultForMap(field_descriptor),
  222. is_message_map)
  223. else:
  224. field_decoder = type_checkers.TYPE_TO_DECODER[decode_type](
  225. field_descriptor.number, is_repeated, is_packed,
  226. field_descriptor, field_descriptor._default_constructor)
  227. cls._decoders_by_tag[tag_bytes] = (field_decoder, oneof_descriptor)
  228. AddDecoder(type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type],
  229. False)
  230. if is_repeated and wire_format.IsTypePackable(field_descriptor.type):
  231. # To support wire compatibility of adding packed = true, add a decoder for
  232. # packed values regardless of the field's options.
  233. AddDecoder(wire_format.WIRETYPE_LENGTH_DELIMITED, True)
  234. def _AddClassAttributesForNestedExtensions(descriptor, dictionary):
  235. extension_dict = descriptor.extensions_by_name
  236. for extension_name, extension_field in extension_dict.iteritems():
  237. assert extension_name not in dictionary
  238. dictionary[extension_name] = extension_field
  239. def _AddEnumValues(descriptor, cls):
  240. """Sets class-level attributes for all enum fields defined in this message.
  241. Also exporting a class-level object that can name enum values.
  242. Args:
  243. descriptor: Descriptor object for this message type.
  244. cls: Class we're constructing for this message type.
  245. """
  246. for enum_type in descriptor.enum_types:
  247. setattr(cls, enum_type.name, enum_type_wrapper.EnumTypeWrapper(enum_type))
  248. for enum_value in enum_type.values:
  249. setattr(cls, enum_value.name, enum_value.number)
  250. def _GetInitializeDefaultForMap(field):
  251. if field.label != _FieldDescriptor.LABEL_REPEATED:
  252. raise ValueError('map_entry set on non-repeated field %s' % (
  253. field.name))
  254. fields_by_name = field.message_type.fields_by_name
  255. key_checker = type_checkers.GetTypeChecker(fields_by_name['key'])
  256. value_field = fields_by_name['value']
  257. if _IsMessageMapField(field):
  258. def MakeMessageMapDefault(message):
  259. return containers.MessageMap(
  260. message._listener_for_children, value_field.message_type, key_checker)
  261. return MakeMessageMapDefault
  262. else:
  263. value_checker = type_checkers.GetTypeChecker(value_field)
  264. def MakePrimitiveMapDefault(message):
  265. return containers.ScalarMap(
  266. message._listener_for_children, key_checker, value_checker)
  267. return MakePrimitiveMapDefault
  268. def _DefaultValueConstructorForField(field):
  269. """Returns a function which returns a default value for a field.
  270. Args:
  271. field: FieldDescriptor object for this field.
  272. The returned function has one argument:
  273. message: Message instance containing this field, or a weakref proxy
  274. of same.
  275. That function in turn returns a default value for this field. The default
  276. value may refer back to |message| via a weak reference.
  277. """
  278. if _IsMapField(field):
  279. return _GetInitializeDefaultForMap(field)
  280. if field.label == _FieldDescriptor.LABEL_REPEATED:
  281. if field.has_default_value and field.default_value != []:
  282. raise ValueError('Repeated field default value not empty list: %s' % (
  283. field.default_value))
  284. if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  285. # We can't look at _concrete_class yet since it might not have
  286. # been set. (Depends on order in which we initialize the classes).
  287. message_type = field.message_type
  288. def MakeRepeatedMessageDefault(message):
  289. return containers.RepeatedCompositeFieldContainer(
  290. message._listener_for_children, field.message_type)
  291. return MakeRepeatedMessageDefault
  292. else:
  293. type_checker = type_checkers.GetTypeChecker(field)
  294. def MakeRepeatedScalarDefault(message):
  295. return containers.RepeatedScalarFieldContainer(
  296. message._listener_for_children, type_checker)
  297. return MakeRepeatedScalarDefault
  298. if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  299. # _concrete_class may not yet be initialized.
  300. message_type = field.message_type
  301. def MakeSubMessageDefault(message):
  302. result = message_type._concrete_class()
  303. result._SetListener(message._listener_for_children)
  304. if field.containing_oneof:
  305. message._UpdateOneofState(field)
  306. return result
  307. return MakeSubMessageDefault
  308. def MakeScalarDefault(message):
  309. # TODO(protobuf-team): This may be broken since there may not be
  310. # default_value. Combine with has_default_value somehow.
  311. return field.default_value
  312. return MakeScalarDefault
  313. def _ReraiseTypeErrorWithFieldName(message_name, field_name):
  314. """Re-raise the currently-handled TypeError with the field name added."""
  315. exc = sys.exc_info()[1]
  316. if len(exc.args) == 1 and type(exc) is TypeError:
  317. # simple TypeError; add field name to exception message
  318. exc = TypeError('%s for field %s.%s' % (str(exc), message_name, field_name))
  319. # re-raise possibly-amended exception with original traceback:
  320. raise type(exc)(exc, sys.exc_info()[2])
  321. def _AddInitMethod(message_descriptor, cls):
  322. """Adds an __init__ method to cls."""
  323. def _GetIntegerEnumValue(enum_type, value):
  324. """Convert a string or integer enum value to an integer.
  325. If the value is a string, it is converted to the enum value in
  326. enum_type with the same name. If the value is not a string, it's
  327. returned as-is. (No conversion or bounds-checking is done.)
  328. """
  329. if isinstance(value, _basestring):
  330. try:
  331. return enum_type.values_by_name[value].number
  332. except KeyError:
  333. raise ValueError('Enum type %s: unknown label "%s"' % (
  334. enum_type.full_name, value))
  335. return value
  336. def init(self, **kwargs):
  337. self._cached_byte_size = 0
  338. self._cached_byte_size_dirty = len(kwargs) > 0
  339. self._fields = {}
  340. # Contains a mapping from oneof field descriptors to the descriptor
  341. # of the currently set field in that oneof field.
  342. self._oneofs = {}
  343. # _unknown_fields is () when empty for efficiency, and will be turned into
  344. # a list if fields are added.
  345. self._unknown_fields = ()
  346. self._is_present_in_parent = False
  347. self._listener = message_listener_mod.NullMessageListener()
  348. self._listener_for_children = _Listener(self)
  349. for field_name, field_value in kwargs.iteritems():
  350. field = _GetFieldByName(message_descriptor, field_name)
  351. if field is None:
  352. raise TypeError("%s() got an unexpected keyword argument '%s'" %
  353. (message_descriptor.name, field_name))
  354. if field.label == _FieldDescriptor.LABEL_REPEATED:
  355. copy = field._default_constructor(self)
  356. if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: # Composite
  357. if _IsMapField(field):
  358. if _IsMessageMapField(field):
  359. for key in field_value:
  360. copy[key].MergeFrom(field_value[key])
  361. else:
  362. copy.update(field_value)
  363. else:
  364. for val in field_value:
  365. if isinstance(val, dict):
  366. copy.add(**val)
  367. else:
  368. copy.add().MergeFrom(val)
  369. else: # Scalar
  370. if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
  371. field_value = [_GetIntegerEnumValue(field.enum_type, val)
  372. for val in field_value]
  373. copy.extend(field_value)
  374. self._fields[field] = copy
  375. elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  376. copy = field._default_constructor(self)
  377. new_val = field_value
  378. if isinstance(field_value, dict):
  379. new_val = field.message_type._concrete_class(**field_value)
  380. try:
  381. copy.MergeFrom(new_val)
  382. except TypeError:
  383. _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
  384. self._fields[field] = copy
  385. else:
  386. if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
  387. field_value = _GetIntegerEnumValue(field.enum_type, field_value)
  388. try:
  389. setattr(self, field_name, field_value)
  390. except TypeError:
  391. _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
  392. init.__module__ = None
  393. init.__doc__ = None
  394. cls.__init__ = init
  395. def _GetFieldByName(message_descriptor, field_name):
  396. """Returns a field descriptor by field name.
  397. Args:
  398. message_descriptor: A Descriptor describing all fields in message.
  399. field_name: The name of the field to retrieve.
  400. Returns:
  401. The field descriptor associated with the field name.
  402. """
  403. try:
  404. return message_descriptor.fields_by_name[field_name]
  405. except KeyError:
  406. raise ValueError('Protocol message has no "%s" field.' % field_name)
  407. def _AddPropertiesForFields(descriptor, cls):
  408. """Adds properties for all fields in this protocol message type."""
  409. for field in descriptor.fields:
  410. _AddPropertiesForField(field, cls)
  411. if descriptor.is_extendable:
  412. # _ExtensionDict is just an adaptor with no state so we allocate a new one
  413. # every time it is accessed.
  414. cls.Extensions = property(lambda self: _ExtensionDict(self))
  415. def _AddPropertiesForField(field, cls):
  416. """Adds a public property for a protocol message field.
  417. Clients can use this property to get and (in the case
  418. of non-repeated scalar fields) directly set the value
  419. of a protocol message field.
  420. Args:
  421. field: A FieldDescriptor for this field.
  422. cls: The class we're constructing.
  423. """
  424. # Catch it if we add other types that we should
  425. # handle specially here.
  426. assert _FieldDescriptor.MAX_CPPTYPE == 10
  427. constant_name = field.name.upper() + "_FIELD_NUMBER"
  428. setattr(cls, constant_name, field.number)
  429. if field.label == _FieldDescriptor.LABEL_REPEATED:
  430. _AddPropertiesForRepeatedField(field, cls)
  431. elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  432. _AddPropertiesForNonRepeatedCompositeField(field, cls)
  433. else:
  434. _AddPropertiesForNonRepeatedScalarField(field, cls)
  435. def _AddPropertiesForRepeatedField(field, cls):
  436. """Adds a public property for a "repeated" protocol message field. Clients
  437. can use this property to get the value of the field, which will be either a
  438. _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see
  439. below).
  440. Note that when clients add values to these containers, we perform
  441. type-checking in the case of repeated scalar fields, and we also set any
  442. necessary "has" bits as a side-effect.
  443. Args:
  444. field: A FieldDescriptor for this field.
  445. cls: The class we're constructing.
  446. """
  447. proto_field_name = field.name
  448. property_name = _PropertyName(proto_field_name)
  449. def getter(self):
  450. field_value = self._fields.get(field)
  451. if field_value is None:
  452. # Construct a new object to represent this field.
  453. field_value = field._default_constructor(self)
  454. # Atomically check if another thread has preempted us and, if not, swap
  455. # in the new object we just created. If someone has preempted us, we
  456. # take that object and discard ours.
  457. # WARNING: We are relying on setdefault() being atomic. This is true
  458. # in CPython but we haven't investigated others. This warning appears
  459. # in several other locations in this file.
  460. field_value = self._fields.setdefault(field, field_value)
  461. return field_value
  462. getter.__module__ = None
  463. getter.__doc__ = 'Getter for %s.' % proto_field_name
  464. # We define a setter just so we can throw an exception with a more
  465. # helpful error message.
  466. def setter(self, new_value):
  467. raise AttributeError('Assignment not allowed to repeated field '
  468. '"%s" in protocol message object.' % proto_field_name)
  469. doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name
  470. setattr(cls, property_name, property(getter, setter, doc=doc))
  471. def _AddPropertiesForNonRepeatedScalarField(field, cls):
  472. """Adds a public property for a nonrepeated, scalar protocol message field.
  473. Clients can use this property to get and directly set the value of the field.
  474. Note that when the client sets the value of a field by using this property,
  475. all necessary "has" bits are set as a side-effect, and we also perform
  476. type-checking.
  477. Args:
  478. field: A FieldDescriptor for this field.
  479. cls: The class we're constructing.
  480. """
  481. proto_field_name = field.name
  482. property_name = _PropertyName(proto_field_name)
  483. type_checker = type_checkers.GetTypeChecker(field)
  484. default_value = field.default_value
  485. valid_values = set()
  486. is_proto3 = field.containing_type.syntax == "proto3"
  487. def getter(self):
  488. # TODO(protobuf-team): This may be broken since there may not be
  489. # default_value. Combine with has_default_value somehow.
  490. return self._fields.get(field, default_value)
  491. getter.__module__ = None
  492. getter.__doc__ = 'Getter for %s.' % proto_field_name
  493. clear_when_set_to_default = is_proto3 and not field.containing_oneof
  494. def field_setter(self, new_value):
  495. # pylint: disable=protected-access
  496. # Testing the value for truthiness captures all of the proto3 defaults
  497. # (0, 0.0, enum 0, and False).
  498. new_value = type_checker.CheckValue(new_value)
  499. if clear_when_set_to_default and not new_value:
  500. self._fields.pop(field, None)
  501. else:
  502. self._fields[field] = new_value
  503. # Check _cached_byte_size_dirty inline to improve performance, since scalar
  504. # setters are called frequently.
  505. if not self._cached_byte_size_dirty:
  506. self._Modified()
  507. if field.containing_oneof:
  508. def setter(self, new_value):
  509. field_setter(self, new_value)
  510. self._UpdateOneofState(field)
  511. else:
  512. setter = field_setter
  513. setter.__module__ = None
  514. setter.__doc__ = 'Setter for %s.' % proto_field_name
  515. # Add a property to encapsulate the getter/setter.
  516. doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name
  517. setattr(cls, property_name, property(getter, setter, doc=doc))
  518. def _AddPropertiesForNonRepeatedCompositeField(field, cls):
  519. """Adds a public property for a nonrepeated, composite protocol message field.
  520. A composite field is a "group" or "message" field.
  521. Clients can use this property to get the value of the field, but cannot
  522. assign to the property directly.
  523. Args:
  524. field: A FieldDescriptor for this field.
  525. cls: The class we're constructing.
  526. """
  527. # TODO(robinson): Remove duplication with similar method
  528. # for non-repeated scalars.
  529. proto_field_name = field.name
  530. property_name = _PropertyName(proto_field_name)
  531. # TODO(komarek): Can anyone explain to me why we cache the message_type this
  532. # way, instead of referring to field.message_type inside of getter(self)?
  533. # What if someone sets message_type later on (which makes for simpler
  534. # dyanmic proto descriptor and class creation code).
  535. message_type = field.message_type
  536. def getter(self):
  537. field_value = self._fields.get(field)
  538. if field_value is None:
  539. # Construct a new object to represent this field.
  540. field_value = message_type._concrete_class() # use field.message_type?
  541. field_value._SetListener(
  542. _OneofListener(self, field)
  543. if field.containing_oneof is not None
  544. else self._listener_for_children)
  545. # Atomically check if another thread has preempted us and, if not, swap
  546. # in the new object we just created. If someone has preempted us, we
  547. # take that object and discard ours.
  548. # WARNING: We are relying on setdefault() being atomic. This is true
  549. # in CPython but we haven't investigated others. This warning appears
  550. # in several other locations in this file.
  551. field_value = self._fields.setdefault(field, field_value)
  552. return field_value
  553. getter.__module__ = None
  554. getter.__doc__ = 'Getter for %s.' % proto_field_name
  555. # We define a setter just so we can throw an exception with a more
  556. # helpful error message.
  557. def setter(self, new_value):
  558. raise AttributeError('Assignment not allowed to composite field '
  559. '"%s" in protocol message object.' % proto_field_name)
  560. # Add a property to encapsulate the getter.
  561. doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name
  562. setattr(cls, property_name, property(getter, setter, doc=doc))
  563. def _AddPropertiesForExtensions(descriptor, cls):
  564. """Adds properties for all fields in this protocol message type."""
  565. extension_dict = descriptor.extensions_by_name
  566. for extension_name, extension_field in extension_dict.iteritems():
  567. constant_name = extension_name.upper() + "_FIELD_NUMBER"
  568. setattr(cls, constant_name, extension_field.number)
  569. def _AddStaticMethods(cls):
  570. # TODO(robinson): This probably needs to be thread-safe(?)
  571. def RegisterExtension(extension_handle):
  572. extension_handle.containing_type = cls.DESCRIPTOR
  573. _AttachFieldHelpers(cls, extension_handle)
  574. # Try to insert our extension, failing if an extension with the same number
  575. # already exists.
  576. actual_handle = cls._extensions_by_number.setdefault(
  577. extension_handle.number, extension_handle)
  578. if actual_handle is not extension_handle:
  579. raise AssertionError(
  580. 'Extensions "%s" and "%s" both try to extend message type "%s" with '
  581. 'field number %d.' %
  582. (extension_handle.full_name, actual_handle.full_name,
  583. cls.DESCRIPTOR.full_name, extension_handle.number))
  584. cls._extensions_by_name[extension_handle.full_name] = extension_handle
  585. handle = extension_handle # avoid line wrapping
  586. if _IsMessageSetExtension(handle):
  587. # MessageSet extension. Also register under type name.
  588. cls._extensions_by_name[
  589. extension_handle.message_type.full_name] = extension_handle
  590. cls.RegisterExtension = staticmethod(RegisterExtension)
  591. def FromString(s):
  592. message = cls()
  593. message.MergeFromString(s)
  594. return message
  595. cls.FromString = staticmethod(FromString)
  596. def _IsPresent(item):
  597. """Given a (FieldDescriptor, value) tuple from _fields, return true if the
  598. value should be included in the list returned by ListFields()."""
  599. if item[0].label == _FieldDescriptor.LABEL_REPEATED:
  600. return bool(item[1])
  601. elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  602. return item[1]._is_present_in_parent
  603. else:
  604. return True
  605. def _AddListFieldsMethod(message_descriptor, cls):
  606. """Helper for _AddMessageMethods()."""
  607. def ListFields(self):
  608. all_fields = [item for item in self._fields.iteritems() if _IsPresent(item)]
  609. all_fields.sort(key = lambda item: item[0].number)
  610. return all_fields
  611. cls.ListFields = ListFields
  612. _Proto3HasError = 'Protocol message has no non-repeated submessage field "%s"'
  613. _Proto2HasError = 'Protocol message has no non-repeated field "%s"'
  614. def _AddHasFieldMethod(message_descriptor, cls):
  615. """Helper for _AddMessageMethods()."""
  616. is_proto3 = (message_descriptor.syntax == "proto3")
  617. error_msg = _Proto3HasError if is_proto3 else _Proto2HasError
  618. hassable_fields = {}
  619. for field in message_descriptor.fields:
  620. if field.label == _FieldDescriptor.LABEL_REPEATED:
  621. continue
  622. # For proto3, only submessages and fields inside a oneof have presence.
  623. if (is_proto3 and field.cpp_type != _FieldDescriptor.CPPTYPE_MESSAGE and
  624. not field.containing_oneof):
  625. continue
  626. hassable_fields[field.name] = field
  627. if not is_proto3:
  628. # Fields inside oneofs are never repeated (enforced by the compiler).
  629. for oneof in message_descriptor.oneofs:
  630. hassable_fields[oneof.name] = oneof
  631. def HasField(self, field_name):
  632. try:
  633. field = hassable_fields[field_name]
  634. except KeyError:
  635. raise ValueError(error_msg % field_name)
  636. if isinstance(field, descriptor_mod.OneofDescriptor):
  637. try:
  638. return HasField(self, self._oneofs[field].name)
  639. except KeyError:
  640. return False
  641. else:
  642. if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  643. value = self._fields.get(field)
  644. return value is not None and value._is_present_in_parent
  645. else:
  646. return field in self._fields
  647. cls.HasField = HasField
  648. def _AddClearFieldMethod(message_descriptor, cls):
  649. """Helper for _AddMessageMethods()."""
  650. def ClearField(self, field_name):
  651. try:
  652. field = message_descriptor.fields_by_name[field_name]
  653. except KeyError:
  654. try:
  655. field = message_descriptor.oneofs_by_name[field_name]
  656. if field in self._oneofs:
  657. field = self._oneofs[field]
  658. else:
  659. return
  660. except KeyError:
  661. raise ValueError('Protocol message has no "%s" field.' % field_name)
  662. if field in self._fields:
  663. # Note: If the field is a sub-message, its listener will still point
  664. # at us. That's fine, because the worst than can happen is that it
  665. # will call _Modified() and invalidate our byte size. Big deal.
  666. del self._fields[field]
  667. if self._oneofs.get(field.containing_oneof, None) is field:
  668. del self._oneofs[field.containing_oneof]
  669. # Always call _Modified() -- even if nothing was changed, this is
  670. # a mutating method, and thus calling it should cause the field to become
  671. # present in the parent message.
  672. self._Modified()
  673. cls.ClearField = ClearField
  674. def _AddClearExtensionMethod(cls):
  675. """Helper for _AddMessageMethods()."""
  676. def ClearExtension(self, extension_handle):
  677. _VerifyExtensionHandle(self, extension_handle)
  678. # Similar to ClearField(), above.
  679. if extension_handle in self._fields:
  680. del self._fields[extension_handle]
  681. self._Modified()
  682. cls.ClearExtension = ClearExtension
  683. def _AddClearMethod(message_descriptor, cls):
  684. """Helper for _AddMessageMethods()."""
  685. def Clear(self):
  686. # Clear fields.
  687. self._fields = {}
  688. self._unknown_fields = ()
  689. self._oneofs = {}
  690. self._Modified()
  691. cls.Clear = Clear
  692. def _AddHasExtensionMethod(cls):
  693. """Helper for _AddMessageMethods()."""
  694. def HasExtension(self, extension_handle):
  695. _VerifyExtensionHandle(self, extension_handle)
  696. if extension_handle.label == _FieldDescriptor.LABEL_REPEATED:
  697. raise KeyError('"%s" is repeated.' % extension_handle.full_name)
  698. if extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  699. value = self._fields.get(extension_handle)
  700. return value is not None and value._is_present_in_parent
  701. else:
  702. return extension_handle in self._fields
  703. cls.HasExtension = HasExtension
  704. def _UnpackAny(msg):
  705. type_url = msg.type_url
  706. db = symbol_database.Default()
  707. if not type_url:
  708. return None
  709. # TODO(haberman): For now we just strip the hostname. Better logic will be
  710. # required.
  711. type_name = type_url.split("/")[-1]
  712. descriptor = db.pool.FindMessageTypeByName(type_name)
  713. if descriptor is None:
  714. return None
  715. message_class = db.GetPrototype(descriptor)
  716. message = message_class()
  717. message.ParseFromString(msg.value)
  718. return message
  719. def _AddEqualsMethod(message_descriptor, cls):
  720. """Helper for _AddMessageMethods()."""
  721. def __eq__(self, other):
  722. if (not isinstance(other, message_mod.Message) or
  723. other.DESCRIPTOR != self.DESCRIPTOR):
  724. return False
  725. if self is other:
  726. return True
  727. if self.DESCRIPTOR.full_name == "google.protobuf.Any":
  728. any_a = _UnpackAny(self)
  729. any_b = _UnpackAny(other)
  730. if any_a and any_b:
  731. return any_a == any_b
  732. if not self.ListFields() == other.ListFields():
  733. return False
  734. # Sort unknown fields because their order shouldn't affect equality test.
  735. unknown_fields = list(self._unknown_fields)
  736. unknown_fields.sort()
  737. other_unknown_fields = list(other._unknown_fields)
  738. other_unknown_fields.sort()
  739. return unknown_fields == other_unknown_fields
  740. cls.__eq__ = __eq__
  741. def _AddStrMethod(message_descriptor, cls):
  742. """Helper for _AddMessageMethods()."""
  743. def __str__(self):
  744. return text_format.MessageToString(self)
  745. cls.__str__ = __str__
  746. def _AddUnicodeMethod(unused_message_descriptor, cls):
  747. """Helper for _AddMessageMethods()."""
  748. def __unicode__(self):
  749. return text_format.MessageToString(self, as_utf8=True).decode('utf-8')
  750. cls.__unicode__ = __unicode__
  751. def _AddSetListenerMethod(cls):
  752. """Helper for _AddMessageMethods()."""
  753. def SetListener(self, listener):
  754. if listener is None:
  755. self._listener = message_listener_mod.NullMessageListener()
  756. else:
  757. self._listener = listener
  758. cls._SetListener = SetListener
  759. def _BytesForNonRepeatedElement(value, field_number, field_type):
  760. """Returns the number of bytes needed to serialize a non-repeated element.
  761. The returned byte count includes space for tag information and any
  762. other additional space associated with serializing value.
  763. Args:
  764. value: Value we're serializing.
  765. field_number: Field number of this value. (Since the field number
  766. is stored as part of a varint-encoded tag, this has an impact
  767. on the total bytes required to serialize the value).
  768. field_type: The type of the field. One of the TYPE_* constants
  769. within FieldDescriptor.
  770. """
  771. try:
  772. fn = type_checkers.TYPE_TO_BYTE_SIZE_FN[field_type]
  773. return fn(field_number, value)
  774. except KeyError:
  775. raise message_mod.EncodeError('Unrecognized field type: %d' % field_type)
  776. def _AddByteSizeMethod(message_descriptor, cls):
  777. """Helper for _AddMessageMethods()."""
  778. def ByteSize(self):
  779. if not self._cached_byte_size_dirty:
  780. return self._cached_byte_size
  781. size = 0
  782. for field_descriptor, field_value in self.ListFields():
  783. size += field_descriptor._sizer(field_value)
  784. for tag_bytes, value_bytes in self._unknown_fields:
  785. size += len(tag_bytes) + len(value_bytes)
  786. self._cached_byte_size = size
  787. self._cached_byte_size_dirty = False
  788. self._listener_for_children.dirty = False
  789. return size
  790. cls.ByteSize = ByteSize
  791. def _AddSerializeToStringMethod(message_descriptor, cls):
  792. """Helper for _AddMessageMethods()."""
  793. def SerializeToString(self):
  794. # Check if the message has all of its required fields set.
  795. errors = []
  796. if not self.IsInitialized():
  797. raise message_mod.EncodeError(
  798. 'Message %s is missing required fields: %s' % (
  799. self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  800. return self.SerializePartialToString()
  801. cls.SerializeToString = SerializeToString
  802. def _AddSerializePartialToStringMethod(message_descriptor, cls):
  803. """Helper for _AddMessageMethods()."""
  804. def SerializePartialToString(self):
  805. out = BytesIO()
  806. self._InternalSerialize(out.write)
  807. return out.getvalue()
  808. cls.SerializePartialToString = SerializePartialToString
  809. def InternalSerialize(self, write_bytes):
  810. for field_descriptor, field_value in self.ListFields():
  811. field_descriptor._encoder(write_bytes, field_value)
  812. for tag_bytes, value_bytes in self._unknown_fields:
  813. write_bytes(tag_bytes)
  814. write_bytes(value_bytes)
  815. cls._InternalSerialize = InternalSerialize
  816. def _AddMergeFromStringMethod(message_descriptor, cls):
  817. """Helper for _AddMessageMethods()."""
  818. def MergeFromString(self, serialized):
  819. length = len(serialized)
  820. try:
  821. if self._InternalParse(serialized, 0, length) != length:
  822. # The only reason _InternalParse would return early is if it
  823. # encountered an end-group tag.
  824. raise message_mod.DecodeError('Unexpected end-group tag.')
  825. except (IndexError, TypeError):
  826. # Now ord(buf[p:p+1]) == ord('') gets TypeError.
  827. raise message_mod.DecodeError('Truncated message.')
  828. except struct.error as e:
  829. raise message_mod.DecodeError(e)
  830. return length # Return this for legacy reasons.
  831. cls.MergeFromString = MergeFromString
  832. local_ReadTag = decoder.ReadTag
  833. local_SkipField = decoder.SkipField
  834. decoders_by_tag = cls._decoders_by_tag
  835. is_proto3 = message_descriptor.syntax == "proto3"
  836. def InternalParse(self, buffer, pos, end):
  837. self._Modified()
  838. field_dict = self._fields
  839. unknown_field_list = self._unknown_fields
  840. while pos != end:
  841. (tag_bytes, new_pos) = local_ReadTag(buffer, pos)
  842. field_decoder, field_desc = decoders_by_tag.get(tag_bytes, (None, None))
  843. if field_decoder is None:
  844. value_start_pos = new_pos
  845. new_pos = local_SkipField(buffer, new_pos, end, tag_bytes)
  846. if new_pos == -1:
  847. return pos
  848. if not is_proto3:
  849. if not unknown_field_list:
  850. unknown_field_list = self._unknown_fields = []
  851. unknown_field_list.append(
  852. (tag_bytes, buffer[value_start_pos:new_pos]))
  853. pos = new_pos
  854. else:
  855. pos = field_decoder(buffer, new_pos, end, self, field_dict)
  856. if field_desc:
  857. self._UpdateOneofState(field_desc)
  858. return pos
  859. cls._InternalParse = InternalParse
  860. def _AddIsInitializedMethod(message_descriptor, cls):
  861. """Adds the IsInitialized and FindInitializationError methods to the
  862. protocol message class."""
  863. required_fields = [field for field in message_descriptor.fields
  864. if field.label == _FieldDescriptor.LABEL_REQUIRED]
  865. def IsInitialized(self, errors=None):
  866. """Checks if all required fields of a message are set.
  867. Args:
  868. errors: A list which, if provided, will be populated with the field
  869. paths of all missing required fields.
  870. Returns:
  871. True iff the specified message has all required fields set.
  872. """
  873. # Performance is critical so we avoid HasField() and ListFields().
  874. for field in required_fields:
  875. if (field not in self._fields or
  876. (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
  877. not self._fields[field]._is_present_in_parent)):
  878. if errors is not None:
  879. errors.extend(self.FindInitializationErrors())
  880. return False
  881. for field, value in list(self._fields.items()): # dict can change size!
  882. if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  883. if field.label == _FieldDescriptor.LABEL_REPEATED:
  884. if (field.message_type.has_options and
  885. field.message_type.GetOptions().map_entry):
  886. continue
  887. for element in value:
  888. if not element.IsInitialized():
  889. if errors is not None:
  890. errors.extend(self.FindInitializationErrors())
  891. return False
  892. elif value._is_present_in_parent and not value.IsInitialized():
  893. if errors is not None:
  894. errors.extend(self.FindInitializationErrors())
  895. return False
  896. return True
  897. cls.IsInitialized = IsInitialized
  898. def FindInitializationErrors(self):
  899. """Finds required fields which are not initialized.
  900. Returns:
  901. A list of strings. Each string is a path to an uninitialized field from
  902. the top-level message, e.g. "foo.bar[5].baz".
  903. """
  904. errors = [] # simplify things
  905. for field in required_fields:
  906. if not self.HasField(field.name):
  907. errors.append(field.name)
  908. for field, value in self.ListFields():
  909. if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  910. if field.is_extension:
  911. name = "(%s)" % field.full_name
  912. else:
  913. name = field.name
  914. if _IsMapField(field):
  915. if _IsMessageMapField(field):
  916. for key in value:
  917. element = value[key]
  918. prefix = "%s[%d]." % (name, key)
  919. sub_errors = element.FindInitializationErrors()
  920. errors += [prefix + error for error in sub_errors]
  921. else:
  922. # ScalarMaps can't have any initialization errors.
  923. pass
  924. elif field.label == _FieldDescriptor.LABEL_REPEATED:
  925. for i in xrange(len(value)):
  926. element = value[i]
  927. prefix = "%s[%d]." % (name, i)
  928. sub_errors = element.FindInitializationErrors()
  929. errors += [prefix + error for error in sub_errors]
  930. else:
  931. prefix = name + "."
  932. sub_errors = value.FindInitializationErrors()
  933. errors += [prefix + error for error in sub_errors]
  934. return errors
  935. cls.FindInitializationErrors = FindInitializationErrors
  936. def _AddMergeFromMethod(cls):
  937. LABEL_REPEATED = _FieldDescriptor.LABEL_REPEATED
  938. CPPTYPE_MESSAGE = _FieldDescriptor.CPPTYPE_MESSAGE
  939. def MergeFrom(self, msg):
  940. if not isinstance(msg, cls):
  941. raise TypeError(
  942. "Parameter to MergeFrom() must be instance of same class: "
  943. "expected %s got %s." % (cls.__name__, type(msg).__name__))
  944. assert msg is not self
  945. self._Modified()
  946. fields = self._fields
  947. for field, value in msg._fields.iteritems():
  948. if field.label == LABEL_REPEATED:
  949. field_value = fields.get(field)
  950. if field_value is None:
  951. # Construct a new object to represent this field.
  952. field_value = field._default_constructor(self)
  953. fields[field] = field_value
  954. field_value.MergeFrom(value)
  955. elif field.cpp_type == CPPTYPE_MESSAGE:
  956. if value._is_present_in_parent:
  957. field_value = fields.get(field)
  958. if field_value is None:
  959. # Construct a new object to represent this field.
  960. field_value = field._default_constructor(self)
  961. fields[field] = field_value
  962. if field.containing_oneof:
  963. self._UpdateOneofState(field)
  964. field_value.MergeFrom(value)
  965. else:
  966. self._fields[field] = value
  967. if field.containing_oneof:
  968. self._UpdateOneofState(field)
  969. if msg._unknown_fields:
  970. if not self._unknown_fields:
  971. self._unknown_fields = []
  972. self._unknown_fields.extend(msg._unknown_fields)
  973. cls.MergeFrom = MergeFrom
  974. def _AddWhichOneofMethod(message_descriptor, cls):
  975. def WhichOneof(self, oneof_name):
  976. """Returns the name of the currently set field inside a oneof, or None."""
  977. try:
  978. field = message_descriptor.oneofs_by_name[oneof_name]
  979. except KeyError:
  980. raise ValueError(
  981. 'Protocol message has no oneof "%s" field.' % oneof_name)
  982. nested_field = self._oneofs.get(field, None)
  983. if nested_field is not None and self.HasField(nested_field.name):
  984. return nested_field.name
  985. else:
  986. return None
  987. cls.WhichOneof = WhichOneof
  988. def _AddMessageMethods(message_descriptor, cls):
  989. """Adds implementations of all Message methods to cls."""
  990. _AddListFieldsMethod(message_descriptor, cls)
  991. _AddHasFieldMethod(message_descriptor, cls)
  992. _AddClearFieldMethod(message_descriptor, cls)
  993. if message_descriptor.is_extendable:
  994. _AddClearExtensionMethod(cls)
  995. _AddHasExtensionMethod(cls)
  996. _AddClearMethod(message_descriptor, cls)
  997. _AddEqualsMethod(message_descriptor, cls)
  998. _AddStrMethod(message_descriptor, cls)
  999. _AddUnicodeMethod(message_descriptor, cls)
  1000. _AddSetListenerMethod(cls)
  1001. _AddByteSizeMethod(message_descriptor, cls)
  1002. _AddSerializeToStringMethod(message_descriptor, cls)
  1003. _AddSerializePartialToStringMethod(message_descriptor, cls)
  1004. _AddMergeFromStringMethod(message_descriptor, cls)
  1005. _AddIsInitializedMethod(message_descriptor, cls)
  1006. _AddMergeFromMethod(cls)
  1007. _AddWhichOneofMethod(message_descriptor, cls)
  1008. def _AddPrivateHelperMethods(message_descriptor, cls):
  1009. """Adds implementation of private helper methods to cls."""
  1010. def Modified(self):
  1011. """Sets the _cached_byte_size_dirty bit to true,
  1012. and propagates this to our listener iff this was a state change.
  1013. """
  1014. # Note: Some callers check _cached_byte_size_dirty before calling
  1015. # _Modified() as an extra optimization. So, if this method is ever
  1016. # changed such that it does stuff even when _cached_byte_size_dirty is
  1017. # already true, the callers need to be updated.
  1018. if not self._cached_byte_size_dirty:
  1019. self._cached_byte_size_dirty = True
  1020. self._listener_for_children.dirty = True
  1021. self._is_present_in_parent = True
  1022. self._listener.Modified()
  1023. def _UpdateOneofState(self, field):
  1024. """Sets field as the active field in its containing oneof.
  1025. Will also delete currently active field in the oneof, if it is different
  1026. from the argument. Does not mark the message as modified.
  1027. """
  1028. other_field = self._oneofs.setdefault(field.containing_oneof, field)
  1029. if other_field is not field:
  1030. del self._fields[other_field]
  1031. self._oneofs[field.containing_oneof] = field
  1032. cls._Modified = Modified
  1033. cls.SetInParent = Modified
  1034. cls._UpdateOneofState = _UpdateOneofState
  1035. class _Listener(object):
  1036. """MessageListener implementation that a parent message registers with its
  1037. child message.
  1038. In order to support semantics like:
  1039. foo.bar.baz.qux = 23
  1040. assert foo.HasField('bar')
  1041. ...child objects must have back references to their parents.
  1042. This helper class is at the heart of this support.
  1043. """
  1044. def __init__(self, parent_message):
  1045. """Args:
  1046. parent_message: The message whose _Modified() method we should call when
  1047. we receive Modified() messages.
  1048. """
  1049. # This listener establishes a back reference from a child (contained) object
  1050. # to its parent (containing) object. We make this a weak reference to avoid
  1051. # creating cyclic garbage when the client finishes with the 'parent' object
  1052. # in the tree.
  1053. if isinstance(parent_message, weakref.ProxyType):
  1054. self._parent_message_weakref = parent_message
  1055. else:
  1056. self._parent_message_weakref = weakref.proxy(parent_message)
  1057. # As an optimization, we also indicate directly on the listener whether
  1058. # or not the parent message is dirty. This way we can avoid traversing
  1059. # up the tree in the common case.
  1060. self.dirty = False
  1061. def Modified(self):
  1062. if self.dirty:
  1063. return
  1064. try:
  1065. # Propagate the signal to our parents iff this is the first field set.
  1066. self._parent_message_weakref._Modified()
  1067. except ReferenceError:
  1068. # We can get here if a client has kept a reference to a child object,
  1069. # and is now setting a field on it, but the child's parent has been
  1070. # garbage-collected. This is not an error.
  1071. pass
  1072. class _OneofListener(_Listener):
  1073. """Special listener implementation for setting composite oneof fields."""
  1074. def __init__(self, parent_message, field):
  1075. """Args:
  1076. parent_message: The message whose _Modified() method we should call when
  1077. we receive Modified() messages.
  1078. field: The descriptor of the field being set in the parent message.
  1079. """
  1080. super(_OneofListener, self).__init__(parent_message)
  1081. self._field = field
  1082. def Modified(self):
  1083. """Also updates the state of the containing oneof in the parent message."""
  1084. try:
  1085. self._parent_message_weakref._UpdateOneofState(self._field)
  1086. super(_OneofListener, self).Modified()
  1087. except ReferenceError:
  1088. pass
  1089. # TODO(robinson): Move elsewhere? This file is getting pretty ridiculous...
  1090. # TODO(robinson): Unify error handling of "unknown extension" crap.
  1091. # TODO(robinson): Support iteritems()-style iteration over all
  1092. # extensions with the "has" bits turned on?
  1093. class _ExtensionDict(object):
  1094. """Dict-like container for supporting an indexable "Extensions"
  1095. field on proto instances.
  1096. Note that in all cases we expect extension handles to be
  1097. FieldDescriptors.
  1098. """
  1099. def __init__(self, extended_message):
  1100. """extended_message: Message instance for which we are the Extensions dict.
  1101. """
  1102. self._extended_message = extended_message
  1103. def __getitem__(self, extension_handle):
  1104. """Returns the current value of the given extension handle."""
  1105. _VerifyExtensionHandle(self._extended_message, extension_handle)
  1106. result = self._extended_message._fields.get(extension_handle)
  1107. if result is not None:
  1108. return result
  1109. if extension_handle.label == _FieldDescriptor.LABEL_REPEATED:
  1110. result = extension_handle._default_constructor(self._extended_message)
  1111. elif extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
  1112. result = extension_handle.message_type._concrete_class()
  1113. try:
  1114. result._SetListener(self._extended_message._listener_for_children)
  1115. except ReferenceError:
  1116. pass
  1117. else:
  1118. # Singular scalar -- just return the default without inserting into the
  1119. # dict.
  1120. return extension_handle.default_value
  1121. # Atomically check if another thread has preempted us and, if not, swap
  1122. # in the new object we just created. If someone has preempted us, we
  1123. # take that object and discard ours.
  1124. # WARNING: We are relying on setdefault() being atomic. This is true
  1125. # in CPython but we haven't investigated others. This warning appears
  1126. # in several other locations in this file.
  1127. result = self._extended_message._fields.setdefault(
  1128. extension_handle, result)
  1129. return result
  1130. def __eq__(self, other):
  1131. if not isinstance(other, self.__class__):
  1132. return False
  1133. my_fields = self._extended_message.ListFields()
  1134. other_fields = other._extended_message.ListFields()
  1135. # Get rid of non-extension fields.
  1136. my_fields = [ field for field in my_fields if field.is_extension ]
  1137. other_fields = [ field for field in other_fields if field.is_extension ]
  1138. return my_fields == other_fields
  1139. def __ne__(self, other):
  1140. return not self == other
  1141. def __hash__(self):
  1142. raise TypeError('unhashable object')
  1143. # Note that this is only meaningful for non-repeated, scalar extension
  1144. # fields. Note also that we may have to call _Modified() when we do
  1145. # successfully set a field this way, to set any necssary "has" bits in the
  1146. # ancestors of the extended message.
  1147. def __setitem__(self, extension_handle, value):
  1148. """If extension_handle specifies a non-repeated, scalar extension
  1149. field, sets the value of that field.
  1150. """
  1151. _VerifyExtensionHandle(self._extended_message, extension_handle)
  1152. if (extension_handle.label == _FieldDescriptor.LABEL_REPEATED or
  1153. extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE):
  1154. raise TypeError(
  1155. 'Cannot assign to extension "%s" because it is a repeated or '
  1156. 'composite type.' % extension_handle.full_name)
  1157. # It's slightly wasteful to lookup the type checker each time,
  1158. # but we expect this to be a vanishingly uncommon case anyway.
  1159. type_checker = type_checkers.GetTypeChecker(extension_handle)
  1160. # pylint: disable=protected-access
  1161. self._extended_message._fields[extension_handle] = (
  1162. type_checker.CheckValue(value))
  1163. self._extended_message._Modified()
  1164. def _FindExtensionByName(self, name):
  1165. """Tries to find a known extension with the specified name.
  1166. Args:
  1167. name: Extension full name.
  1168. Returns:
  1169. Extension field descriptor.
  1170. """
  1171. return self._extended_message._extensions_by_name.get(name, None)