descriptor.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  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. # Needs to stay compatible with Python 2.5 due to GAE.
  31. #
  32. # Copyright 2007 Google Inc. All Rights Reserved.
  33. """Descriptors essentially contain exactly the information found in a .proto
  34. file, in types that make this information accessible in Python.
  35. """
  36. __author__ = 'robinson@google.com (Will Robinson)'
  37. from google.protobuf.internal import api_implementation
  38. _USE_C_DESCRIPTORS = False
  39. if api_implementation.Type() == 'cpp':
  40. # Used by MakeDescriptor in cpp mode
  41. import os
  42. import uuid
  43. from google.protobuf.pyext import _message
  44. _USE_C_DESCRIPTORS = getattr(_message, '_USE_C_DESCRIPTORS', False)
  45. class Error(Exception):
  46. """Base error for this module."""
  47. class TypeTransformationError(Error):
  48. """Error transforming between python proto type and corresponding C++ type."""
  49. if _USE_C_DESCRIPTORS:
  50. # This metaclass allows to override the behavior of code like
  51. # isinstance(my_descriptor, FieldDescriptor)
  52. # and make it return True when the descriptor is an instance of the extension
  53. # type written in C++.
  54. class DescriptorMetaclass(type):
  55. def __instancecheck__(cls, obj):
  56. if super(DescriptorMetaclass, cls).__instancecheck__(obj):
  57. return True
  58. if isinstance(obj, cls._C_DESCRIPTOR_CLASS):
  59. return True
  60. return False
  61. else:
  62. # The standard metaclass; nothing changes.
  63. DescriptorMetaclass = type
  64. class DescriptorBase(object):
  65. """Descriptors base class.
  66. This class is the base of all descriptor classes. It provides common options
  67. related functionality.
  68. Attributes:
  69. has_options: True if the descriptor has non-default options. Usually it
  70. is not necessary to read this -- just call GetOptions() which will
  71. happily return the default instance. However, it's sometimes useful
  72. for efficiency, and also useful inside the protobuf implementation to
  73. avoid some bootstrapping issues.
  74. """
  75. __metaclass__ = DescriptorMetaclass
  76. if _USE_C_DESCRIPTORS:
  77. # The class, or tuple of classes, that are considered as "virtual
  78. # subclasses" of this descriptor class.
  79. _C_DESCRIPTOR_CLASS = ()
  80. def __init__(self, options, options_class_name):
  81. """Initialize the descriptor given its options message and the name of the
  82. class of the options message. The name of the class is required in case
  83. the options message is None and has to be created.
  84. """
  85. self._options = options
  86. self._options_class_name = options_class_name
  87. # Does this descriptor have non-default options?
  88. self.has_options = options is not None
  89. def _SetOptions(self, options, options_class_name):
  90. """Sets the descriptor's options
  91. This function is used in generated proto2 files to update descriptor
  92. options. It must not be used outside proto2.
  93. """
  94. self._options = options
  95. self._options_class_name = options_class_name
  96. # Does this descriptor have non-default options?
  97. self.has_options = options is not None
  98. def GetOptions(self):
  99. """Retrieves descriptor options.
  100. This method returns the options set or creates the default options for the
  101. descriptor.
  102. """
  103. if self._options:
  104. return self._options
  105. from google.protobuf import descriptor_pb2
  106. try:
  107. options_class = getattr(descriptor_pb2, self._options_class_name)
  108. except AttributeError:
  109. raise RuntimeError('Unknown options class name %s!' %
  110. (self._options_class_name))
  111. self._options = options_class()
  112. return self._options
  113. class _NestedDescriptorBase(DescriptorBase):
  114. """Common class for descriptors that can be nested."""
  115. def __init__(self, options, options_class_name, name, full_name,
  116. file, containing_type, serialized_start=None,
  117. serialized_end=None):
  118. """Constructor.
  119. Args:
  120. options: Protocol message options or None
  121. to use default message options.
  122. options_class_name: (str) The class name of the above options.
  123. name: (str) Name of this protocol message type.
  124. full_name: (str) Fully-qualified name of this protocol message type,
  125. which will include protocol "package" name and the name of any
  126. enclosing types.
  127. file: (FileDescriptor) Reference to file info.
  128. containing_type: if provided, this is a nested descriptor, with this
  129. descriptor as parent, otherwise None.
  130. serialized_start: The start index (inclusive) in block in the
  131. file.serialized_pb that describes this descriptor.
  132. serialized_end: The end index (exclusive) in block in the
  133. file.serialized_pb that describes this descriptor.
  134. """
  135. super(_NestedDescriptorBase, self).__init__(
  136. options, options_class_name)
  137. self.name = name
  138. # TODO(falk): Add function to calculate full_name instead of having it in
  139. # memory?
  140. self.full_name = full_name
  141. self.file = file
  142. self.containing_type = containing_type
  143. self._serialized_start = serialized_start
  144. self._serialized_end = serialized_end
  145. def GetTopLevelContainingType(self):
  146. """Returns the root if this is a nested type, or itself if its the root."""
  147. desc = self
  148. while desc.containing_type is not None:
  149. desc = desc.containing_type
  150. return desc
  151. def CopyToProto(self, proto):
  152. """Copies this to the matching proto in descriptor_pb2.
  153. Args:
  154. proto: An empty proto instance from descriptor_pb2.
  155. Raises:
  156. Error: If self couldnt be serialized, due to to few constructor arguments.
  157. """
  158. if (self.file is not None and
  159. self._serialized_start is not None and
  160. self._serialized_end is not None):
  161. proto.ParseFromString(self.file.serialized_pb[
  162. self._serialized_start:self._serialized_end])
  163. else:
  164. raise Error('Descriptor does not contain serialization.')
  165. class Descriptor(_NestedDescriptorBase):
  166. """Descriptor for a protocol message type.
  167. A Descriptor instance has the following attributes:
  168. name: (str) Name of this protocol message type.
  169. full_name: (str) Fully-qualified name of this protocol message type,
  170. which will include protocol "package" name and the name of any
  171. enclosing types.
  172. containing_type: (Descriptor) Reference to the descriptor of the
  173. type containing us, or None if this is top-level.
  174. fields: (list of FieldDescriptors) Field descriptors for all
  175. fields in this type.
  176. fields_by_number: (dict int -> FieldDescriptor) Same FieldDescriptor
  177. objects as in |fields|, but indexed by "number" attribute in each
  178. FieldDescriptor.
  179. fields_by_name: (dict str -> FieldDescriptor) Same FieldDescriptor
  180. objects as in |fields|, but indexed by "name" attribute in each
  181. FieldDescriptor.
  182. nested_types: (list of Descriptors) Descriptor references
  183. for all protocol message types nested within this one.
  184. nested_types_by_name: (dict str -> Descriptor) Same Descriptor
  185. objects as in |nested_types|, but indexed by "name" attribute
  186. in each Descriptor.
  187. enum_types: (list of EnumDescriptors) EnumDescriptor references
  188. for all enums contained within this type.
  189. enum_types_by_name: (dict str ->EnumDescriptor) Same EnumDescriptor
  190. objects as in |enum_types|, but indexed by "name" attribute
  191. in each EnumDescriptor.
  192. enum_values_by_name: (dict str -> EnumValueDescriptor) Dict mapping
  193. from enum value name to EnumValueDescriptor for that value.
  194. extensions: (list of FieldDescriptor) All extensions defined directly
  195. within this message type (NOT within a nested type).
  196. extensions_by_name: (dict, string -> FieldDescriptor) Same FieldDescriptor
  197. objects as |extensions|, but indexed by "name" attribute of each
  198. FieldDescriptor.
  199. is_extendable: Does this type define any extension ranges?
  200. options: (descriptor_pb2.MessageOptions) Protocol message options or None
  201. to use default message options.
  202. oneofs: (list of OneofDescriptor) The list of descriptors for oneof fields
  203. in this message.
  204. oneofs_by_name: (dict str -> OneofDescriptor) Same objects as in |oneofs|,
  205. but indexed by "name" attribute.
  206. file: (FileDescriptor) Reference to file descriptor.
  207. """
  208. if _USE_C_DESCRIPTORS:
  209. _C_DESCRIPTOR_CLASS = _message.Descriptor
  210. def __new__(cls, name, full_name, filename, containing_type, fields,
  211. nested_types, enum_types, extensions, options=None,
  212. is_extendable=True, extension_ranges=None, oneofs=None,
  213. file=None, serialized_start=None, serialized_end=None,
  214. syntax=None):
  215. _message.Message._CheckCalledFromGeneratedFile()
  216. return _message.Message._GetMessageDescriptor(full_name)
  217. # NOTE(tmarek): The file argument redefining a builtin is nothing we can
  218. # fix right now since we don't know how many clients already rely on the
  219. # name of the argument.
  220. def __init__(self, name, full_name, filename, containing_type, fields,
  221. nested_types, enum_types, extensions, options=None,
  222. is_extendable=True, extension_ranges=None, oneofs=None,
  223. file=None, serialized_start=None, serialized_end=None,
  224. syntax=None): # pylint:disable=redefined-builtin
  225. """Arguments to __init__() are as described in the description
  226. of Descriptor fields above.
  227. Note that filename is an obsolete argument, that is not used anymore.
  228. Please use file.name to access this as an attribute.
  229. """
  230. super(Descriptor, self).__init__(
  231. options, 'MessageOptions', name, full_name, file,
  232. containing_type, serialized_start=serialized_start,
  233. serialized_end=serialized_end)
  234. # We have fields in addition to fields_by_name and fields_by_number,
  235. # so that:
  236. # 1. Clients can index fields by "order in which they're listed."
  237. # 2. Clients can easily iterate over all fields with the terse
  238. # syntax: for f in descriptor.fields: ...
  239. self.fields = fields
  240. for field in self.fields:
  241. field.containing_type = self
  242. self.fields_by_number = dict((f.number, f) for f in fields)
  243. self.fields_by_name = dict((f.name, f) for f in fields)
  244. self.nested_types = nested_types
  245. for nested_type in nested_types:
  246. nested_type.containing_type = self
  247. self.nested_types_by_name = dict((t.name, t) for t in nested_types)
  248. self.enum_types = enum_types
  249. for enum_type in self.enum_types:
  250. enum_type.containing_type = self
  251. self.enum_types_by_name = dict((t.name, t) for t in enum_types)
  252. self.enum_values_by_name = dict(
  253. (v.name, v) for t in enum_types for v in t.values)
  254. self.extensions = extensions
  255. for extension in self.extensions:
  256. extension.extension_scope = self
  257. self.extensions_by_name = dict((f.name, f) for f in extensions)
  258. self.is_extendable = is_extendable
  259. self.extension_ranges = extension_ranges
  260. self.oneofs = oneofs if oneofs is not None else []
  261. self.oneofs_by_name = dict((o.name, o) for o in self.oneofs)
  262. for oneof in self.oneofs:
  263. oneof.containing_type = self
  264. self.syntax = syntax or "proto2"
  265. def EnumValueName(self, enum, value):
  266. """Returns the string name of an enum value.
  267. This is just a small helper method to simplify a common operation.
  268. Args:
  269. enum: string name of the Enum.
  270. value: int, value of the enum.
  271. Returns:
  272. string name of the enum value.
  273. Raises:
  274. KeyError if either the Enum doesn't exist or the value is not a valid
  275. value for the enum.
  276. """
  277. return self.enum_types_by_name[enum].values_by_number[value].name
  278. def CopyToProto(self, proto):
  279. """Copies this to a descriptor_pb2.DescriptorProto.
  280. Args:
  281. proto: An empty descriptor_pb2.DescriptorProto.
  282. """
  283. # This function is overriden to give a better doc comment.
  284. super(Descriptor, self).CopyToProto(proto)
  285. # TODO(robinson): We should have aggressive checking here,
  286. # for example:
  287. # * If you specify a repeated field, you should not be allowed
  288. # to specify a default value.
  289. # * [Other examples here as needed].
  290. #
  291. # TODO(robinson): for this and other *Descriptor classes, we
  292. # might also want to lock things down aggressively (e.g.,
  293. # prevent clients from setting the attributes). Having
  294. # stronger invariants here in general will reduce the number
  295. # of runtime checks we must do in reflection.py...
  296. class FieldDescriptor(DescriptorBase):
  297. """Descriptor for a single field in a .proto file.
  298. A FieldDescriptor instance has the following attributes:
  299. name: (str) Name of this field, exactly as it appears in .proto.
  300. full_name: (str) Name of this field, including containing scope. This is
  301. particularly relevant for extensions.
  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):
  413. _message.Message._CheckCalledFromGeneratedFile()
  414. if is_extension:
  415. return _message.Message._GetExtensionDescriptor(full_name)
  416. else:
  417. return _message.Message._GetFieldDescriptor(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):
  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.index = index
  432. self.number = number
  433. self.type = type
  434. self.cpp_type = cpp_type
  435. self.label = label
  436. self.has_default_value = has_default_value
  437. self.default_value = default_value
  438. self.containing_type = containing_type
  439. self.message_type = message_type
  440. self.enum_type = enum_type
  441. self.is_extension = is_extension
  442. self.extension_scope = extension_scope
  443. self.containing_oneof = containing_oneof
  444. if api_implementation.Type() == 'cpp':
  445. if is_extension:
  446. # pylint: disable=protected-access
  447. self._cdescriptor = (
  448. _message.Message._GetExtensionDescriptor(full_name))
  449. # pylint: enable=protected-access
  450. else:
  451. # pylint: disable=protected-access
  452. self._cdescriptor = _message.Message._GetFieldDescriptor(full_name)
  453. # pylint: enable=protected-access
  454. else:
  455. self._cdescriptor = None
  456. @staticmethod
  457. def ProtoTypeToCppProtoType(proto_type):
  458. """Converts from a Python proto type to a C++ Proto Type.
  459. The Python ProtocolBuffer classes specify both the 'Python' datatype and the
  460. 'C++' datatype - and they're not the same. This helper method should
  461. translate from one to another.
  462. Args:
  463. proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
  464. Returns:
  465. descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
  466. Raises:
  467. TypeTransformationError: when the Python proto type isn't known.
  468. """
  469. try:
  470. return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
  471. except KeyError:
  472. raise TypeTransformationError('Unknown proto_type: %s' % proto_type)
  473. class EnumDescriptor(_NestedDescriptorBase):
  474. """Descriptor for an enum defined in a .proto file.
  475. An EnumDescriptor instance has the following attributes:
  476. name: (str) Name of the enum type.
  477. full_name: (str) Full name of the type, including package name
  478. and any enclosing type(s).
  479. values: (list of EnumValueDescriptors) List of the values
  480. in this enum.
  481. values_by_name: (dict str -> EnumValueDescriptor) Same as |values|,
  482. but indexed by the "name" field of each EnumValueDescriptor.
  483. values_by_number: (dict int -> EnumValueDescriptor) Same as |values|,
  484. but indexed by the "number" field of each EnumValueDescriptor.
  485. containing_type: (Descriptor) Descriptor of the immediate containing
  486. type of this enum, or None if this is an enum defined at the
  487. top level in a .proto file. Set by Descriptor's constructor
  488. if we're passed into one.
  489. file: (FileDescriptor) Reference to file descriptor.
  490. options: (descriptor_pb2.EnumOptions) Enum options message or
  491. None to use default enum options.
  492. """
  493. if _USE_C_DESCRIPTORS:
  494. _C_DESCRIPTOR_CLASS = _message.EnumDescriptor
  495. def __new__(cls, name, full_name, filename, values,
  496. containing_type=None, options=None, file=None,
  497. serialized_start=None, serialized_end=None):
  498. _message.Message._CheckCalledFromGeneratedFile()
  499. return _message.Message._GetEnumDescriptor(full_name)
  500. def __init__(self, name, full_name, filename, values,
  501. containing_type=None, options=None, file=None,
  502. serialized_start=None, serialized_end=None):
  503. """Arguments are as described in the attribute description above.
  504. Note that filename is an obsolete argument, that is not used anymore.
  505. Please use file.name to access this as an attribute.
  506. """
  507. super(EnumDescriptor, self).__init__(
  508. options, 'EnumOptions', name, full_name, file,
  509. containing_type, serialized_start=serialized_start,
  510. serialized_end=serialized_end)
  511. self.values = values
  512. for value in self.values:
  513. value.type = self
  514. self.values_by_name = dict((v.name, v) for v in values)
  515. self.values_by_number = dict((v.number, v) for v in values)
  516. def CopyToProto(self, proto):
  517. """Copies this to a descriptor_pb2.EnumDescriptorProto.
  518. Args:
  519. proto: An empty descriptor_pb2.EnumDescriptorProto.
  520. """
  521. # This function is overriden to give a better doc comment.
  522. super(EnumDescriptor, self).CopyToProto(proto)
  523. class EnumValueDescriptor(DescriptorBase):
  524. """Descriptor for a single value within an enum.
  525. name: (str) Name of this value.
  526. index: (int) Dense, 0-indexed index giving the order that this
  527. value appears textually within its enum in the .proto file.
  528. number: (int) Actual number assigned to this enum value.
  529. type: (EnumDescriptor) EnumDescriptor to which this value
  530. belongs. Set by EnumDescriptor's constructor if we're
  531. passed into one.
  532. options: (descriptor_pb2.EnumValueOptions) Enum value options message or
  533. None to use default enum value options options.
  534. """
  535. if _USE_C_DESCRIPTORS:
  536. _C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor
  537. def __new__(cls, name, index, number, type=None, options=None):
  538. _message.Message._CheckCalledFromGeneratedFile()
  539. # There is no way we can build a complete EnumValueDescriptor with the
  540. # given parameters (the name of the Enum is not known, for example).
  541. # Fortunately generated files just pass it to the EnumDescriptor()
  542. # constructor, which will ignore it, so returning None is good enough.
  543. return None
  544. def __init__(self, name, index, number, type=None, options=None):
  545. """Arguments are as described in the attribute description above."""
  546. super(EnumValueDescriptor, self).__init__(options, 'EnumValueOptions')
  547. self.name = name
  548. self.index = index
  549. self.number = number
  550. self.type = type
  551. class OneofDescriptor(object):
  552. """Descriptor for a oneof field.
  553. name: (str) Name of the oneof field.
  554. full_name: (str) Full name of the oneof field, including package name.
  555. index: (int) 0-based index giving the order of the oneof field inside
  556. its containing type.
  557. containing_type: (Descriptor) Descriptor of the protocol message
  558. type that contains this field. Set by the Descriptor constructor
  559. if we're passed into one.
  560. fields: (list of FieldDescriptor) The list of field descriptors this
  561. oneof can contain.
  562. """
  563. if _USE_C_DESCRIPTORS:
  564. _C_DESCRIPTOR_CLASS = _message.OneofDescriptor
  565. def __new__(cls, name, full_name, index, containing_type, fields):
  566. _message.Message._CheckCalledFromGeneratedFile()
  567. return _message.Message._GetOneofDescriptor(full_name)
  568. def __init__(self, name, full_name, index, containing_type, fields):
  569. """Arguments are as described in the attribute description above."""
  570. self.name = name
  571. self.full_name = full_name
  572. self.index = index
  573. self.containing_type = containing_type
  574. self.fields = fields
  575. class ServiceDescriptor(_NestedDescriptorBase):
  576. """Descriptor for a service.
  577. name: (str) Name of the service.
  578. full_name: (str) Full name of the service, including package name.
  579. index: (int) 0-indexed index giving the order that this services
  580. definition appears withing the .proto file.
  581. methods: (list of MethodDescriptor) List of methods provided by this
  582. service.
  583. options: (descriptor_pb2.ServiceOptions) Service options message or
  584. None to use default service options.
  585. file: (FileDescriptor) Reference to file info.
  586. """
  587. def __init__(self, name, full_name, index, methods, options=None, file=None,
  588. serialized_start=None, serialized_end=None):
  589. super(ServiceDescriptor, self).__init__(
  590. options, 'ServiceOptions', name, full_name, file,
  591. None, serialized_start=serialized_start,
  592. serialized_end=serialized_end)
  593. self.index = index
  594. self.methods = methods
  595. # Set the containing service for each method in this service.
  596. for method in self.methods:
  597. method.containing_service = self
  598. def FindMethodByName(self, name):
  599. """Searches for the specified method, and returns its descriptor."""
  600. for method in self.methods:
  601. if name == method.name:
  602. return method
  603. return None
  604. def CopyToProto(self, proto):
  605. """Copies this to a descriptor_pb2.ServiceDescriptorProto.
  606. Args:
  607. proto: An empty descriptor_pb2.ServiceDescriptorProto.
  608. """
  609. # This function is overriden to give a better doc comment.
  610. super(ServiceDescriptor, self).CopyToProto(proto)
  611. class MethodDescriptor(DescriptorBase):
  612. """Descriptor for a method in a service.
  613. name: (str) Name of the method within the service.
  614. full_name: (str) Full name of method.
  615. index: (int) 0-indexed index of the method inside the service.
  616. containing_service: (ServiceDescriptor) The service that contains this
  617. method.
  618. input_type: The descriptor of the message that this method accepts.
  619. output_type: The descriptor of the message that this method returns.
  620. options: (descriptor_pb2.MethodOptions) Method options message or
  621. None to use default method options.
  622. """
  623. def __init__(self, name, full_name, index, containing_service,
  624. input_type, output_type, options=None):
  625. """The arguments are as described in the description of MethodDescriptor
  626. attributes above.
  627. Note that containing_service may be None, and may be set later if necessary.
  628. """
  629. super(MethodDescriptor, self).__init__(options, 'MethodOptions')
  630. self.name = name
  631. self.full_name = full_name
  632. self.index = index
  633. self.containing_service = containing_service
  634. self.input_type = input_type
  635. self.output_type = output_type
  636. class FileDescriptor(DescriptorBase):
  637. """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto.
  638. Note that enum_types_by_name, extensions_by_name, and dependencies
  639. fields are only set by the message_factory module, and not by the
  640. generated proto code.
  641. name: name of file, relative to root of source tree.
  642. package: name of the package
  643. syntax: string indicating syntax of the file (can be "proto2" or "proto3")
  644. serialized_pb: (str) Byte string of serialized
  645. descriptor_pb2.FileDescriptorProto.
  646. dependencies: List of other FileDescriptors this FileDescriptor depends on.
  647. message_types_by_name: Dict of message names of their descriptors.
  648. enum_types_by_name: Dict of enum names and their descriptors.
  649. extensions_by_name: Dict of extension names and their descriptors.
  650. """
  651. if _USE_C_DESCRIPTORS:
  652. _C_DESCRIPTOR_CLASS = _message.FileDescriptor
  653. def __new__(cls, name, package, options=None, serialized_pb=None,
  654. dependencies=None, syntax=None):
  655. # FileDescriptor() is called from various places, not only from generated
  656. # files, to register dynamic proto files and messages.
  657. # TODO(amauryfa): Expose BuildFile() as a public function and make this
  658. # constructor an implementation detail.
  659. if serialized_pb:
  660. # pylint: disable=protected-access2
  661. return _message.Message._BuildFile(serialized_pb)
  662. # pylint: enable=protected-access
  663. else:
  664. return super(FileDescriptor, cls).__new__(cls)
  665. def __init__(self, name, package, options=None, serialized_pb=None,
  666. dependencies=None, syntax=None):
  667. """Constructor."""
  668. super(FileDescriptor, self).__init__(options, 'FileOptions')
  669. self.message_types_by_name = {}
  670. self.name = name
  671. self.package = package
  672. self.syntax = syntax or "proto2"
  673. self.serialized_pb = serialized_pb
  674. self.enum_types_by_name = {}
  675. self.extensions_by_name = {}
  676. self.dependencies = (dependencies or [])
  677. if (api_implementation.Type() == 'cpp' and
  678. self.serialized_pb is not None):
  679. # pylint: disable=protected-access
  680. _message.Message._BuildFile(self.serialized_pb)
  681. # pylint: enable=protected-access
  682. def CopyToProto(self, proto):
  683. """Copies this to a descriptor_pb2.FileDescriptorProto.
  684. Args:
  685. proto: An empty descriptor_pb2.FileDescriptorProto.
  686. """
  687. proto.ParseFromString(self.serialized_pb)
  688. def _ParseOptions(message, string):
  689. """Parses serialized options.
  690. This helper function is used to parse serialized options in generated
  691. proto2 files. It must not be used outside proto2.
  692. """
  693. message.ParseFromString(string)
  694. return message
  695. def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
  696. syntax=None):
  697. """Make a protobuf Descriptor given a DescriptorProto protobuf.
  698. Handles nested descriptors. Note that this is limited to the scope of defining
  699. a message inside of another message. Composite fields can currently only be
  700. resolved if the message is defined in the same scope as the field.
  701. Args:
  702. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  703. package: Optional package name for the new message Descriptor (string).
  704. build_file_if_cpp: Update the C++ descriptor pool if api matches.
  705. Set to False on recursion, so no duplicates are created.
  706. syntax: The syntax/semantics that should be used. Set to "proto3" to get
  707. proto3 field presence semantics.
  708. Returns:
  709. A Descriptor for protobuf messages.
  710. """
  711. if api_implementation.Type() == 'cpp' and build_file_if_cpp:
  712. # The C++ implementation requires all descriptors to be backed by the same
  713. # definition in the C++ descriptor pool. To do this, we build a
  714. # FileDescriptorProto with the same definition as this descriptor and build
  715. # it into the pool.
  716. from google.protobuf import descriptor_pb2
  717. file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
  718. file_descriptor_proto.message_type.add().MergeFrom(desc_proto)
  719. # Generate a random name for this proto file to prevent conflicts with
  720. # any imported ones. We need to specify a file name so BuildFile accepts
  721. # our FileDescriptorProto, but it is not important what that file name
  722. # is actually set to.
  723. proto_name = str(uuid.uuid4())
  724. if package:
  725. file_descriptor_proto.name = os.path.join(package.replace('.', '/'),
  726. proto_name + '.proto')
  727. file_descriptor_proto.package = package
  728. else:
  729. file_descriptor_proto.name = proto_name + '.proto'
  730. # pylint: disable=protected-access
  731. result = _message.Message._BuildFile(
  732. file_descriptor_proto.SerializeToString())
  733. # pylint: enable=protected-access
  734. if _USE_C_DESCRIPTORS:
  735. return result.message_types_by_name[desc_proto.name]
  736. full_message_name = [desc_proto.name]
  737. if package: full_message_name.insert(0, package)
  738. # Create Descriptors for enum types
  739. enum_types = {}
  740. for enum_proto in desc_proto.enum_type:
  741. full_name = '.'.join(full_message_name + [enum_proto.name])
  742. enum_desc = EnumDescriptor(
  743. enum_proto.name, full_name, None, [
  744. EnumValueDescriptor(enum_val.name, ii, enum_val.number)
  745. for ii, enum_val in enumerate(enum_proto.value)])
  746. enum_types[full_name] = enum_desc
  747. # Create Descriptors for nested types
  748. nested_types = {}
  749. for nested_proto in desc_proto.nested_type:
  750. full_name = '.'.join(full_message_name + [nested_proto.name])
  751. # Nested types are just those defined inside of the message, not all types
  752. # used by fields in the message, so no loops are possible here.
  753. nested_desc = MakeDescriptor(nested_proto,
  754. package='.'.join(full_message_name),
  755. build_file_if_cpp=False,
  756. syntax=syntax)
  757. nested_types[full_name] = nested_desc
  758. fields = []
  759. for field_proto in desc_proto.field:
  760. full_name = '.'.join(full_message_name + [field_proto.name])
  761. enum_desc = None
  762. nested_desc = None
  763. if field_proto.HasField('type_name'):
  764. type_name = field_proto.type_name
  765. full_type_name = '.'.join(full_message_name +
  766. [type_name[type_name.rfind('.')+1:]])
  767. if full_type_name in nested_types:
  768. nested_desc = nested_types[full_type_name]
  769. elif full_type_name in enum_types:
  770. enum_desc = enum_types[full_type_name]
  771. # Else type_name references a non-local type, which isn't implemented
  772. field = FieldDescriptor(
  773. field_proto.name, full_name, field_proto.number - 1,
  774. field_proto.number, field_proto.type,
  775. FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
  776. field_proto.label, None, nested_desc, enum_desc, None, False, None,
  777. options=field_proto.options, has_default_value=False)
  778. fields.append(field)
  779. desc_name = '.'.join(full_message_name)
  780. return Descriptor(desc_proto.name, desc_name, None, None, fields,
  781. nested_types.values(), enum_types.values(), [],
  782. options=desc_proto.options)