descriptor.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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. """
  336. # Must be consistent with C++ FieldDescriptor::Type enum in
  337. # descriptor.h.
  338. #
  339. # TODO(robinson): Find a way to eliminate this repetition.
  340. TYPE_DOUBLE = 1
  341. TYPE_FLOAT = 2
  342. TYPE_INT64 = 3
  343. TYPE_UINT64 = 4
  344. TYPE_INT32 = 5
  345. TYPE_FIXED64 = 6
  346. TYPE_FIXED32 = 7
  347. TYPE_BOOL = 8
  348. TYPE_STRING = 9
  349. TYPE_GROUP = 10
  350. TYPE_MESSAGE = 11
  351. TYPE_BYTES = 12
  352. TYPE_UINT32 = 13
  353. TYPE_ENUM = 14
  354. TYPE_SFIXED32 = 15
  355. TYPE_SFIXED64 = 16
  356. TYPE_SINT32 = 17
  357. TYPE_SINT64 = 18
  358. MAX_TYPE = 18
  359. # Must be consistent with C++ FieldDescriptor::CppType enum in
  360. # descriptor.h.
  361. #
  362. # TODO(robinson): Find a way to eliminate this repetition.
  363. CPPTYPE_INT32 = 1
  364. CPPTYPE_INT64 = 2
  365. CPPTYPE_UINT32 = 3
  366. CPPTYPE_UINT64 = 4
  367. CPPTYPE_DOUBLE = 5
  368. CPPTYPE_FLOAT = 6
  369. CPPTYPE_BOOL = 7
  370. CPPTYPE_ENUM = 8
  371. CPPTYPE_STRING = 9
  372. CPPTYPE_MESSAGE = 10
  373. MAX_CPPTYPE = 10
  374. _PYTHON_TO_CPP_PROTO_TYPE_MAP = {
  375. TYPE_DOUBLE: CPPTYPE_DOUBLE,
  376. TYPE_FLOAT: CPPTYPE_FLOAT,
  377. TYPE_ENUM: CPPTYPE_ENUM,
  378. TYPE_INT64: CPPTYPE_INT64,
  379. TYPE_SINT64: CPPTYPE_INT64,
  380. TYPE_SFIXED64: CPPTYPE_INT64,
  381. TYPE_UINT64: CPPTYPE_UINT64,
  382. TYPE_FIXED64: CPPTYPE_UINT64,
  383. TYPE_INT32: CPPTYPE_INT32,
  384. TYPE_SFIXED32: CPPTYPE_INT32,
  385. TYPE_SINT32: CPPTYPE_INT32,
  386. TYPE_UINT32: CPPTYPE_UINT32,
  387. TYPE_FIXED32: CPPTYPE_UINT32,
  388. TYPE_BYTES: CPPTYPE_STRING,
  389. TYPE_STRING: CPPTYPE_STRING,
  390. TYPE_BOOL: CPPTYPE_BOOL,
  391. TYPE_MESSAGE: CPPTYPE_MESSAGE,
  392. TYPE_GROUP: CPPTYPE_MESSAGE
  393. }
  394. # Must be consistent with C++ FieldDescriptor::Label enum in
  395. # descriptor.h.
  396. #
  397. # TODO(robinson): Find a way to eliminate this repetition.
  398. LABEL_OPTIONAL = 1
  399. LABEL_REQUIRED = 2
  400. LABEL_REPEATED = 3
  401. MAX_LABEL = 3
  402. # Must be consistent with C++ constants kMaxNumber, kFirstReservedNumber,
  403. # and kLastReservedNumber in descriptor.h
  404. MAX_FIELD_NUMBER = (1 << 29) - 1
  405. FIRST_RESERVED_FIELD_NUMBER = 19000
  406. LAST_RESERVED_FIELD_NUMBER = 19999
  407. if _USE_C_DESCRIPTORS:
  408. _C_DESCRIPTOR_CLASS = _message.FieldDescriptor
  409. def __new__(cls, name, full_name, index, number, type, cpp_type, label,
  410. default_value, message_type, enum_type, containing_type,
  411. is_extension, extension_scope, options=None,
  412. has_default_value=True, containing_oneof=None, json_name=None):
  413. _message.Message._CheckCalledFromGeneratedFile()
  414. if is_extension:
  415. return _message.default_pool.FindExtensionByName(full_name)
  416. else:
  417. return _message.default_pool.FindFieldByName(full_name)
  418. def __init__(self, name, full_name, index, number, type, cpp_type, label,
  419. default_value, message_type, enum_type, containing_type,
  420. is_extension, extension_scope, options=None,
  421. has_default_value=True, containing_oneof=None, json_name=None):
  422. """The arguments are as described in the description of FieldDescriptor
  423. attributes above.
  424. Note that containing_type may be None, and may be set later if necessary
  425. (to deal with circular references between message types, for example).
  426. Likewise for extension_scope.
  427. """
  428. super(FieldDescriptor, self).__init__(options, 'FieldOptions')
  429. self.name = name
  430. self.full_name = full_name
  431. self._camelcase_name = None
  432. if json_name is None:
  433. self.json_name = _ToJsonName(name)
  434. else:
  435. self.json_name = json_name
  436. self.index = index
  437. self.number = number
  438. self.type = type
  439. self.cpp_type = cpp_type
  440. self.label = label
  441. self.has_default_value = has_default_value
  442. self.default_value = default_value
  443. self.containing_type = containing_type
  444. self.message_type = message_type
  445. self.enum_type = enum_type
  446. self.is_extension = is_extension
  447. self.extension_scope = extension_scope
  448. self.containing_oneof = containing_oneof
  449. if api_implementation.Type() == 'cpp':
  450. if is_extension:
  451. self._cdescriptor = _message.default_pool.FindExtensionByName(full_name)
  452. else:
  453. self._cdescriptor = _message.default_pool.FindFieldByName(full_name)
  454. else:
  455. self._cdescriptor = None
  456. @property
  457. def camelcase_name(self):
  458. if self._camelcase_name is None:
  459. self._camelcase_name = _ToCamelCase(self.name)
  460. return self._camelcase_name
  461. @staticmethod
  462. def ProtoTypeToCppProtoType(proto_type):
  463. """Converts from a Python proto type to a C++ Proto Type.
  464. The Python ProtocolBuffer classes specify both the 'Python' datatype and the
  465. 'C++' datatype - and they're not the same. This helper method should
  466. translate from one to another.
  467. Args:
  468. proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
  469. Returns:
  470. descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
  471. Raises:
  472. TypeTransformationError: when the Python proto type isn't known.
  473. """
  474. try:
  475. return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
  476. except KeyError:
  477. raise TypeTransformationError('Unknown proto_type: %s' % proto_type)
  478. class EnumDescriptor(_NestedDescriptorBase):
  479. """Descriptor for an enum defined in a .proto file.
  480. An EnumDescriptor instance has the following attributes:
  481. name: (str) Name of the enum type.
  482. full_name: (str) Full name of the type, including package name
  483. and any enclosing type(s).
  484. values: (list of EnumValueDescriptors) List of the values
  485. in this enum.
  486. values_by_name: (dict str -> EnumValueDescriptor) Same as |values|,
  487. but indexed by the "name" field of each EnumValueDescriptor.
  488. values_by_number: (dict int -> EnumValueDescriptor) Same as |values|,
  489. but indexed by the "number" field of each EnumValueDescriptor.
  490. containing_type: (Descriptor) Descriptor of the immediate containing
  491. type of this enum, or None if this is an enum defined at the
  492. top level in a .proto file. Set by Descriptor's constructor
  493. if we're passed into one.
  494. file: (FileDescriptor) Reference to file descriptor.
  495. options: (descriptor_pb2.EnumOptions) Enum options message or
  496. None to use default enum options.
  497. """
  498. if _USE_C_DESCRIPTORS:
  499. _C_DESCRIPTOR_CLASS = _message.EnumDescriptor
  500. def __new__(cls, name, full_name, filename, values,
  501. containing_type=None, options=None, file=None,
  502. serialized_start=None, serialized_end=None):
  503. _message.Message._CheckCalledFromGeneratedFile()
  504. return _message.default_pool.FindEnumTypeByName(full_name)
  505. def __init__(self, name, full_name, filename, values,
  506. containing_type=None, options=None, file=None,
  507. serialized_start=None, serialized_end=None):
  508. """Arguments are as described in the attribute description above.
  509. Note that filename is an obsolete argument, that is not used anymore.
  510. Please use file.name to access this as an attribute.
  511. """
  512. super(EnumDescriptor, self).__init__(
  513. options, 'EnumOptions', name, full_name, file,
  514. containing_type, serialized_start=serialized_start,
  515. serialized_end=serialized_end)
  516. self.values = values
  517. for value in self.values:
  518. value.type = self
  519. self.values_by_name = dict((v.name, v) for v in values)
  520. self.values_by_number = dict((v.number, v) for v in values)
  521. def CopyToProto(self, proto):
  522. """Copies this to a descriptor_pb2.EnumDescriptorProto.
  523. Args:
  524. proto: An empty descriptor_pb2.EnumDescriptorProto.
  525. """
  526. # This function is overridden to give a better doc comment.
  527. super(EnumDescriptor, self).CopyToProto(proto)
  528. class EnumValueDescriptor(DescriptorBase):
  529. """Descriptor for a single value within an enum.
  530. name: (str) Name of this value.
  531. index: (int) Dense, 0-indexed index giving the order that this
  532. value appears textually within its enum in the .proto file.
  533. number: (int) Actual number assigned to this enum value.
  534. type: (EnumDescriptor) EnumDescriptor to which this value
  535. belongs. Set by EnumDescriptor's constructor if we're
  536. passed into one.
  537. options: (descriptor_pb2.EnumValueOptions) Enum value options message or
  538. None to use default enum value options options.
  539. """
  540. if _USE_C_DESCRIPTORS:
  541. _C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor
  542. def __new__(cls, name, index, number, type=None, options=None):
  543. _message.Message._CheckCalledFromGeneratedFile()
  544. # There is no way we can build a complete EnumValueDescriptor with the
  545. # given parameters (the name of the Enum is not known, for example).
  546. # Fortunately generated files just pass it to the EnumDescriptor()
  547. # constructor, which will ignore it, so returning None is good enough.
  548. return None
  549. def __init__(self, name, index, number, type=None, options=None):
  550. """Arguments are as described in the attribute description above."""
  551. super(EnumValueDescriptor, self).__init__(options, 'EnumValueOptions')
  552. self.name = name
  553. self.index = index
  554. self.number = number
  555. self.type = type
  556. class OneofDescriptor(DescriptorBase):
  557. """Descriptor for a oneof field.
  558. name: (str) Name of the oneof field.
  559. full_name: (str) Full name of the oneof field, including package name.
  560. index: (int) 0-based index giving the order of the oneof field inside
  561. its containing type.
  562. containing_type: (Descriptor) Descriptor of the protocol message
  563. type that contains this field. Set by the Descriptor constructor
  564. if we're passed into one.
  565. fields: (list of FieldDescriptor) The list of field descriptors this
  566. oneof can contain.
  567. """
  568. if _USE_C_DESCRIPTORS:
  569. _C_DESCRIPTOR_CLASS = _message.OneofDescriptor
  570. def __new__(
  571. cls, name, full_name, index, containing_type, fields, options=None):
  572. _message.Message._CheckCalledFromGeneratedFile()
  573. return _message.default_pool.FindOneofByName(full_name)
  574. def __init__(
  575. self, name, full_name, index, containing_type, fields, options=None):
  576. """Arguments are as described in the attribute description above."""
  577. super(OneofDescriptor, self).__init__(options, 'OneofOptions')
  578. self.name = name
  579. self.full_name = full_name
  580. self.index = index
  581. self.containing_type = containing_type
  582. self.fields = fields
  583. class ServiceDescriptor(_NestedDescriptorBase):
  584. """Descriptor for a service.
  585. name: (str) Name of the service.
  586. full_name: (str) Full name of the service, including package name.
  587. index: (int) 0-indexed index giving the order that this services
  588. definition appears withing the .proto file.
  589. methods: (list of MethodDescriptor) List of methods provided by this
  590. service.
  591. methods_by_name: (dict str -> MethodDescriptor) Same MethodDescriptor
  592. objects as in |methods_by_name|, but indexed by "name" attribute in each
  593. MethodDescriptor.
  594. options: (descriptor_pb2.ServiceOptions) Service options message or
  595. None to use default service options.
  596. file: (FileDescriptor) Reference to file info.
  597. """
  598. if _USE_C_DESCRIPTORS:
  599. _C_DESCRIPTOR_CLASS = _message.ServiceDescriptor
  600. def __new__(cls, name, full_name, index, methods, options=None, file=None, # pylint: disable=redefined-builtin
  601. serialized_start=None, serialized_end=None):
  602. _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
  603. return _message.default_pool.FindServiceByName(full_name)
  604. def __init__(self, name, full_name, index, methods, options=None, file=None,
  605. serialized_start=None, serialized_end=None):
  606. super(ServiceDescriptor, self).__init__(
  607. options, 'ServiceOptions', name, full_name, file,
  608. None, serialized_start=serialized_start,
  609. serialized_end=serialized_end)
  610. self.index = index
  611. self.methods = methods
  612. self.methods_by_name = dict((m.name, m) for m in methods)
  613. # Set the containing service for each method in this service.
  614. for method in self.methods:
  615. method.containing_service = self
  616. def FindMethodByName(self, name):
  617. """Searches for the specified method, and returns its descriptor."""
  618. return self.methods_by_name.get(name, None)
  619. def CopyToProto(self, proto):
  620. """Copies this to a descriptor_pb2.ServiceDescriptorProto.
  621. Args:
  622. proto: An empty descriptor_pb2.ServiceDescriptorProto.
  623. """
  624. # This function is overridden to give a better doc comment.
  625. super(ServiceDescriptor, self).CopyToProto(proto)
  626. class MethodDescriptor(DescriptorBase):
  627. """Descriptor for a method in a service.
  628. name: (str) Name of the method within the service.
  629. full_name: (str) Full name of method.
  630. index: (int) 0-indexed index of the method inside the service.
  631. containing_service: (ServiceDescriptor) The service that contains this
  632. method.
  633. input_type: The descriptor of the message that this method accepts.
  634. output_type: The descriptor of the message that this method returns.
  635. options: (descriptor_pb2.MethodOptions) Method options message or
  636. None to use default method options.
  637. """
  638. if _USE_C_DESCRIPTORS:
  639. _C_DESCRIPTOR_CLASS = _message.MethodDescriptor
  640. def __new__(cls, name, full_name, index, containing_service,
  641. input_type, output_type, options=None):
  642. _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
  643. return _message.default_pool.FindMethodByName(full_name)
  644. def __init__(self, name, full_name, index, containing_service,
  645. input_type, output_type, options=None):
  646. """The arguments are as described in the description of MethodDescriptor
  647. attributes above.
  648. Note that containing_service may be None, and may be set later if necessary.
  649. """
  650. super(MethodDescriptor, self).__init__(options, 'MethodOptions')
  651. self.name = name
  652. self.full_name = full_name
  653. self.index = index
  654. self.containing_service = containing_service
  655. self.input_type = input_type
  656. self.output_type = output_type
  657. class FileDescriptor(DescriptorBase):
  658. """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto.
  659. Note that enum_types_by_name, extensions_by_name, and dependencies
  660. fields are only set by the message_factory module, and not by the
  661. generated proto code.
  662. name: name of file, relative to root of source tree.
  663. package: name of the package
  664. syntax: string indicating syntax of the file (can be "proto2" or "proto3")
  665. serialized_pb: (str) Byte string of serialized
  666. descriptor_pb2.FileDescriptorProto.
  667. dependencies: List of other FileDescriptors this FileDescriptor depends on.
  668. public_dependencies: A list of FileDescriptors, subset of the dependencies
  669. above, which were declared as "public".
  670. message_types_by_name: Dict of message names of their descriptors.
  671. enum_types_by_name: Dict of enum names and their descriptors.
  672. extensions_by_name: Dict of extension names and their descriptors.
  673. services_by_name: Dict of services names and their descriptors.
  674. pool: the DescriptorPool this descriptor belongs to. When not passed to the
  675. constructor, the global default pool is used.
  676. """
  677. if _USE_C_DESCRIPTORS:
  678. _C_DESCRIPTOR_CLASS = _message.FileDescriptor
  679. def __new__(cls, name, package, options=None, serialized_pb=None,
  680. dependencies=None, public_dependencies=None,
  681. syntax=None, pool=None):
  682. # FileDescriptor() is called from various places, not only from generated
  683. # files, to register dynamic proto files and messages.
  684. if serialized_pb:
  685. # TODO(amauryfa): use the pool passed as argument. This will work only
  686. # for C++-implemented DescriptorPools.
  687. return _message.default_pool.AddSerializedFile(serialized_pb)
  688. else:
  689. return super(FileDescriptor, cls).__new__(cls)
  690. def __init__(self, name, package, options=None, serialized_pb=None,
  691. dependencies=None, public_dependencies=None,
  692. syntax=None, pool=None):
  693. """Constructor."""
  694. super(FileDescriptor, self).__init__(options, 'FileOptions')
  695. if pool is None:
  696. from google.protobuf import descriptor_pool
  697. pool = descriptor_pool.Default()
  698. self.pool = pool
  699. self.message_types_by_name = {}
  700. self.name = name
  701. self.package = package
  702. self.syntax = syntax or "proto2"
  703. self.serialized_pb = serialized_pb
  704. self.enum_types_by_name = {}
  705. self.extensions_by_name = {}
  706. self.services_by_name = {}
  707. self.dependencies = (dependencies or [])
  708. self.public_dependencies = (public_dependencies or [])
  709. if (api_implementation.Type() == 'cpp' and
  710. self.serialized_pb is not None):
  711. _message.default_pool.AddSerializedFile(self.serialized_pb)
  712. def CopyToProto(self, proto):
  713. """Copies this to a descriptor_pb2.FileDescriptorProto.
  714. Args:
  715. proto: An empty descriptor_pb2.FileDescriptorProto.
  716. """
  717. proto.ParseFromString(self.serialized_pb)
  718. def _ParseOptions(message, string):
  719. """Parses serialized options.
  720. This helper function is used to parse serialized options in generated
  721. proto2 files. It must not be used outside proto2.
  722. """
  723. message.ParseFromString(string)
  724. return message
  725. def _ToCamelCase(name):
  726. """Converts name to camel-case and returns it."""
  727. capitalize_next = False
  728. result = []
  729. for c in name:
  730. if c == '_':
  731. if result:
  732. capitalize_next = True
  733. elif capitalize_next:
  734. result.append(c.upper())
  735. capitalize_next = False
  736. else:
  737. result += c
  738. # Lower-case the first letter.
  739. if result and result[0].isupper():
  740. result[0] = result[0].lower()
  741. return ''.join(result)
  742. def _OptionsOrNone(descriptor_proto):
  743. """Returns the value of the field `options`, or None if it is not set."""
  744. if descriptor_proto.HasField('options'):
  745. return descriptor_proto.options
  746. else:
  747. return None
  748. def _ToJsonName(name):
  749. """Converts name to Json name and returns it."""
  750. capitalize_next = False
  751. result = []
  752. for c in name:
  753. if c == '_':
  754. capitalize_next = True
  755. elif capitalize_next:
  756. result.append(c.upper())
  757. capitalize_next = False
  758. else:
  759. result += c
  760. return ''.join(result)
  761. def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
  762. syntax=None):
  763. """Make a protobuf Descriptor given a DescriptorProto protobuf.
  764. Handles nested descriptors. Note that this is limited to the scope of defining
  765. a message inside of another message. Composite fields can currently only be
  766. resolved if the message is defined in the same scope as the field.
  767. Args:
  768. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  769. package: Optional package name for the new message Descriptor (string).
  770. build_file_if_cpp: Update the C++ descriptor pool if api matches.
  771. Set to False on recursion, so no duplicates are created.
  772. syntax: The syntax/semantics that should be used. Set to "proto3" to get
  773. proto3 field presence semantics.
  774. Returns:
  775. A Descriptor for protobuf messages.
  776. """
  777. if api_implementation.Type() == 'cpp' and build_file_if_cpp:
  778. # The C++ implementation requires all descriptors to be backed by the same
  779. # definition in the C++ descriptor pool. To do this, we build a
  780. # FileDescriptorProto with the same definition as this descriptor and build
  781. # it into the pool.
  782. from google.protobuf import descriptor_pb2
  783. file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
  784. file_descriptor_proto.message_type.add().MergeFrom(desc_proto)
  785. # Generate a random name for this proto file to prevent conflicts with any
  786. # imported ones. We need to specify a file name so the descriptor pool
  787. # accepts our FileDescriptorProto, but it is not important what that file
  788. # name is actually set to.
  789. proto_name = str(uuid.uuid4())
  790. if package:
  791. file_descriptor_proto.name = os.path.join(package.replace('.', '/'),
  792. proto_name + '.proto')
  793. file_descriptor_proto.package = package
  794. else:
  795. file_descriptor_proto.name = proto_name + '.proto'
  796. _message.default_pool.Add(file_descriptor_proto)
  797. result = _message.default_pool.FindFileByName(file_descriptor_proto.name)
  798. if _USE_C_DESCRIPTORS:
  799. return result.message_types_by_name[desc_proto.name]
  800. full_message_name = [desc_proto.name]
  801. if package: full_message_name.insert(0, package)
  802. # Create Descriptors for enum types
  803. enum_types = {}
  804. for enum_proto in desc_proto.enum_type:
  805. full_name = '.'.join(full_message_name + [enum_proto.name])
  806. enum_desc = EnumDescriptor(
  807. enum_proto.name, full_name, None, [
  808. EnumValueDescriptor(enum_val.name, ii, enum_val.number)
  809. for ii, enum_val in enumerate(enum_proto.value)])
  810. enum_types[full_name] = enum_desc
  811. # Create Descriptors for nested types
  812. nested_types = {}
  813. for nested_proto in desc_proto.nested_type:
  814. full_name = '.'.join(full_message_name + [nested_proto.name])
  815. # Nested types are just those defined inside of the message, not all types
  816. # used by fields in the message, so no loops are possible here.
  817. nested_desc = MakeDescriptor(nested_proto,
  818. package='.'.join(full_message_name),
  819. build_file_if_cpp=False,
  820. syntax=syntax)
  821. nested_types[full_name] = nested_desc
  822. fields = []
  823. for field_proto in desc_proto.field:
  824. full_name = '.'.join(full_message_name + [field_proto.name])
  825. enum_desc = None
  826. nested_desc = None
  827. if field_proto.json_name:
  828. json_name = field_proto.json_name
  829. else:
  830. json_name = None
  831. if field_proto.HasField('type_name'):
  832. type_name = field_proto.type_name
  833. full_type_name = '.'.join(full_message_name +
  834. [type_name[type_name.rfind('.')+1:]])
  835. if full_type_name in nested_types:
  836. nested_desc = nested_types[full_type_name]
  837. elif full_type_name in enum_types:
  838. enum_desc = enum_types[full_type_name]
  839. # Else type_name references a non-local type, which isn't implemented
  840. field = FieldDescriptor(
  841. field_proto.name, full_name, field_proto.number - 1,
  842. field_proto.number, field_proto.type,
  843. FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
  844. field_proto.label, None, nested_desc, enum_desc, None, False, None,
  845. options=_OptionsOrNone(field_proto), has_default_value=False,
  846. json_name=json_name)
  847. fields.append(field)
  848. desc_name = '.'.join(full_message_name)
  849. return Descriptor(desc_proto.name, desc_name, None, None, fields,
  850. list(nested_types.values()), list(enum_types.values()), [],
  851. options=_OptionsOrNone(desc_proto))