python_message.py 58 KB

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