descriptor.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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. """Descriptors essentially contain exactly the information found in a .proto
  31. file, in types that make this information accessible in Python.
  32. """
  33. __author__ = 'robinson@google.com (Will Robinson)'
  34. import six
  35. from google.protobuf.internal import api_implementation
  36. _USE_C_DESCRIPTORS = False
  37. if api_implementation.Type() == 'cpp':
  38. # Used by MakeDescriptor in cpp mode
  39. import os
  40. import uuid
  41. from google.protobuf.pyext import _message
  42. _USE_C_DESCRIPTORS = getattr(_message, '_USE_C_DESCRIPTORS', False)
  43. class Error(Exception):
  44. """Base error for this module."""
  45. class TypeTransformationError(Error):
  46. """Error transforming between python proto type and corresponding C++ type."""
  47. if _USE_C_DESCRIPTORS:
  48. # This metaclass allows to override the behavior of code like
  49. # isinstance(my_descriptor, FieldDescriptor)
  50. # and make it return True when the descriptor is an instance of the extension
  51. # type written in C++.
  52. class DescriptorMetaclass(type):
  53. def __instancecheck__(cls, obj):
  54. if super(DescriptorMetaclass, cls).__instancecheck__(obj):
  55. return True
  56. if isinstance(obj, cls._C_DESCRIPTOR_CLASS):
  57. return True
  58. return False
  59. else:
  60. # The standard metaclass; nothing changes.
  61. DescriptorMetaclass = type
  62. class DescriptorBase(six.with_metaclass(DescriptorMetaclass)):
  63. """Descriptors base class.
  64. This class is the base of all descriptor classes. It provides common options
  65. related functionality.
  66. Attributes:
  67. has_options: True if the descriptor has non-default options. Usually it
  68. is not necessary to read this -- just call GetOptions() which will
  69. happily return the default instance. However, it's sometimes useful
  70. for efficiency, and also useful inside the protobuf implementation to
  71. avoid some bootstrapping issues.
  72. """
  73. if _USE_C_DESCRIPTORS:
  74. # The class, or tuple of classes, that are considered as "virtual
  75. # subclasses" of this descriptor class.
  76. _C_DESCRIPTOR_CLASS = ()
  77. def __init__(self, options, options_class_name):
  78. """Initialize the descriptor given its options message and the name of the
  79. class of the options message. The name of the class is required in case
  80. the options message is None and has to be created.
  81. """
  82. self._options = options
  83. self._options_class_name = options_class_name
  84. # Does this descriptor have non-default options?
  85. self.has_options = options is not None
  86. def _SetOptions(self, options, options_class_name):
  87. """Sets the descriptor's options
  88. This function is used in generated proto2 files to update descriptor
  89. options. It must not be used outside proto2.
  90. """
  91. self._options = options
  92. self._options_class_name = options_class_name
  93. # Does this descriptor have non-default options?
  94. self.has_options = options is not None
  95. def GetOptions(self):
  96. """Retrieves descriptor options.
  97. This method returns the options set or creates the default options for the
  98. descriptor.
  99. """
  100. if self._options:
  101. return self._options
  102. from google.protobuf import descriptor_pb2
  103. try:
  104. options_class = getattr(descriptor_pb2, self._options_class_name)
  105. except AttributeError:
  106. raise RuntimeError('Unknown options class name %s!' %
  107. (self._options_class_name))
  108. self._options = options_class()
  109. return self._options
  110. class _NestedDescriptorBase(DescriptorBase):
  111. """Common class for descriptors that can be nested."""
  112. def __init__(self, options, options_class_name, name, full_name,
  113. file, containing_type, serialized_start=None,
  114. serialized_end=None):
  115. """Constructor.
  116. Args:
  117. options: Protocol message options or None
  118. to use default message options.
  119. options_class_name: (str) The class name of the above options.
  120. name: (str) Name of this protocol message type.
  121. full_name: (str) Fully-qualified name of this protocol message type,
  122. which will include protocol "package" name and the name of any
  123. enclosing types.
  124. file: (FileDescriptor) Reference to file info.
  125. containing_type: if provided, this is a nested descriptor, with this
  126. descriptor as parent, otherwise None.
  127. serialized_start: The start index (inclusive) in block in the
  128. file.serialized_pb that describes this descriptor.
  129. serialized_end: The end index (exclusive) in block in the
  130. file.serialized_pb that describes this descriptor.
  131. """
  132. super(_NestedDescriptorBase, self).__init__(
  133. options, options_class_name)
  134. self.name = name
  135. # TODO(falk): Add function to calculate full_name instead of having it in
  136. # memory?
  137. self.full_name = full_name
  138. self.file = file
  139. self.containing_type = containing_type
  140. self._serialized_start = serialized_start
  141. self._serialized_end = serialized_end
  142. def CopyToProto(self, proto):
  143. """Copies this to the matching proto in descriptor_pb2.
  144. Args:
  145. proto: An empty proto instance from descriptor_pb2.
  146. Raises:
  147. Error: If self couldnt be serialized, due to to few constructor arguments.
  148. """
  149. if (self.file is not None and
  150. self._serialized_start is not None and
  151. self._serialized_end is not None):
  152. proto.ParseFromString(self.file.serialized_pb[
  153. self._serialized_start:self._serialized_end])
  154. else:
  155. raise Error('Descriptor does not contain serialization.')
  156. class Descriptor(_NestedDescriptorBase):
  157. """Descriptor for a protocol message type.
  158. A Descriptor instance has the following attributes:
  159. name: (str) Name of this protocol message type.
  160. full_name: (str) Fully-qualified name of this protocol message type,
  161. which will include protocol "package" name and the name of any
  162. enclosing types.
  163. containing_type: (Descriptor) Reference to the descriptor of the
  164. type containing us, or None if this is top-level.
  165. fields: (list of FieldDescriptors) Field descriptors for all
  166. fields in this type.
  167. fields_by_number: (dict int -> FieldDescriptor) Same FieldDescriptor
  168. objects as in |fields|, but indexed by "number" attribute in each
  169. FieldDescriptor.
  170. fields_by_name: (dict str -> FieldDescriptor) Same FieldDescriptor
  171. objects as in |fields|, but indexed by "name" attribute in each
  172. FieldDescriptor.
  173. fields_by_camelcase_name: (dict str -> FieldDescriptor) Same
  174. FieldDescriptor objects as in |fields|, but indexed by
  175. "camelcase_name" attribute in each FieldDescriptor.
  176. nested_types: (list of Descriptors) Descriptor references
  177. for all protocol message types nested within this one.
  178. nested_types_by_name: (dict str -> Descriptor) Same Descriptor
  179. objects as in |nested_types|, but indexed by "name" attribute
  180. in each Descriptor.
  181. enum_types: (list of EnumDescriptors) EnumDescriptor references
  182. for all enums contained within this type.
  183. enum_types_by_name: (dict str ->EnumDescriptor) Same EnumDescriptor
  184. objects as in |enum_types|, but indexed by "name" attribute
  185. in each EnumDescriptor.
  186. enum_values_by_name: (dict str -> EnumValueDescriptor) Dict mapping
  187. from enum value name to EnumValueDescriptor for that value.
  188. extensions: (list of FieldDescriptor) All extensions defined directly
  189. within this message type (NOT within a nested type).
  190. extensions_by_name: (dict, string -> FieldDescriptor) Same FieldDescriptor
  191. objects as |extensions|, but indexed by "name" attribute of each
  192. FieldDescriptor.
  193. is_extendable: Does this type define any extension ranges?
  194. oneofs: (list of OneofDescriptor) The list of descriptors for oneof fields
  195. in this message.
  196. oneofs_by_name: (dict str -> OneofDescriptor) Same objects as in |oneofs|,
  197. but indexed by "name" attribute.
  198. file: (FileDescriptor) Reference to file descriptor.
  199. """
  200. if _USE_C_DESCRIPTORS:
  201. _C_DESCRIPTOR_CLASS = _message.Descriptor
  202. def __new__(cls, name, full_name, filename, containing_type, fields,
  203. nested_types, enum_types, extensions, options=None,
  204. is_extendable=True, extension_ranges=None, oneofs=None,
  205. file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin
  206. syntax=None):
  207. _message.Message._CheckCalledFromGeneratedFile()
  208. return _message.default_pool.FindMessageTypeByName(full_name)
  209. # NOTE(tmarek): The file argument redefining a builtin is nothing we can
  210. # fix right now since we don't know how many clients already rely on the
  211. # name of the argument.
  212. def __init__(self, name, full_name, filename, containing_type, fields,
  213. nested_types, enum_types, extensions, options=None,
  214. is_extendable=True, extension_ranges=None, oneofs=None,
  215. file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin
  216. syntax=None):
  217. """Arguments to __init__() are as described in the description
  218. of Descriptor fields above.
  219. Note that filename is an obsolete argument, that is not used anymore.
  220. Please use file.name to access this as an attribute.
  221. """
  222. super(Descriptor, self).__init__(
  223. options, 'MessageOptions', name, full_name, file,
  224. containing_type, serialized_start=serialized_start,
  225. serialized_end=serialized_end)
  226. # We have fields in addition to fields_by_name and fields_by_number,
  227. # so that:
  228. # 1. Clients can index fields by "order in which they're listed."
  229. # 2. Clients can easily iterate over all fields with the terse
  230. # syntax: for f in descriptor.fields: ...
  231. self.fields = fields
  232. for field in self.fields:
  233. field.containing_type = self
  234. self.fields_by_number = dict((f.number, f) for f in fields)
  235. self.fields_by_name = dict((f.name, f) for f in fields)
  236. self._fields_by_camelcase_name = None
  237. self.nested_types = nested_types
  238. for nested_type in nested_types:
  239. nested_type.containing_type = self
  240. self.nested_types_by_name = dict((t.name, t) for t in nested_types)
  241. self.enum_types = enum_types
  242. for enum_type in self.enum_types:
  243. enum_type.containing_type = self
  244. self.enum_types_by_name = dict((t.name, t) for t in enum_types)
  245. self.enum_values_by_name = dict(
  246. (v.name, v) for t in enum_types for v in t.values)
  247. self.extensions = extensions
  248. for extension in self.extensions:
  249. extension.extension_scope = self
  250. self.extensions_by_name = dict((f.name, f) for f in extensions)
  251. self.is_extendable = is_extendable
  252. self.extension_ranges = extension_ranges
  253. self.oneofs = oneofs if oneofs is not None else []
  254. self.oneofs_by_name = dict((o.name, o) for o in self.oneofs)
  255. for oneof in self.oneofs:
  256. oneof.containing_type = self
  257. self.syntax = syntax or "proto2"
  258. @property
  259. def fields_by_camelcase_name(self):
  260. if self._fields_by_camelcase_name is None:
  261. self._fields_by_camelcase_name = dict(
  262. (f.camelcase_name, f) for f in self.fields)
  263. return self._fields_by_camelcase_name
  264. def EnumValueName(self, enum, value):
  265. """Returns the string name of an enum value.
  266. This is just a small helper method to simplify a common operation.
  267. Args:
  268. enum: string name of the Enum.
  269. value: int, value of the enum.
  270. Returns:
  271. string name of the enum value.
  272. Raises:
  273. KeyError if either the Enum doesn't exist or the value is not a valid
  274. value for the enum.
  275. """
  276. return self.enum_types_by_name[enum].values_by_number[value].name
  277. def CopyToProto(self, proto):
  278. """Copies this to a descriptor_pb2.DescriptorProto.
  279. Args:
  280. proto: An empty descriptor_pb2.DescriptorProto.
  281. """
  282. # This function is overridden to give a better doc comment.
  283. super(Descriptor, self).CopyToProto(proto)
  284. # TODO(robinson): We should have aggressive checking here,
  285. # for example:
  286. # * If you specify a repeated field, you should not be allowed
  287. # to specify a default value.
  288. # * [Other examples here as needed].
  289. #
  290. # TODO(robinson): for this and other *Descriptor classes, we
  291. # might also want to lock things down aggressively (e.g.,
  292. # prevent clients from setting the attributes). Having
  293. # stronger invariants here in general will reduce the number
  294. # of runtime checks we must do in reflection.py...
  295. class FieldDescriptor(DescriptorBase):
  296. """Descriptor for a single field in a .proto file.
  297. A FieldDescriptor instance has the following attributes:
  298. name: (str) Name of this field, exactly as it appears in .proto.
  299. full_name: (str) Name of this field, including containing scope. This is
  300. particularly relevant for extensions.
  301. camelcase_name: (str) Camelcase name of this field.
  302. index: (int) Dense, 0-indexed index giving the order that this
  303. field textually appears within its message in the .proto file.
  304. number: (int) Tag number declared for this field in the .proto file.
  305. type: (One of the TYPE_* constants below) Declared type.
  306. cpp_type: (One of the CPPTYPE_* constants below) C++ type used to
  307. represent this field.
  308. label: (One of the LABEL_* constants below) Tells whether this
  309. field is optional, required, or repeated.
  310. has_default_value: (bool) True if this field has a default value defined,
  311. otherwise false.
  312. default_value: (Varies) Default value of this field. Only
  313. meaningful for non-repeated scalar fields. Repeated fields
  314. should always set this to [], and non-repeated composite
  315. fields should always set this to None.
  316. containing_type: (Descriptor) Descriptor of the protocol message
  317. type that contains this field. Set by the Descriptor constructor
  318. if we're passed into one.
  319. Somewhat confusingly, for extension fields, this is the
  320. descriptor of the EXTENDED message, not the descriptor
  321. of the message containing this field. (See is_extension and
  322. extension_scope below).
  323. message_type: (Descriptor) If a composite field, a descriptor
  324. of the message type contained in this field. Otherwise, this is None.
  325. enum_type: (EnumDescriptor) If this field contains an enum, a
  326. descriptor of that enum. Otherwise, this is None.
  327. is_extension: True iff this describes an extension field.
  328. extension_scope: (Descriptor) Only meaningful if is_extension is True.
  329. Gives the message that immediately contains this extension field.
  330. Will be None iff we're a top-level (file-level) extension field.
  331. options: (descriptor_pb2.FieldOptions) Protocol message field options or
  332. None to use default field options.
  333. containing_oneof: (OneofDescriptor) If the field is a member of a oneof
  334. union, contains its descriptor. Otherwise, None.
  335. file: (FileDescriptor) Reference to file descriptor.
  336. """
  337. # Must be consistent with C++ FieldDescriptor::Type enum in
  338. # descriptor.h.
  339. #
  340. # TODO(robinson): Find a way to eliminate this repetition.
  341. TYPE_DOUBLE = 1
  342. TYPE_FLOAT = 2
  343. TYPE_INT64 = 3
  344. TYPE_UINT64 = 4
  345. TYPE_INT32 = 5
  346. TYPE_FIXED64 = 6
  347. TYPE_FIXED32 = 7
  348. TYPE_BOOL = 8
  349. TYPE_STRING = 9
  350. TYPE_GROUP = 10
  351. TYPE_MESSAGE = 11
  352. TYPE_BYTES = 12
  353. TYPE_UINT32 = 13
  354. TYPE_ENUM = 14
  355. TYPE_SFIXED32 = 15
  356. TYPE_SFIXED64 = 16
  357. TYPE_SINT32 = 17
  358. TYPE_SINT64 = 18
  359. MAX_TYPE = 18
  360. # Must be consistent with C++ FieldDescriptor::CppType enum in
  361. # descriptor.h.
  362. #
  363. # TODO(robinson): Find a way to eliminate this repetition.
  364. CPPTYPE_INT32 = 1
  365. CPPTYPE_INT64 = 2
  366. CPPTYPE_UINT32 = 3
  367. CPPTYPE_UINT64 = 4
  368. CPPTYPE_DOUBLE = 5
  369. CPPTYPE_FLOAT = 6
  370. CPPTYPE_BOOL = 7
  371. CPPTYPE_ENUM = 8
  372. CPPTYPE_STRING = 9
  373. CPPTYPE_MESSAGE = 10
  374. MAX_CPPTYPE = 10
  375. _PYTHON_TO_CPP_PROTO_TYPE_MAP = {
  376. TYPE_DOUBLE: CPPTYPE_DOUBLE,
  377. TYPE_FLOAT: CPPTYPE_FLOAT,
  378. TYPE_ENUM: CPPTYPE_ENUM,
  379. TYPE_INT64: CPPTYPE_INT64,
  380. TYPE_SINT64: CPPTYPE_INT64,
  381. TYPE_SFIXED64: CPPTYPE_INT64,
  382. TYPE_UINT64: CPPTYPE_UINT64,
  383. TYPE_FIXED64: CPPTYPE_UINT64,
  384. TYPE_INT32: CPPTYPE_INT32,
  385. TYPE_SFIXED32: CPPTYPE_INT32,
  386. TYPE_SINT32: CPPTYPE_INT32,
  387. TYPE_UINT32: CPPTYPE_UINT32,
  388. TYPE_FIXED32: CPPTYPE_UINT32,
  389. TYPE_BYTES: CPPTYPE_STRING,
  390. TYPE_STRING: CPPTYPE_STRING,
  391. TYPE_BOOL: CPPTYPE_BOOL,
  392. TYPE_MESSAGE: CPPTYPE_MESSAGE,
  393. TYPE_GROUP: CPPTYPE_MESSAGE
  394. }
  395. # Must be consistent with C++ FieldDescriptor::Label enum in
  396. # descriptor.h.
  397. #
  398. # TODO(robinson): Find a way to eliminate this repetition.
  399. LABEL_OPTIONAL = 1
  400. LABEL_REQUIRED = 2
  401. LABEL_REPEATED = 3
  402. MAX_LABEL = 3
  403. # Must be consistent with C++ constants kMaxNumber, kFirstReservedNumber,
  404. # and kLastReservedNumber in descriptor.h
  405. MAX_FIELD_NUMBER = (1 << 29) - 1
  406. FIRST_RESERVED_FIELD_NUMBER = 19000
  407. LAST_RESERVED_FIELD_NUMBER = 19999
  408. if _USE_C_DESCRIPTORS:
  409. _C_DESCRIPTOR_CLASS = _message.FieldDescriptor
  410. def __new__(cls, name, full_name, index, number, type, cpp_type, label,
  411. default_value, message_type, enum_type, containing_type,
  412. is_extension, extension_scope, options=None,
  413. has_default_value=True, containing_oneof=None, json_name=None,
  414. file=None):
  415. _message.Message._CheckCalledFromGeneratedFile()
  416. if is_extension:
  417. return _message.default_pool.FindExtensionByName(full_name)
  418. else:
  419. return _message.default_pool.FindFieldByName(full_name)
  420. def __init__(self, name, full_name, index, number, type, cpp_type, label,
  421. default_value, message_type, enum_type, containing_type,
  422. is_extension, extension_scope, options=None,
  423. has_default_value=True, containing_oneof=None, json_name=None,
  424. file=None):
  425. """The arguments are as described in the description of FieldDescriptor
  426. attributes above.
  427. Note that containing_type may be None, and may be set later if necessary
  428. (to deal with circular references between message types, for example).
  429. Likewise for extension_scope.
  430. """
  431. super(FieldDescriptor, self).__init__(options, 'FieldOptions')
  432. self.name = name
  433. self.full_name = full_name
  434. self.file = file
  435. self._camelcase_name = None
  436. if json_name is None:
  437. self.json_name = _ToJsonName(name)
  438. else:
  439. self.json_name = json_name
  440. self.index = index
  441. self.number = number
  442. self.type = type
  443. self.cpp_type = cpp_type
  444. self.label = label
  445. self.has_default_value = has_default_value
  446. self.default_value = default_value
  447. self.containing_type = containing_type
  448. self.message_type = message_type
  449. self.enum_type = enum_type
  450. self.is_extension = is_extension
  451. self.extension_scope = extension_scope
  452. self.containing_oneof = containing_oneof
  453. if api_implementation.Type() == 'cpp':
  454. if is_extension:
  455. self._cdescriptor = _message.default_pool.FindExtensionByName(full_name)
  456. else:
  457. self._cdescriptor = _message.default_pool.FindFieldByName(full_name)
  458. else:
  459. self._cdescriptor = None
  460. @property
  461. def camelcase_name(self):
  462. if self._camelcase_name is None:
  463. self._camelcase_name = _ToCamelCase(self.name)
  464. return self._camelcase_name
  465. @staticmethod
  466. def ProtoTypeToCppProtoType(proto_type):
  467. """Converts from a Python proto type to a C++ Proto Type.
  468. The Python ProtocolBuffer classes specify both the 'Python' datatype and the
  469. 'C++' datatype - and they're not the same. This helper method should
  470. translate from one to another.
  471. Args:
  472. proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
  473. Returns:
  474. descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
  475. Raises:
  476. TypeTransformationError: when the Python proto type isn't known.
  477. """
  478. try:
  479. return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
  480. except KeyError:
  481. raise TypeTransformationError('Unknown proto_type: %s' % proto_type)
  482. class EnumDescriptor(_NestedDescriptorBase):
  483. """Descriptor for an enum defined in a .proto file.
  484. An EnumDescriptor instance has the following attributes:
  485. name: (str) Name of the enum type.
  486. full_name: (str) Full name of the type, including package name
  487. and any enclosing type(s).
  488. values: (list of EnumValueDescriptors) List of the values
  489. in this enum.
  490. values_by_name: (dict str -> EnumValueDescriptor) Same as |values|,
  491. but indexed by the "name" field of each EnumValueDescriptor.
  492. values_by_number: (dict int -> EnumValueDescriptor) Same as |values|,
  493. but indexed by the "number" field of each EnumValueDescriptor.
  494. containing_type: (Descriptor) Descriptor of the immediate containing
  495. type of this enum, or None if this is an enum defined at the
  496. top level in a .proto file. Set by Descriptor's constructor
  497. if we're passed into one.
  498. file: (FileDescriptor) Reference to file descriptor.
  499. options: (descriptor_pb2.EnumOptions) Enum options message or
  500. None to use default enum options.
  501. """
  502. if _USE_C_DESCRIPTORS:
  503. _C_DESCRIPTOR_CLASS = _message.EnumDescriptor
  504. def __new__(cls, name, full_name, filename, values,
  505. containing_type=None, options=None, file=None,
  506. serialized_start=None, serialized_end=None):
  507. _message.Message._CheckCalledFromGeneratedFile()
  508. return _message.default_pool.FindEnumTypeByName(full_name)
  509. def __init__(self, name, full_name, filename, values,
  510. containing_type=None, options=None, file=None,
  511. serialized_start=None, serialized_end=None):
  512. """Arguments are as described in the attribute description above.
  513. Note that filename is an obsolete argument, that is not used anymore.
  514. Please use file.name to access this as an attribute.
  515. """
  516. super(EnumDescriptor, self).__init__(
  517. options, 'EnumOptions', name, full_name, file,
  518. containing_type, serialized_start=serialized_start,
  519. serialized_end=serialized_end)
  520. self.values = values
  521. for value in self.values:
  522. value.type = self
  523. self.values_by_name = dict((v.name, v) for v in values)
  524. self.values_by_number = dict((v.number, v) for v in values)
  525. def CopyToProto(self, proto):
  526. """Copies this to a descriptor_pb2.EnumDescriptorProto.
  527. Args:
  528. proto: An empty descriptor_pb2.EnumDescriptorProto.
  529. """
  530. # This function is overridden to give a better doc comment.
  531. super(EnumDescriptor, self).CopyToProto(proto)
  532. class EnumValueDescriptor(DescriptorBase):
  533. """Descriptor for a single value within an enum.
  534. name: (str) Name of this value.
  535. index: (int) Dense, 0-indexed index giving the order that this
  536. value appears textually within its enum in the .proto file.
  537. number: (int) Actual number assigned to this enum value.
  538. type: (EnumDescriptor) EnumDescriptor to which this value
  539. belongs. Set by EnumDescriptor's constructor if we're
  540. passed into one.
  541. options: (descriptor_pb2.EnumValueOptions) Enum value options message or
  542. None to use default enum value options options.
  543. """
  544. if _USE_C_DESCRIPTORS:
  545. _C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor
  546. def __new__(cls, name, index, number, type=None, options=None):
  547. _message.Message._CheckCalledFromGeneratedFile()
  548. # There is no way we can build a complete EnumValueDescriptor with the
  549. # given parameters (the name of the Enum is not known, for example).
  550. # Fortunately generated files just pass it to the EnumDescriptor()
  551. # constructor, which will ignore it, so returning None is good enough.
  552. return None
  553. def __init__(self, name, index, number, type=None, options=None):
  554. """Arguments are as described in the attribute description above."""
  555. super(EnumValueDescriptor, self).__init__(options, 'EnumValueOptions')
  556. self.name = name
  557. self.index = index
  558. self.number = number
  559. self.type = type
  560. class OneofDescriptor(DescriptorBase):
  561. """Descriptor for a oneof field.
  562. name: (str) Name of the oneof field.
  563. full_name: (str) Full name of the oneof field, including package name.
  564. index: (int) 0-based index giving the order of the oneof field inside
  565. its containing type.
  566. containing_type: (Descriptor) Descriptor of the protocol message
  567. type that contains this field. Set by the Descriptor constructor
  568. if we're passed into one.
  569. fields: (list of FieldDescriptor) The list of field descriptors this
  570. oneof can contain.
  571. """
  572. if _USE_C_DESCRIPTORS:
  573. _C_DESCRIPTOR_CLASS = _message.OneofDescriptor
  574. def __new__(
  575. cls, name, full_name, index, containing_type, fields, options=None):
  576. _message.Message._CheckCalledFromGeneratedFile()
  577. return _message.default_pool.FindOneofByName(full_name)
  578. def __init__(
  579. self, name, full_name, index, containing_type, fields, options=None):
  580. """Arguments are as described in the attribute description above."""
  581. super(OneofDescriptor, self).__init__(options, 'OneofOptions')
  582. self.name = name
  583. self.full_name = full_name
  584. self.index = index
  585. self.containing_type = containing_type
  586. self.fields = fields
  587. class ServiceDescriptor(_NestedDescriptorBase):
  588. """Descriptor for a service.
  589. name: (str) Name of the service.
  590. full_name: (str) Full name of the service, including package name.
  591. index: (int) 0-indexed index giving the order that this services
  592. definition appears withing the .proto file.
  593. methods: (list of MethodDescriptor) List of methods provided by this
  594. service.
  595. methods_by_name: (dict str -> MethodDescriptor) Same MethodDescriptor
  596. objects as in |methods_by_name|, but indexed by "name" attribute in each
  597. MethodDescriptor.
  598. options: (descriptor_pb2.ServiceOptions) Service options message or
  599. None to use default service options.
  600. file: (FileDescriptor) Reference to file info.
  601. """
  602. if _USE_C_DESCRIPTORS:
  603. _C_DESCRIPTOR_CLASS = _message.ServiceDescriptor
  604. def __new__(cls, name, full_name, index, methods, options=None, file=None, # pylint: disable=redefined-builtin
  605. serialized_start=None, serialized_end=None):
  606. _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
  607. return _message.default_pool.FindServiceByName(full_name)
  608. def __init__(self, name, full_name, index, methods, options=None, file=None,
  609. serialized_start=None, serialized_end=None):
  610. super(ServiceDescriptor, self).__init__(
  611. options, 'ServiceOptions', name, full_name, file,
  612. None, serialized_start=serialized_start,
  613. serialized_end=serialized_end)
  614. self.index = index
  615. self.methods = methods
  616. self.methods_by_name = dict((m.name, m) for m in methods)
  617. # Set the containing service for each method in this service.
  618. for method in self.methods:
  619. method.containing_service = self
  620. def FindMethodByName(self, name):
  621. """Searches for the specified method, and returns its descriptor."""
  622. return self.methods_by_name.get(name, None)
  623. def CopyToProto(self, proto):
  624. """Copies this to a descriptor_pb2.ServiceDescriptorProto.
  625. Args:
  626. proto: An empty descriptor_pb2.ServiceDescriptorProto.
  627. """
  628. # This function is overridden to give a better doc comment.
  629. super(ServiceDescriptor, self).CopyToProto(proto)
  630. class MethodDescriptor(DescriptorBase):
  631. """Descriptor for a method in a service.
  632. name: (str) Name of the method within the service.
  633. full_name: (str) Full name of method.
  634. index: (int) 0-indexed index of the method inside the service.
  635. containing_service: (ServiceDescriptor) The service that contains this
  636. method.
  637. input_type: The descriptor of the message that this method accepts.
  638. output_type: The descriptor of the message that this method returns.
  639. options: (descriptor_pb2.MethodOptions) Method options message or
  640. None to use default method options.
  641. """
  642. if _USE_C_DESCRIPTORS:
  643. _C_DESCRIPTOR_CLASS = _message.MethodDescriptor
  644. def __new__(cls, name, full_name, index, containing_service,
  645. input_type, output_type, options=None):
  646. _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
  647. return _message.default_pool.FindMethodByName(full_name)
  648. def __init__(self, name, full_name, index, containing_service,
  649. input_type, output_type, options=None):
  650. """The arguments are as described in the description of MethodDescriptor
  651. attributes above.
  652. Note that containing_service may be None, and may be set later if necessary.
  653. """
  654. super(MethodDescriptor, self).__init__(options, 'MethodOptions')
  655. self.name = name
  656. self.full_name = full_name
  657. self.index = index
  658. self.containing_service = containing_service
  659. self.input_type = input_type
  660. self.output_type = output_type
  661. class FileDescriptor(DescriptorBase):
  662. """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto.
  663. Note that enum_types_by_name, extensions_by_name, and dependencies
  664. fields are only set by the message_factory module, and not by the
  665. generated proto code.
  666. name: name of file, relative to root of source tree.
  667. package: name of the package
  668. syntax: string indicating syntax of the file (can be "proto2" or "proto3")
  669. serialized_pb: (str) Byte string of serialized
  670. descriptor_pb2.FileDescriptorProto.
  671. dependencies: List of other FileDescriptors this FileDescriptor depends on.
  672. public_dependencies: A list of FileDescriptors, subset of the dependencies
  673. above, which were declared as "public".
  674. message_types_by_name: Dict of message names of their descriptors.
  675. enum_types_by_name: Dict of enum names and their descriptors.
  676. extensions_by_name: Dict of extension names and their descriptors.
  677. services_by_name: Dict of services names and their descriptors.
  678. pool: the DescriptorPool this descriptor belongs to. When not passed to the
  679. constructor, the global default pool is used.
  680. """
  681. if _USE_C_DESCRIPTORS:
  682. _C_DESCRIPTOR_CLASS = _message.FileDescriptor
  683. def __new__(cls, name, package, options=None, serialized_pb=None,
  684. dependencies=None, public_dependencies=None,
  685. syntax=None, pool=None):
  686. # FileDescriptor() is called from various places, not only from generated
  687. # files, to register dynamic proto files and messages.
  688. if serialized_pb:
  689. # TODO(amauryfa): use the pool passed as argument. This will work only
  690. # for C++-implemented DescriptorPools.
  691. return _message.default_pool.AddSerializedFile(serialized_pb)
  692. else:
  693. return super(FileDescriptor, cls).__new__(cls)
  694. def __init__(self, name, package, options=None, serialized_pb=None,
  695. dependencies=None, public_dependencies=None,
  696. syntax=None, pool=None):
  697. """Constructor."""
  698. super(FileDescriptor, self).__init__(options, 'FileOptions')
  699. if pool is None:
  700. from google.protobuf import descriptor_pool
  701. pool = descriptor_pool.Default()
  702. self.pool = pool
  703. self.message_types_by_name = {}
  704. self.name = name
  705. self.package = package
  706. self.syntax = syntax or "proto2"
  707. self.serialized_pb = serialized_pb
  708. self.enum_types_by_name = {}
  709. self.extensions_by_name = {}
  710. self.services_by_name = {}
  711. self.dependencies = (dependencies or [])
  712. self.public_dependencies = (public_dependencies or [])
  713. if (api_implementation.Type() == 'cpp' and
  714. self.serialized_pb is not None):
  715. _message.default_pool.AddSerializedFile(self.serialized_pb)
  716. def CopyToProto(self, proto):
  717. """Copies this to a descriptor_pb2.FileDescriptorProto.
  718. Args:
  719. proto: An empty descriptor_pb2.FileDescriptorProto.
  720. """
  721. proto.ParseFromString(self.serialized_pb)
  722. def _ParseOptions(message, string):
  723. """Parses serialized options.
  724. This helper function is used to parse serialized options in generated
  725. proto2 files. It must not be used outside proto2.
  726. """
  727. message.ParseFromString(string)
  728. return message
  729. def _ToCamelCase(name):
  730. """Converts name to camel-case and returns it."""
  731. capitalize_next = False
  732. result = []
  733. for c in name:
  734. if c == '_':
  735. if result:
  736. capitalize_next = True
  737. elif capitalize_next:
  738. result.append(c.upper())
  739. capitalize_next = False
  740. else:
  741. result += c
  742. # Lower-case the first letter.
  743. if result and result[0].isupper():
  744. result[0] = result[0].lower()
  745. return ''.join(result)
  746. def _OptionsOrNone(descriptor_proto):
  747. """Returns the value of the field `options`, or None if it is not set."""
  748. if descriptor_proto.HasField('options'):
  749. return descriptor_proto.options
  750. else:
  751. return None
  752. def _ToJsonName(name):
  753. """Converts name to Json name and returns it."""
  754. capitalize_next = False
  755. result = []
  756. for c in name:
  757. if c == '_':
  758. capitalize_next = True
  759. elif capitalize_next:
  760. result.append(c.upper())
  761. capitalize_next = False
  762. else:
  763. result += c
  764. return ''.join(result)
  765. def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
  766. syntax=None):
  767. """Make a protobuf Descriptor given a DescriptorProto protobuf.
  768. Handles nested descriptors. Note that this is limited to the scope of defining
  769. a message inside of another message. Composite fields can currently only be
  770. resolved if the message is defined in the same scope as the field.
  771. Args:
  772. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  773. package: Optional package name for the new message Descriptor (string).
  774. build_file_if_cpp: Update the C++ descriptor pool if api matches.
  775. Set to False on recursion, so no duplicates are created.
  776. syntax: The syntax/semantics that should be used. Set to "proto3" to get
  777. proto3 field presence semantics.
  778. Returns:
  779. A Descriptor for protobuf messages.
  780. """
  781. if api_implementation.Type() == 'cpp' and build_file_if_cpp:
  782. # The C++ implementation requires all descriptors to be backed by the same
  783. # definition in the C++ descriptor pool. To do this, we build a
  784. # FileDescriptorProto with the same definition as this descriptor and build
  785. # it into the pool.
  786. from google.protobuf import descriptor_pb2
  787. file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
  788. file_descriptor_proto.message_type.add().MergeFrom(desc_proto)
  789. # Generate a random name for this proto file to prevent conflicts with any
  790. # imported ones. We need to specify a file name so the descriptor pool
  791. # accepts our FileDescriptorProto, but it is not important what that file
  792. # name is actually set to.
  793. proto_name = str(uuid.uuid4())
  794. if package:
  795. file_descriptor_proto.name = os.path.join(package.replace('.', '/'),
  796. proto_name + '.proto')
  797. file_descriptor_proto.package = package
  798. else:
  799. file_descriptor_proto.name = proto_name + '.proto'
  800. _message.default_pool.Add(file_descriptor_proto)
  801. result = _message.default_pool.FindFileByName(file_descriptor_proto.name)
  802. if _USE_C_DESCRIPTORS:
  803. return result.message_types_by_name[desc_proto.name]
  804. full_message_name = [desc_proto.name]
  805. if package: full_message_name.insert(0, package)
  806. # Create Descriptors for enum types
  807. enum_types = {}
  808. for enum_proto in desc_proto.enum_type:
  809. full_name = '.'.join(full_message_name + [enum_proto.name])
  810. enum_desc = EnumDescriptor(
  811. enum_proto.name, full_name, None, [
  812. EnumValueDescriptor(enum_val.name, ii, enum_val.number)
  813. for ii, enum_val in enumerate(enum_proto.value)])
  814. enum_types[full_name] = enum_desc
  815. # Create Descriptors for nested types
  816. nested_types = {}
  817. for nested_proto in desc_proto.nested_type:
  818. full_name = '.'.join(full_message_name + [nested_proto.name])
  819. # Nested types are just those defined inside of the message, not all types
  820. # used by fields in the message, so no loops are possible here.
  821. nested_desc = MakeDescriptor(nested_proto,
  822. package='.'.join(full_message_name),
  823. build_file_if_cpp=False,
  824. syntax=syntax)
  825. nested_types[full_name] = nested_desc
  826. fields = []
  827. for field_proto in desc_proto.field:
  828. full_name = '.'.join(full_message_name + [field_proto.name])
  829. enum_desc = None
  830. nested_desc = None
  831. if field_proto.json_name:
  832. json_name = field_proto.json_name
  833. else:
  834. json_name = None
  835. if field_proto.HasField('type_name'):
  836. type_name = field_proto.type_name
  837. full_type_name = '.'.join(full_message_name +
  838. [type_name[type_name.rfind('.')+1:]])
  839. if full_type_name in nested_types:
  840. nested_desc = nested_types[full_type_name]
  841. elif full_type_name in enum_types:
  842. enum_desc = enum_types[full_type_name]
  843. # Else type_name references a non-local type, which isn't implemented
  844. field = FieldDescriptor(
  845. field_proto.name, full_name, field_proto.number - 1,
  846. field_proto.number, field_proto.type,
  847. FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
  848. field_proto.label, None, nested_desc, enum_desc, None, False, None,
  849. options=_OptionsOrNone(field_proto), has_default_value=False,
  850. json_name=json_name)
  851. fields.append(field)
  852. desc_name = '.'.join(full_message_name)
  853. return Descriptor(desc_proto.name, desc_name, None, None, fields,
  854. list(nested_types.values()), list(enum_types.values()), [],
  855. options=_OptionsOrNone(desc_proto))