图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1517 lines
56 KiB

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