descriptor.py 41 KB

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