Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

713 lines
26 KiB

  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # http://code.google.com/p/protobuf/
  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__ = '[email protected] (Will Robinson)'
  34. from google.protobuf.internal import api_implementation
  35. if api_implementation.Type() == 'cpp':
  36. if api_implementation.Version() == 2:
  37. from google.protobuf.internal.cpp import _message
  38. else:
  39. from google.protobuf.internal import cpp_message
  40. class Error(Exception):
  41. """Base error for this module."""
  42. class TypeTransformationError(Error):
  43. """Error transforming between python proto type and corresponding C++ type."""
  44. class DescriptorBase(object):
  45. """Descriptors base class.
  46. This class is the base of all descriptor classes. It provides common options
  47. related functionaility.
  48. Attributes:
  49. has_options: True if the descriptor has non-default options. Usually it
  50. is not necessary to read this -- just call GetOptions() which will
  51. happily return the default instance. However, it's sometimes useful
  52. for efficiency, and also useful inside the protobuf implementation to
  53. avoid some bootstrapping issues.
  54. """
  55. def __init__(self, options, options_class_name):
  56. """Initialize the descriptor given its options message and the name of the
  57. class of the options message. The name of the class is required in case
  58. the options message is None and has to be created.
  59. """
  60. self._options = options
  61. self._options_class_name = options_class_name
  62. # Does this descriptor have non-default options?
  63. self.has_options = options is not None
  64. def _SetOptions(self, options, options_class_name):
  65. """Sets the descriptor's options
  66. This function is used in generated proto2 files to update descriptor
  67. options. It must not be used outside proto2.
  68. """
  69. self._options = options
  70. self._options_class_name = options_class_name
  71. # Does this descriptor have non-default options?
  72. self.has_options = options is not None
  73. def GetOptions(self):
  74. """Retrieves descriptor options.
  75. This method returns the options set or creates the default options for the
  76. descriptor.
  77. """
  78. if self._options:
  79. return self._options
  80. from google.protobuf import descriptor_pb2
  81. try:
  82. options_class = getattr(descriptor_pb2, self._options_class_name)
  83. except AttributeError:
  84. raise RuntimeError('Unknown options class name %s!' %
  85. (self._options_class_name))
  86. self._options = options_class()
  87. return self._options
  88. class _NestedDescriptorBase(DescriptorBase):
  89. """Common class for descriptors that can be nested."""
  90. def __init__(self, options, options_class_name, name, full_name,
  91. file, containing_type, serialized_start=None,
  92. serialized_end=None):
  93. """Constructor.
  94. Args:
  95. options: Protocol message options or None
  96. to use default message options.
  97. options_class_name: (str) The class name of the above options.
  98. name: (str) Name of this protocol message type.
  99. full_name: (str) Fully-qualified name of this protocol message type,
  100. which will include protocol "package" name and the name of any
  101. enclosing types.
  102. file: (FileDescriptor) Reference to file info.
  103. containing_type: if provided, this is a nested descriptor, with this
  104. descriptor as parent, otherwise None.
  105. serialized_start: The start index (inclusive) in block in the
  106. file.serialized_pb that describes this descriptor.
  107. serialized_end: The end index (exclusive) in block in the
  108. file.serialized_pb that describes this descriptor.
  109. """
  110. super(_NestedDescriptorBase, self).__init__(
  111. options, options_class_name)
  112. self.name = name
  113. # TODO(falk): Add function to calculate full_name instead of having it in
  114. # memory?
  115. self.full_name = full_name
  116. self.file = file
  117. self.containing_type = containing_type
  118. self._serialized_start = serialized_start
  119. self._serialized_end = serialized_end
  120. def GetTopLevelContainingType(self):
  121. """Returns the root if this is a nested type, or itself if its the root."""
  122. desc = self
  123. while desc.containing_type is not None:
  124. desc = desc.containing_type
  125. return desc
  126. def CopyToProto(self, proto):
  127. """Copies this to the matching proto in descriptor_pb2.
  128. Args:
  129. proto: An empty proto instance from descriptor_pb2.
  130. Raises:
  131. Error: If self couldnt be serialized, due to to few constructor arguments.
  132. """
  133. if (self.file is not None and
  134. self._serialized_start is not None and
  135. self._serialized_end is not None):
  136. proto.ParseFromString(self.file.serialized_pb[
  137. self._serialized_start:self._serialized_end])
  138. else:
  139. raise Error('Descriptor does not contain serialization.')
  140. class Descriptor(_NestedDescriptorBase):
  141. """Descriptor for a protocol message type.
  142. A Descriptor instance has the following attributes:
  143. name: (str) Name of this protocol message type.
  144. full_name: (str) Fully-qualified name of this protocol message type,
  145. which will include protocol "package" name and the name of any
  146. enclosing types.
  147. containing_type: (Descriptor) Reference to the descriptor of the
  148. type containing us, or None if this is top-level.
  149. fields: (list of FieldDescriptors) Field descriptors for all
  150. fields in this type.
  151. fields_by_number: (dict int -> FieldDescriptor) Same FieldDescriptor
  152. objects as in |fields|, but indexed by "number" attribute in each
  153. FieldDescriptor.
  154. fields_by_name: (dict str -> FieldDescriptor) Same FieldDescriptor
  155. objects as in |fields|, but indexed by "name" attribute in each
  156. FieldDescriptor.
  157. nested_types: (list of Descriptors) Descriptor references
  158. for all protocol message types nested within this one.
  159. nested_types_by_name: (dict str -> Descriptor) Same Descriptor
  160. objects as in |nested_types|, but indexed by "name" attribute
  161. in each Descriptor.
  162. enum_types: (list of EnumDescriptors) EnumDescriptor references
  163. for all enums contained within this type.
  164. enum_types_by_name: (dict str ->EnumDescriptor) Same EnumDescriptor
  165. objects as in |enum_types|, but indexed by "name" attribute
  166. in each EnumDescriptor.
  167. enum_values_by_name: (dict str -> EnumValueDescriptor) Dict mapping
  168. from enum value name to EnumValueDescriptor for that value.
  169. extensions: (list of FieldDescriptor) All extensions defined directly
  170. within this message type (NOT within a nested type).
  171. extensions_by_name: (dict, string -> FieldDescriptor) Same FieldDescriptor
  172. objects as |extensions|, but indexed by "name" attribute of each
  173. FieldDescriptor.
  174. is_extendable: Does this type define any extension ranges?
  175. options: (descriptor_pb2.MessageOptions) Protocol message options or None
  176. to use default message options.
  177. file: (FileDescriptor) Reference to file descriptor.
  178. """
  179. def __init__(self, name, full_name, filename, containing_type, fields,
  180. nested_types, enum_types, extensions, options=None,
  181. is_extendable=True, extension_ranges=None, file=None,
  182. serialized_start=None, serialized_end=None):
  183. """Arguments to __init__() are as described in the description
  184. of Descriptor fields above.
  185. Note that filename is an obsolete argument, that is not used anymore.
  186. Please use file.name to access this as an attribute.
  187. """
  188. super(Descriptor, self).__init__(
  189. options, 'MessageOptions', name, full_name, file,
  190. containing_type, serialized_start=serialized_start,
  191. serialized_end=serialized_start)
  192. # We have fields in addition to fields_by_name and fields_by_number,
  193. # so that:
  194. # 1. Clients can index fields by "order in which they're listed."
  195. # 2. Clients can easily iterate over all fields with the terse
  196. # syntax: for f in descriptor.fields: ...
  197. self.fields = fields
  198. for field in self.fields:
  199. field.containing_type = self
  200. self.fields_by_number = dict((f.number, f) for f in fields)
  201. self.fields_by_name = dict((f.name, f) for f in fields)
  202. self.nested_types = nested_types
  203. self.nested_types_by_name = dict((t.name, t) for t in nested_types)
  204. self.enum_types = enum_types
  205. for enum_type in self.enum_types:
  206. enum_type.containing_type = self
  207. self.enum_types_by_name = dict((t.name, t) for t in enum_types)
  208. self.enum_values_by_name = dict(
  209. (v.name, v) for t in enum_types for v in t.values)
  210. self.extensions = extensions
  211. for extension in self.extensions:
  212. extension.extension_scope = self
  213. self.extensions_by_name = dict((f.name, f) for f in extensions)
  214. self.is_extendable = is_extendable
  215. self.extension_ranges = extension_ranges
  216. self._serialized_start = serialized_start
  217. self._serialized_end = serialized_end
  218. def EnumValueName(self, enum, value):
  219. """Returns the string name of an enum value.
  220. This is just a small helper method to simplify a common operation.
  221. Args:
  222. enum: string name of the Enum.
  223. value: int, value of the enum.
  224. Returns:
  225. string name of the enum value.
  226. Raises:
  227. KeyError if either the Enum doesn't exist or the value is not a valid
  228. value for the enum.
  229. """
  230. return self.enum_types_by_name[enum].values_by_number[value].name
  231. def CopyToProto(self, proto):
  232. """Copies this to a descriptor_pb2.DescriptorProto.
  233. Args:
  234. proto: An empty descriptor_pb2.DescriptorProto.
  235. """
  236. # This function is overriden to give a better doc comment.
  237. super(Descriptor, self).CopyToProto(proto)
  238. # TODO(robinson): We should have aggressive checking here,
  239. # for example:
  240. # * If you specify a repeated field, you should not be allowed
  241. # to specify a default value.
  242. # * [Other examples here as needed].
  243. #
  244. # TODO(robinson): for this and other *Descriptor classes, we
  245. # might also want to lock things down aggressively (e.g.,
  246. # prevent clients from setting the attributes). Having
  247. # stronger invariants here in general will reduce the number
  248. # of runtime checks we must do in reflection.py...
  249. class FieldDescriptor(DescriptorBase):
  250. """Descriptor for a single field in a .proto file.
  251. A FieldDescriptor instance has the following attributes:
  252. name: (str) Name of this field, exactly as it appears in .proto.
  253. full_name: (str) Name of this field, including containing scope. This is
  254. particularly relevant for extensions.
  255. index: (int) Dense, 0-indexed index giving the order that this
  256. field textually appears within its message in the .proto file.
  257. number: (int) Tag number declared for this field in the .proto file.
  258. type: (One of the TYPE_* constants below) Declared type.
  259. cpp_type: (One of the CPPTYPE_* constants below) C++ type used to
  260. represent this field.
  261. label: (One of the LABEL_* constants below) Tells whether this
  262. field is optional, required, or repeated.
  263. has_default_value: (bool) True if this field has a default value defined,
  264. otherwise false.
  265. default_value: (Varies) Default value of this field. Only
  266. meaningful for non-repeated scalar fields. Repeated fields
  267. should always set this to [], and non-repeated composite
  268. fields should always set this to None.
  269. containing_type: (Descriptor) Descriptor of the protocol message
  270. type that contains this field. Set by the Descriptor constructor
  271. if we're passed into one.
  272. Somewhat confusingly, for extension fields, this is the
  273. descriptor of the EXTENDED message, not the descriptor
  274. of the message containing this field. (See is_extension and
  275. extension_scope below).
  276. message_type: (Descriptor) If a composite field, a descriptor
  277. of the message type contained in this field. Otherwise, this is None.
  278. enum_type: (EnumDescriptor) If this field contains an enum, a
  279. descriptor of that enum. Otherwise, this is None.
  280. is_extension: True iff this describes an extension field.
  281. extension_scope: (Descriptor) Only meaningful if is_extension is True.
  282. Gives the message that immediately contains this extension field.
  283. Will be None iff we're a top-level (file-level) extension field.
  284. options: (descriptor_pb2.FieldOptions) Protocol message field options or
  285. None to use default field options.
  286. """
  287. # Must be consistent with C++ FieldDescriptor::Type enum in
  288. # descriptor.h.
  289. #
  290. # TODO(robinson): Find a way to eliminate this repetition.
  291. TYPE_DOUBLE = 1
  292. TYPE_FLOAT = 2
  293. TYPE_INT64 = 3
  294. TYPE_UINT64 = 4
  295. TYPE_INT32 = 5
  296. TYPE_FIXED64 = 6
  297. TYPE_FIXED32 = 7
  298. TYPE_BOOL = 8
  299. TYPE_STRING = 9
  300. TYPE_GROUP = 10
  301. TYPE_MESSAGE = 11
  302. TYPE_BYTES = 12
  303. TYPE_UINT32 = 13
  304. TYPE_ENUM = 14
  305. TYPE_SFIXED32 = 15
  306. TYPE_SFIXED64 = 16
  307. TYPE_SINT32 = 17
  308. TYPE_SINT64 = 18
  309. MAX_TYPE = 18
  310. # Must be consistent with C++ FieldDescriptor::CppType enum in
  311. # descriptor.h.
  312. #
  313. # TODO(robinson): Find a way to eliminate this repetition.
  314. CPPTYPE_INT32 = 1
  315. CPPTYPE_INT64 = 2
  316. CPPTYPE_UINT32 = 3
  317. CPPTYPE_UINT64 = 4
  318. CPPTYPE_DOUBLE = 5
  319. CPPTYPE_FLOAT = 6
  320. CPPTYPE_BOOL = 7
  321. CPPTYPE_ENUM = 8
  322. CPPTYPE_STRING = 9
  323. CPPTYPE_MESSAGE = 10
  324. MAX_CPPTYPE = 10
  325. _PYTHON_TO_CPP_PROTO_TYPE_MAP = {
  326. TYPE_DOUBLE: CPPTYPE_DOUBLE,
  327. TYPE_FLOAT: CPPTYPE_FLOAT,
  328. TYPE_ENUM: CPPTYPE_ENUM,
  329. TYPE_INT64: CPPTYPE_INT64,
  330. TYPE_SINT64: CPPTYPE_INT64,
  331. TYPE_SFIXED64: CPPTYPE_INT64,
  332. TYPE_UINT64: CPPTYPE_UINT64,
  333. TYPE_FIXED64: CPPTYPE_UINT64,
  334. TYPE_INT32: CPPTYPE_INT32,
  335. TYPE_SFIXED32: CPPTYPE_INT32,
  336. TYPE_SINT32: CPPTYPE_INT32,
  337. TYPE_UINT32: CPPTYPE_UINT32,
  338. TYPE_FIXED32: CPPTYPE_UINT32,
  339. TYPE_BYTES: CPPTYPE_STRING,
  340. TYPE_STRING: CPPTYPE_STRING,
  341. TYPE_BOOL: CPPTYPE_BOOL,
  342. TYPE_MESSAGE: CPPTYPE_MESSAGE,
  343. TYPE_GROUP: CPPTYPE_MESSAGE
  344. }
  345. # Must be consistent with C++ FieldDescriptor::Label enum in
  346. # descriptor.h.
  347. #
  348. # TODO(robinson): Find a way to eliminate this repetition.
  349. LABEL_OPTIONAL = 1
  350. LABEL_REQUIRED = 2
  351. LABEL_REPEATED = 3
  352. MAX_LABEL = 3
  353. def __init__(self, name, full_name, index, number, type, cpp_type, label,
  354. default_value, message_type, enum_type, containing_type,
  355. is_extension, extension_scope, options=None,
  356. has_default_value=True):
  357. """The arguments are as described in the description of FieldDescriptor
  358. attributes above.
  359. Note that containing_type may be None, and may be set later if necessary
  360. (to deal with circular references between message types, for example).
  361. Likewise for extension_scope.
  362. """
  363. super(FieldDescriptor, self).__init__(options, 'FieldOptions')
  364. self.name = name
  365. self.full_name = full_name
  366. self.index = index
  367. self.number = number
  368. self.type = type
  369. self.cpp_type = cpp_type
  370. self.label = label
  371. self.has_default_value = has_default_value
  372. self.default_value = default_value
  373. self.containing_type = containing_type
  374. self.message_type = message_type
  375. self.enum_type = enum_type
  376. self.is_extension = is_extension
  377. self.extension_scope = extension_scope
  378. if api_implementation.Type() == 'cpp':
  379. if is_extension:
  380. if api_implementation.Version() == 2:
  381. self._cdescriptor = _message.GetExtensionDescriptor(full_name)
  382. else:
  383. self._cdescriptor = cpp_message.GetExtensionDescriptor(full_name)
  384. else:
  385. if api_implementation.Version() == 2:
  386. self._cdescriptor = _message.GetFieldDescriptor(full_name)
  387. else:
  388. self._cdescriptor = cpp_message.GetFieldDescriptor(full_name)
  389. else:
  390. self._cdescriptor = None
  391. @staticmethod
  392. def ProtoTypeToCppProtoType(proto_type):
  393. """Converts from a Python proto type to a C++ Proto Type.
  394. The Python ProtocolBuffer classes specify both the 'Python' datatype and the
  395. 'C++' datatype - and they're not the same. This helper method should
  396. translate from one to another.
  397. Args:
  398. proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
  399. Returns:
  400. descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
  401. Raises:
  402. TypeTransformationError: when the Python proto type isn't known.
  403. """
  404. try:
  405. return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
  406. except KeyError:
  407. raise TypeTransformationError('Unknown proto_type: %s' % proto_type)
  408. class EnumDescriptor(_NestedDescriptorBase):
  409. """Descriptor for an enum defined in a .proto file.
  410. An EnumDescriptor instance has the following attributes:
  411. name: (str) Name of the enum type.
  412. full_name: (str) Full name of the type, including package name
  413. and any enclosing type(s).
  414. values: (list of EnumValueDescriptors) List of the values
  415. in this enum.
  416. values_by_name: (dict str -> EnumValueDescriptor) Same as |values|,
  417. but indexed by the "name" field of each EnumValueDescriptor.
  418. values_by_number: (dict int -> EnumValueDescriptor) Same as |values|,
  419. but indexed by the "number" field of each EnumValueDescriptor.
  420. containing_type: (Descriptor) Descriptor of the immediate containing
  421. type of this enum, or None if this is an enum defined at the
  422. top level in a .proto file. Set by Descriptor's constructor
  423. if we're passed into one.
  424. file: (FileDescriptor) Reference to file descriptor.
  425. options: (descriptor_pb2.EnumOptions) Enum options message or
  426. None to use default enum options.
  427. """
  428. def __init__(self, name, full_name, filename, values,
  429. containing_type=None, options=None, file=None,
  430. serialized_start=None, serialized_end=None):
  431. """Arguments are as described in the attribute description above.
  432. Note that filename is an obsolete argument, that is not used anymore.
  433. Please use file.name to access this as an attribute.
  434. """
  435. super(EnumDescriptor, self).__init__(
  436. options, 'EnumOptions', name, full_name, file,
  437. containing_type, serialized_start=serialized_start,
  438. serialized_end=serialized_start)
  439. self.values = values
  440. for value in self.values:
  441. value.type = self
  442. self.values_by_name = dict((v.name, v) for v in values)
  443. self.values_by_number = dict((v.number, v) for v in values)
  444. self._serialized_start = serialized_start
  445. self._serialized_end = serialized_end
  446. def CopyToProto(self, proto):
  447. """Copies this to a descriptor_pb2.EnumDescriptorProto.
  448. Args:
  449. proto: An empty descriptor_pb2.EnumDescriptorProto.
  450. """
  451. # This function is overriden to give a better doc comment.
  452. super(EnumDescriptor, self).CopyToProto(proto)
  453. class EnumValueDescriptor(DescriptorBase):
  454. """Descriptor for a single value within an enum.
  455. name: (str) Name of this value.
  456. index: (int) Dense, 0-indexed index giving the order that this
  457. value appears textually within its enum in the .proto file.
  458. number: (int) Actual number assigned to this enum value.
  459. type: (EnumDescriptor) EnumDescriptor to which this value
  460. belongs. Set by EnumDescriptor's constructor if we're
  461. passed into one.
  462. options: (descriptor_pb2.EnumValueOptions) Enum value options message or
  463. None to use default enum value options options.
  464. """
  465. def __init__(self, name, index, number, type=None, options=None):
  466. """Arguments are as described in the attribute description above."""
  467. super(EnumValueDescriptor, self).__init__(options, 'EnumValueOptions')
  468. self.name = name
  469. self.index = index
  470. self.number = number
  471. self.type = type
  472. class ServiceDescriptor(_NestedDescriptorBase):
  473. """Descriptor for a service.
  474. name: (str) Name of the service.
  475. full_name: (str) Full name of the service, including package name.
  476. index: (int) 0-indexed index giving the order that this services
  477. definition appears withing the .proto file.
  478. methods: (list of MethodDescriptor) List of methods provided by this
  479. service.
  480. options: (descriptor_pb2.ServiceOptions) Service options message or
  481. None to use default service options.
  482. file: (FileDescriptor) Reference to file info.
  483. """
  484. def __init__(self, name, full_name, index, methods, options=None, file=None,
  485. serialized_start=None, serialized_end=None):
  486. super(ServiceDescriptor, self).__init__(
  487. options, 'ServiceOptions', name, full_name, file,
  488. None, serialized_start=serialized_start,
  489. serialized_end=serialized_end)
  490. self.index = index
  491. self.methods = methods
  492. # Set the containing service for each method in this service.
  493. for method in self.methods:
  494. method.containing_service = self
  495. def FindMethodByName(self, name):
  496. """Searches for the specified method, and returns its descriptor."""
  497. for method in self.methods:
  498. if name == method.name:
  499. return method
  500. return None
  501. def CopyToProto(self, proto):
  502. """Copies this to a descriptor_pb2.ServiceDescriptorProto.
  503. Args:
  504. proto: An empty descriptor_pb2.ServiceDescriptorProto.
  505. """
  506. # This function is overriden to give a better doc comment.
  507. super(ServiceDescriptor, self).CopyToProto(proto)
  508. class MethodDescriptor(DescriptorBase):
  509. """Descriptor for a method in a service.
  510. name: (str) Name of the method within the service.
  511. full_name: (str) Full name of method.
  512. index: (int) 0-indexed index of the method inside the service.
  513. containing_service: (ServiceDescriptor) The service that contains this
  514. method.
  515. input_type: The descriptor of the message that this method accepts.
  516. output_type: The descriptor of the message that this method returns.
  517. options: (descriptor_pb2.MethodOptions) Method options message or
  518. None to use default method options.
  519. """
  520. def __init__(self, name, full_name, index, containing_service,
  521. input_type, output_type, options=None):
  522. """The arguments are as described in the description of MethodDescriptor
  523. attributes above.
  524. Note that containing_service may be None, and may be set later if necessary.
  525. """
  526. super(MethodDescriptor, self).__init__(options, 'MethodOptions')
  527. self.name = name
  528. self.full_name = full_name
  529. self.index = index
  530. self.containing_service = containing_service
  531. self.input_type = input_type
  532. self.output_type = output_type
  533. class FileDescriptor(DescriptorBase):
  534. """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto.
  535. name: name of file, relative to root of source tree.
  536. package: name of the package
  537. serialized_pb: (str) Byte string of serialized
  538. descriptor_pb2.FileDescriptorProto.
  539. """
  540. def __init__(self, name, package, options=None, serialized_pb=None):
  541. """Constructor."""
  542. super(FileDescriptor, self).__init__(options, 'FileOptions')
  543. self.message_types_by_name = {}
  544. self.name = name
  545. self.package = package
  546. self.serialized_pb = serialized_pb
  547. if (api_implementation.Type() == 'cpp' and
  548. self.serialized_pb is not None):
  549. if api_implementation.Version() == 2:
  550. _message.BuildFile(self.serialized_pb)
  551. else:
  552. cpp_message.BuildFile(self.serialized_pb)
  553. def CopyToProto(self, proto):
  554. """Copies this to a descriptor_pb2.FileDescriptorProto.
  555. Args:
  556. proto: An empty descriptor_pb2.FileDescriptorProto.
  557. """
  558. proto.ParseFromString(self.serialized_pb)
  559. def _ParseOptions(message, string):
  560. """Parses serialized options.
  561. This helper function is used to parse serialized options in generated
  562. proto2 files. It must not be used outside proto2.
  563. """
  564. message.ParseFromString(string)
  565. return message
  566. def MakeDescriptor(desc_proto, package=''):
  567. """Make a protobuf Descriptor given a DescriptorProto protobuf.
  568. Args:
  569. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  570. package: Optional package name for the new message Descriptor (string).
  571. Returns:
  572. A Descriptor for protobuf messages.
  573. """
  574. full_message_name = [desc_proto.name]
  575. if package: full_message_name.insert(0, package)
  576. fields = []
  577. for field_proto in desc_proto.field:
  578. full_name = '.'.join(full_message_name + [field_proto.name])
  579. field = FieldDescriptor(
  580. field_proto.name, full_name, field_proto.number - 1,
  581. field_proto.number, field_proto.type,
  582. FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
  583. field_proto.label, None, None, None, None, False, None,
  584. has_default_value=False)
  585. fields.append(field)
  586. desc_name = '.'.join(full_message_name)
  587. return Descriptor(desc_proto.name, desc_name, None, None, fields,
  588. [], [], [])