图片解析应用
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.

1293 lines
46 KiB

  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. """Provides DescriptorPool to use as a container for proto2 descriptors.
  31. The DescriptorPool is used in conjection with a DescriptorDatabase to maintain
  32. a collection of protocol buffer descriptors for use when dynamically creating
  33. message types at runtime.
  34. For most applications protocol buffers should be used via modules generated by
  35. the protocol buffer compiler tool. This should only be used when the type of
  36. protocol buffers used in an application or library cannot be predetermined.
  37. Below is a straightforward example on how to use this class::
  38. pool = DescriptorPool()
  39. file_descriptor_protos = [ ... ]
  40. for file_descriptor_proto in file_descriptor_protos:
  41. pool.Add(file_descriptor_proto)
  42. my_message_descriptor = pool.FindMessageTypeByName('some.package.MessageType')
  43. The message descriptor can be used in conjunction with the message_factory
  44. module in order to create a protocol buffer class that can be encoded and
  45. decoded.
  46. If you want to get a Python class for the specified proto, use the
  47. helper functions inside google.protobuf.message_factory
  48. directly instead of this class.
  49. """
  50. __author__ = 'matthewtoia@google.com (Matt Toia)'
  51. import collections
  52. import warnings
  53. from google.protobuf import descriptor
  54. from google.protobuf import descriptor_database
  55. from google.protobuf import text_encoding
  56. from google.protobuf.internal import python_message
  57. _USE_C_DESCRIPTORS = descriptor._USE_C_DESCRIPTORS # pylint: disable=protected-access
  58. def _Deprecated(func):
  59. """Mark functions as deprecated."""
  60. def NewFunc(*args, **kwargs):
  61. warnings.warn(
  62. 'Call to deprecated function %s(). Note: Do add unlinked descriptors '
  63. 'to descriptor_pool is wrong. Please use Add() or AddSerializedFile() '
  64. 'instead. This function will be removed soon.' % func.__name__,
  65. category=DeprecationWarning)
  66. return func(*args, **kwargs)
  67. NewFunc.__name__ = func.__name__
  68. NewFunc.__doc__ = func.__doc__
  69. NewFunc.__dict__.update(func.__dict__)
  70. return NewFunc
  71. def _NormalizeFullyQualifiedName(name):
  72. """Remove leading period from fully-qualified type name.
  73. Due to b/13860351 in descriptor_database.py, types in the root namespace are
  74. generated with a leading period. This function removes that prefix.
  75. Args:
  76. name (str): The fully-qualified symbol name.
  77. Returns:
  78. str: The normalized fully-qualified symbol name.
  79. """
  80. return name.lstrip('.')
  81. def _OptionsOrNone(descriptor_proto):
  82. """Returns the value of the field `options`, or None if it is not set."""
  83. if descriptor_proto.HasField('options'):
  84. return descriptor_proto.options
  85. else:
  86. return None
  87. def _IsMessageSetExtension(field):
  88. return (field.is_extension and
  89. field.containing_type.has_options and
  90. field.containing_type.GetOptions().message_set_wire_format and
  91. field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  92. field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL)
  93. class DescriptorPool(object):
  94. """A collection of protobufs dynamically constructed by descriptor protos."""
  95. if _USE_C_DESCRIPTORS:
  96. def __new__(cls, descriptor_db=None):
  97. # pylint: disable=protected-access
  98. return descriptor._message.DescriptorPool(descriptor_db)
  99. def __init__(
  100. self, descriptor_db=None, use_deprecated_legacy_json_field_conflicts=False
  101. ):
  102. """Initializes a Pool of proto buffs.
  103. The descriptor_db argument to the constructor is provided to allow
  104. specialized file descriptor proto lookup code to be triggered on demand. An
  105. example would be an implementation which will read and compile a file
  106. specified in a call to FindFileByName() and not require the call to Add()
  107. at all. Results from this database will be cached internally here as well.
  108. Args:
  109. descriptor_db: A secondary source of file descriptors.
  110. use_deprecated_legacy_json_field_conflicts: Unused, for compatibility with
  111. C++.
  112. """
  113. self._internal_db = descriptor_database.DescriptorDatabase()
  114. self._descriptor_db = descriptor_db
  115. self._descriptors = {}
  116. self._enum_descriptors = {}
  117. self._service_descriptors = {}
  118. self._file_descriptors = {}
  119. self._toplevel_extensions = {}
  120. self._top_enum_values = {}
  121. # We store extensions in two two-level mappings: The first key is the
  122. # descriptor of the message being extended, the second key is the extension
  123. # full name or its tag number.
  124. self._extensions_by_name = collections.defaultdict(dict)
  125. self._extensions_by_number = collections.defaultdict(dict)
  126. def _CheckConflictRegister(self, desc, desc_name, file_name):
  127. """Check if the descriptor name conflicts with another of the same name.
  128. Args:
  129. desc: Descriptor of a message, enum, service, extension or enum value.
  130. desc_name (str): the full name of desc.
  131. file_name (str): The file name of descriptor.
  132. """
  133. for register, descriptor_type in [
  134. (self._descriptors, descriptor.Descriptor),
  135. (self._enum_descriptors, descriptor.EnumDescriptor),
  136. (self._service_descriptors, descriptor.ServiceDescriptor),
  137. (self._toplevel_extensions, descriptor.FieldDescriptor),
  138. (self._top_enum_values, descriptor.EnumValueDescriptor)]:
  139. if desc_name in register:
  140. old_desc = register[desc_name]
  141. if isinstance(old_desc, descriptor.EnumValueDescriptor):
  142. old_file = old_desc.type.file.name
  143. else:
  144. old_file = old_desc.file.name
  145. if not isinstance(desc, descriptor_type) or (
  146. old_file != file_name):
  147. error_msg = ('Conflict register for file "' + file_name +
  148. '": ' + desc_name +
  149. ' is already defined in file "' +
  150. old_file + '". Please fix the conflict by adding '
  151. 'package name on the proto file, or use different '
  152. 'name for the duplication.')
  153. if isinstance(desc, descriptor.EnumValueDescriptor):
  154. error_msg += ('\nNote: enum values appear as '
  155. 'siblings of the enum type instead of '
  156. 'children of it.')
  157. raise TypeError(error_msg)
  158. return
  159. def Add(self, file_desc_proto):
  160. """Adds the FileDescriptorProto and its types to this pool.
  161. Args:
  162. file_desc_proto (FileDescriptorProto): The file descriptor to add.
  163. """
  164. self._internal_db.Add(file_desc_proto)
  165. def AddSerializedFile(self, serialized_file_desc_proto):
  166. """Adds the FileDescriptorProto and its types to this pool.
  167. Args:
  168. serialized_file_desc_proto (bytes): A bytes string, serialization of the
  169. :class:`FileDescriptorProto` to add.
  170. Returns:
  171. FileDescriptor: Descriptor for the added file.
  172. """
  173. # pylint: disable=g-import-not-at-top
  174. from google.protobuf import descriptor_pb2
  175. file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(
  176. serialized_file_desc_proto)
  177. file_desc = self._ConvertFileProtoToFileDescriptor(file_desc_proto)
  178. file_desc.serialized_pb = serialized_file_desc_proto
  179. return file_desc
  180. # Add Descriptor to descriptor pool is deprecated. Please use Add()
  181. # or AddSerializedFile() to add a FileDescriptorProto instead.
  182. @_Deprecated
  183. def AddDescriptor(self, desc):
  184. self._AddDescriptor(desc)
  185. # Never call this method. It is for internal usage only.
  186. def _AddDescriptor(self, desc):
  187. """Adds a Descriptor to the pool, non-recursively.
  188. If the Descriptor contains nested messages or enums, the caller must
  189. explicitly register them. This method also registers the FileDescriptor
  190. associated with the message.
  191. Args:
  192. desc: A Descriptor.
  193. """
  194. if not isinstance(desc, descriptor.Descriptor):
  195. raise TypeError('Expected instance of descriptor.Descriptor.')
  196. self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
  197. self._descriptors[desc.full_name] = desc
  198. self._AddFileDescriptor(desc.file)
  199. # Never call this method. It is for internal usage only.
  200. def _AddEnumDescriptor(self, enum_desc):
  201. """Adds an EnumDescriptor to the pool.
  202. This method also registers the FileDescriptor associated with the enum.
  203. Args:
  204. enum_desc: An EnumDescriptor.
  205. """
  206. if not isinstance(enum_desc, descriptor.EnumDescriptor):
  207. raise TypeError('Expected instance of descriptor.EnumDescriptor.')
  208. file_name = enum_desc.file.name
  209. self._CheckConflictRegister(enum_desc, enum_desc.full_name, file_name)
  210. self._enum_descriptors[enum_desc.full_name] = enum_desc
  211. # Top enum values need to be indexed.
  212. # Count the number of dots to see whether the enum is toplevel or nested
  213. # in a message. We cannot use enum_desc.containing_type at this stage.
  214. if enum_desc.file.package:
  215. top_level = (enum_desc.full_name.count('.')
  216. - enum_desc.file.package.count('.') == 1)
  217. else:
  218. top_level = enum_desc.full_name.count('.') == 0
  219. if top_level:
  220. file_name = enum_desc.file.name
  221. package = enum_desc.file.package
  222. for enum_value in enum_desc.values:
  223. full_name = _NormalizeFullyQualifiedName(
  224. '.'.join((package, enum_value.name)))
  225. self._CheckConflictRegister(enum_value, full_name, file_name)
  226. self._top_enum_values[full_name] = enum_value
  227. self._AddFileDescriptor(enum_desc.file)
  228. # Add ServiceDescriptor to descriptor pool is deprecated. Please use Add()
  229. # or AddSerializedFile() to add a FileDescriptorProto instead.
  230. @_Deprecated
  231. def AddServiceDescriptor(self, service_desc):
  232. self._AddServiceDescriptor(service_desc)
  233. # Never call this method. It is for internal usage only.
  234. def _AddServiceDescriptor(self, service_desc):
  235. """Adds a ServiceDescriptor to the pool.
  236. Args:
  237. service_desc: A ServiceDescriptor.
  238. """
  239. if not isinstance(service_desc, descriptor.ServiceDescriptor):
  240. raise TypeError('Expected instance of descriptor.ServiceDescriptor.')
  241. self._CheckConflictRegister(service_desc, service_desc.full_name,
  242. service_desc.file.name)
  243. self._service_descriptors[service_desc.full_name] = service_desc
  244. # Add ExtensionDescriptor to descriptor pool is deprecated. Please use Add()
  245. # or AddSerializedFile() to add a FileDescriptorProto instead.
  246. @_Deprecated
  247. def AddExtensionDescriptor(self, extension):
  248. self._AddExtensionDescriptor(extension)
  249. # Never call this method. It is for internal usage only.
  250. def _AddExtensionDescriptor(self, extension):
  251. """Adds a FieldDescriptor describing an extension to the pool.
  252. Args:
  253. extension: A FieldDescriptor.
  254. Raises:
  255. AssertionError: when another extension with the same number extends the
  256. same message.
  257. TypeError: when the specified extension is not a
  258. descriptor.FieldDescriptor.
  259. """
  260. if not (isinstance(extension, descriptor.FieldDescriptor) and
  261. extension.is_extension):
  262. raise TypeError('Expected an extension descriptor.')
  263. if extension.extension_scope is None:
  264. self._CheckConflictRegister(
  265. extension, extension.full_name, extension.file.name)
  266. self._toplevel_extensions[extension.full_name] = extension
  267. try:
  268. existing_desc = self._extensions_by_number[
  269. extension.containing_type][extension.number]
  270. except KeyError:
  271. pass
  272. else:
  273. if extension is not existing_desc:
  274. raise AssertionError(
  275. 'Extensions "%s" and "%s" both try to extend message type "%s" '
  276. 'with field number %d.' %
  277. (extension.full_name, existing_desc.full_name,
  278. extension.containing_type.full_name, extension.number))
  279. self._extensions_by_number[extension.containing_type][
  280. extension.number] = extension
  281. self._extensions_by_name[extension.containing_type][
  282. extension.full_name] = extension
  283. # Also register MessageSet extensions with the type name.
  284. if _IsMessageSetExtension(extension):
  285. self._extensions_by_name[extension.containing_type][
  286. extension.message_type.full_name] = extension
  287. if hasattr(extension.containing_type, '_concrete_class'):
  288. python_message._AttachFieldHelpers(
  289. extension.containing_type._concrete_class, extension)
  290. @_Deprecated
  291. def AddFileDescriptor(self, file_desc):
  292. self._InternalAddFileDescriptor(file_desc)
  293. # Never call this method. It is for internal usage only.
  294. def _InternalAddFileDescriptor(self, file_desc):
  295. """Adds a FileDescriptor to the pool, non-recursively.
  296. If the FileDescriptor contains messages or enums, the caller must explicitly
  297. register them.
  298. Args:
  299. file_desc: A FileDescriptor.
  300. """
  301. self._AddFileDescriptor(file_desc)
  302. def _AddFileDescriptor(self, file_desc):
  303. """Adds a FileDescriptor to the pool, non-recursively.
  304. If the FileDescriptor contains messages or enums, the caller must explicitly
  305. register them.
  306. Args:
  307. file_desc: A FileDescriptor.
  308. """
  309. if not isinstance(file_desc, descriptor.FileDescriptor):
  310. raise TypeError('Expected instance of descriptor.FileDescriptor.')
  311. self._file_descriptors[file_desc.name] = file_desc
  312. def FindFileByName(self, file_name):
  313. """Gets a FileDescriptor by file name.
  314. Args:
  315. file_name (str): The path to the file to get a descriptor for.
  316. Returns:
  317. FileDescriptor: The descriptor for the named file.
  318. Raises:
  319. KeyError: if the file cannot be found in the pool.
  320. """
  321. try:
  322. return self._file_descriptors[file_name]
  323. except KeyError:
  324. pass
  325. try:
  326. file_proto = self._internal_db.FindFileByName(file_name)
  327. except KeyError as error:
  328. if self._descriptor_db:
  329. file_proto = self._descriptor_db.FindFileByName(file_name)
  330. else:
  331. raise error
  332. if not file_proto:
  333. raise KeyError('Cannot find a file named %s' % file_name)
  334. return self._ConvertFileProtoToFileDescriptor(file_proto)
  335. def FindFileContainingSymbol(self, symbol):
  336. """Gets the FileDescriptor for the file containing the specified symbol.
  337. Args:
  338. symbol (str): The name of the symbol to search for.
  339. Returns:
  340. FileDescriptor: Descriptor for the file that contains the specified
  341. symbol.
  342. Raises:
  343. KeyError: if the file cannot be found in the pool.
  344. """
  345. symbol = _NormalizeFullyQualifiedName(symbol)
  346. try:
  347. return self._InternalFindFileContainingSymbol(symbol)
  348. except KeyError:
  349. pass
  350. try:
  351. # Try fallback database. Build and find again if possible.
  352. self._FindFileContainingSymbolInDb(symbol)
  353. return self._InternalFindFileContainingSymbol(symbol)
  354. except KeyError:
  355. raise KeyError('Cannot find a file containing %s' % symbol)
  356. def _InternalFindFileContainingSymbol(self, symbol):
  357. """Gets the already built FileDescriptor containing the specified symbol.
  358. Args:
  359. symbol (str): The name of the symbol to search for.
  360. Returns:
  361. FileDescriptor: Descriptor for the file that contains the specified
  362. symbol.
  363. Raises:
  364. KeyError: if the file cannot be found in the pool.
  365. """
  366. try:
  367. return self._descriptors[symbol].file
  368. except KeyError:
  369. pass
  370. try:
  371. return self._enum_descriptors[symbol].file
  372. except KeyError:
  373. pass
  374. try:
  375. return self._service_descriptors[symbol].file
  376. except KeyError:
  377. pass
  378. try:
  379. return self._top_enum_values[symbol].type.file
  380. except KeyError:
  381. pass
  382. try:
  383. return self._toplevel_extensions[symbol].file
  384. except KeyError:
  385. pass
  386. # Try fields, enum values and nested extensions inside a message.
  387. top_name, _, sub_name = symbol.rpartition('.')
  388. try:
  389. message = self.FindMessageTypeByName(top_name)
  390. assert (sub_name in message.extensions_by_name or
  391. sub_name in message.fields_by_name or
  392. sub_name in message.enum_values_by_name)
  393. return message.file
  394. except (KeyError, AssertionError):
  395. raise KeyError('Cannot find a file containing %s' % symbol)
  396. def FindMessageTypeByName(self, full_name):
  397. """Loads the named descriptor from the pool.
  398. Args:
  399. full_name (str): The full name of the descriptor to load.
  400. Returns:
  401. Descriptor: The descriptor for the named type.
  402. Raises:
  403. KeyError: if the message cannot be found in the pool.
  404. """
  405. full_name = _NormalizeFullyQualifiedName(full_name)
  406. if full_name not in self._descriptors:
  407. self._FindFileContainingSymbolInDb(full_name)
  408. return self._descriptors[full_name]
  409. def FindEnumTypeByName(self, full_name):
  410. """Loads the named enum descriptor from the pool.
  411. Args:
  412. full_name (str): The full name of the enum descriptor to load.
  413. Returns:
  414. EnumDescriptor: The enum descriptor for the named type.
  415. Raises:
  416. KeyError: if the enum cannot be found in the pool.
  417. """
  418. full_name = _NormalizeFullyQualifiedName(full_name)
  419. if full_name not in self._enum_descriptors:
  420. self._FindFileContainingSymbolInDb(full_name)
  421. return self._enum_descriptors[full_name]
  422. def FindFieldByName(self, full_name):
  423. """Loads the named field descriptor from the pool.
  424. Args:
  425. full_name (str): The full name of the field descriptor to load.
  426. Returns:
  427. FieldDescriptor: The field descriptor for the named field.
  428. Raises:
  429. KeyError: if the field cannot be found in the pool.
  430. """
  431. full_name = _NormalizeFullyQualifiedName(full_name)
  432. message_name, _, field_name = full_name.rpartition('.')
  433. message_descriptor = self.FindMessageTypeByName(message_name)
  434. return message_descriptor.fields_by_name[field_name]
  435. def FindOneofByName(self, full_name):
  436. """Loads the named oneof descriptor from the pool.
  437. Args:
  438. full_name (str): The full name of the oneof descriptor to load.
  439. Returns:
  440. OneofDescriptor: The oneof descriptor for the named oneof.
  441. Raises:
  442. KeyError: if the oneof cannot be found in the pool.
  443. """
  444. full_name = _NormalizeFullyQualifiedName(full_name)
  445. message_name, _, oneof_name = full_name.rpartition('.')
  446. message_descriptor = self.FindMessageTypeByName(message_name)
  447. return message_descriptor.oneofs_by_name[oneof_name]
  448. def FindExtensionByName(self, full_name):
  449. """Loads the named extension descriptor from the pool.
  450. Args:
  451. full_name (str): The full name of the extension descriptor to load.
  452. Returns:
  453. FieldDescriptor: The field descriptor for the named extension.
  454. Raises:
  455. KeyError: if the extension cannot be found in the pool.
  456. """
  457. full_name = _NormalizeFullyQualifiedName(full_name)
  458. try:
  459. # The proto compiler does not give any link between the FileDescriptor
  460. # and top-level extensions unless the FileDescriptorProto is added to
  461. # the DescriptorDatabase, but this can impact memory usage.
  462. # So we registered these extensions by name explicitly.
  463. return self._toplevel_extensions[full_name]
  464. except KeyError:
  465. pass
  466. message_name, _, extension_name = full_name.rpartition('.')
  467. try:
  468. # Most extensions are nested inside a message.
  469. scope = self.FindMessageTypeByName(message_name)
  470. except KeyError:
  471. # Some extensions are defined at file scope.
  472. scope = self._FindFileContainingSymbolInDb(full_name)
  473. return scope.extensions_by_name[extension_name]
  474. def FindExtensionByNumber(self, message_descriptor, number):
  475. """Gets the extension of the specified message with the specified number.
  476. Extensions have to be registered to this pool by calling :func:`Add` or
  477. :func:`AddExtensionDescriptor`.
  478. Args:
  479. message_descriptor (Descriptor): descriptor of the extended message.
  480. number (int): Number of the extension field.
  481. Returns:
  482. FieldDescriptor: The descriptor for the extension.
  483. Raises:
  484. KeyError: when no extension with the given number is known for the
  485. specified message.
  486. """
  487. try:
  488. return self._extensions_by_number[message_descriptor][number]
  489. except KeyError:
  490. self._TryLoadExtensionFromDB(message_descriptor, number)
  491. return self._extensions_by_number[message_descriptor][number]
  492. def FindAllExtensions(self, message_descriptor):
  493. """Gets all the known extensions of a given message.
  494. Extensions have to be registered to this pool by build related
  495. :func:`Add` or :func:`AddExtensionDescriptor`.
  496. Args:
  497. message_descriptor (Descriptor): Descriptor of the extended message.
  498. Returns:
  499. list[FieldDescriptor]: Field descriptors describing the extensions.
  500. """
  501. # Fallback to descriptor db if FindAllExtensionNumbers is provided.
  502. if self._descriptor_db and hasattr(
  503. self._descriptor_db, 'FindAllExtensionNumbers'):
  504. full_name = message_descriptor.full_name
  505. all_numbers = self._descriptor_db.FindAllExtensionNumbers(full_name)
  506. for number in all_numbers:
  507. if number in self._extensions_by_number[message_descriptor]:
  508. continue
  509. self._TryLoadExtensionFromDB(message_descriptor, number)
  510. return list(self._extensions_by_number[message_descriptor].values())
  511. def _TryLoadExtensionFromDB(self, message_descriptor, number):
  512. """Try to Load extensions from descriptor db.
  513. Args:
  514. message_descriptor: descriptor of the extended message.
  515. number: the extension number that needs to be loaded.
  516. """
  517. if not self._descriptor_db:
  518. return
  519. # Only supported when FindFileContainingExtension is provided.
  520. if not hasattr(
  521. self._descriptor_db, 'FindFileContainingExtension'):
  522. return
  523. full_name = message_descriptor.full_name
  524. file_proto = self._descriptor_db.FindFileContainingExtension(
  525. full_name, number)
  526. if file_proto is None:
  527. return
  528. try:
  529. self._ConvertFileProtoToFileDescriptor(file_proto)
  530. except:
  531. warn_msg = ('Unable to load proto file %s for extension number %d.' %
  532. (file_proto.name, number))
  533. warnings.warn(warn_msg, RuntimeWarning)
  534. def FindServiceByName(self, full_name):
  535. """Loads the named service descriptor from the pool.
  536. Args:
  537. full_name (str): The full name of the service descriptor to load.
  538. Returns:
  539. ServiceDescriptor: The service descriptor for the named service.
  540. Raises:
  541. KeyError: if the service cannot be found in the pool.
  542. """
  543. full_name = _NormalizeFullyQualifiedName(full_name)
  544. if full_name not in self._service_descriptors:
  545. self._FindFileContainingSymbolInDb(full_name)
  546. return self._service_descriptors[full_name]
  547. def FindMethodByName(self, full_name):
  548. """Loads the named service method descriptor from the pool.
  549. Args:
  550. full_name (str): The full name of the method descriptor to load.
  551. Returns:
  552. MethodDescriptor: The method descriptor for the service method.
  553. Raises:
  554. KeyError: if the method cannot be found in the pool.
  555. """
  556. full_name = _NormalizeFullyQualifiedName(full_name)
  557. service_name, _, method_name = full_name.rpartition('.')
  558. service_descriptor = self.FindServiceByName(service_name)
  559. return service_descriptor.methods_by_name[method_name]
  560. def _FindFileContainingSymbolInDb(self, symbol):
  561. """Finds the file in descriptor DB containing the specified symbol.
  562. Args:
  563. symbol (str): The name of the symbol to search for.
  564. Returns:
  565. FileDescriptor: The file that contains the specified symbol.
  566. Raises:
  567. KeyError: if the file cannot be found in the descriptor database.
  568. """
  569. try:
  570. file_proto = self._internal_db.FindFileContainingSymbol(symbol)
  571. except KeyError as error:
  572. if self._descriptor_db:
  573. file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)
  574. else:
  575. raise error
  576. if not file_proto:
  577. raise KeyError('Cannot find a file containing %s' % symbol)
  578. return self._ConvertFileProtoToFileDescriptor(file_proto)
  579. def _ConvertFileProtoToFileDescriptor(self, file_proto):
  580. """Creates a FileDescriptor from a proto or returns a cached copy.
  581. This method also has the side effect of loading all the symbols found in
  582. the file into the appropriate dictionaries in the pool.
  583. Args:
  584. file_proto: The proto to convert.
  585. Returns:
  586. A FileDescriptor matching the passed in proto.
  587. """
  588. if file_proto.name not in self._file_descriptors:
  589. built_deps = list(self._GetDeps(file_proto.dependency))
  590. direct_deps = [self.FindFileByName(n) for n in file_proto.dependency]
  591. public_deps = [direct_deps[i] for i in file_proto.public_dependency]
  592. file_descriptor = descriptor.FileDescriptor(
  593. pool=self,
  594. name=file_proto.name,
  595. package=file_proto.package,
  596. syntax=file_proto.syntax,
  597. options=_OptionsOrNone(file_proto),
  598. serialized_pb=file_proto.SerializeToString(),
  599. dependencies=direct_deps,
  600. public_dependencies=public_deps,
  601. # pylint: disable=protected-access
  602. create_key=descriptor._internal_create_key)
  603. scope = {}
  604. # This loop extracts all the message and enum types from all the
  605. # dependencies of the file_proto. This is necessary to create the
  606. # scope of available message types when defining the passed in
  607. # file proto.
  608. for dependency in built_deps:
  609. scope.update(self._ExtractSymbols(
  610. dependency.message_types_by_name.values()))
  611. scope.update((_PrefixWithDot(enum.full_name), enum)
  612. for enum in dependency.enum_types_by_name.values())
  613. for message_type in file_proto.message_type:
  614. message_desc = self._ConvertMessageDescriptor(
  615. message_type, file_proto.package, file_descriptor, scope,
  616. file_proto.syntax)
  617. file_descriptor.message_types_by_name[message_desc.name] = (
  618. message_desc)
  619. for enum_type in file_proto.enum_type:
  620. file_descriptor.enum_types_by_name[enum_type.name] = (
  621. self._ConvertEnumDescriptor(enum_type, file_proto.package,
  622. file_descriptor, None, scope, True))
  623. for index, extension_proto in enumerate(file_proto.extension):
  624. extension_desc = self._MakeFieldDescriptor(
  625. extension_proto, file_proto.package, index, file_descriptor,
  626. is_extension=True)
  627. extension_desc.containing_type = self._GetTypeFromScope(
  628. file_descriptor.package, extension_proto.extendee, scope)
  629. self._SetFieldType(extension_proto, extension_desc,
  630. file_descriptor.package, scope)
  631. file_descriptor.extensions_by_name[extension_desc.name] = (
  632. extension_desc)
  633. for desc_proto in file_proto.message_type:
  634. self._SetAllFieldTypes(file_proto.package, desc_proto, scope)
  635. if file_proto.package:
  636. desc_proto_prefix = _PrefixWithDot(file_proto.package)
  637. else:
  638. desc_proto_prefix = ''
  639. for desc_proto in file_proto.message_type:
  640. desc = self._GetTypeFromScope(
  641. desc_proto_prefix, desc_proto.name, scope)
  642. file_descriptor.message_types_by_name[desc_proto.name] = desc
  643. for index, service_proto in enumerate(file_proto.service):
  644. file_descriptor.services_by_name[service_proto.name] = (
  645. self._MakeServiceDescriptor(service_proto, index, scope,
  646. file_proto.package, file_descriptor))
  647. self._file_descriptors[file_proto.name] = file_descriptor
  648. # Add extensions to the pool
  649. def AddExtensionForNested(message_type):
  650. for nested in message_type.nested_types:
  651. AddExtensionForNested(nested)
  652. for extension in message_type.extensions:
  653. self._AddExtensionDescriptor(extension)
  654. file_desc = self._file_descriptors[file_proto.name]
  655. for extension in file_desc.extensions_by_name.values():
  656. self._AddExtensionDescriptor(extension)
  657. for message_type in file_desc.message_types_by_name.values():
  658. AddExtensionForNested(message_type)
  659. return file_desc
  660. def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None,
  661. scope=None, syntax=None):
  662. """Adds the proto to the pool in the specified package.
  663. Args:
  664. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  665. package: The package the proto should be located in.
  666. file_desc: The file containing this message.
  667. scope: Dict mapping short and full symbols to message and enum types.
  668. syntax: string indicating syntax of the file ("proto2" or "proto3")
  669. Returns:
  670. The added descriptor.
  671. """
  672. if package:
  673. desc_name = '.'.join((package, desc_proto.name))
  674. else:
  675. desc_name = desc_proto.name
  676. if file_desc is None:
  677. file_name = None
  678. else:
  679. file_name = file_desc.name
  680. if scope is None:
  681. scope = {}
  682. nested = [
  683. self._ConvertMessageDescriptor(
  684. nested, desc_name, file_desc, scope, syntax)
  685. for nested in desc_proto.nested_type]
  686. enums = [
  687. self._ConvertEnumDescriptor(enum, desc_name, file_desc, None,
  688. scope, False)
  689. for enum in desc_proto.enum_type]
  690. fields = [self._MakeFieldDescriptor(field, desc_name, index, file_desc)
  691. for index, field in enumerate(desc_proto.field)]
  692. extensions = [
  693. self._MakeFieldDescriptor(extension, desc_name, index, file_desc,
  694. is_extension=True)
  695. for index, extension in enumerate(desc_proto.extension)]
  696. oneofs = [
  697. # pylint: disable=g-complex-comprehension
  698. descriptor.OneofDescriptor(
  699. desc.name,
  700. '.'.join((desc_name, desc.name)),
  701. index,
  702. None,
  703. [],
  704. _OptionsOrNone(desc),
  705. # pylint: disable=protected-access
  706. create_key=descriptor._internal_create_key)
  707. for index, desc in enumerate(desc_proto.oneof_decl)
  708. ]
  709. extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range]
  710. if extension_ranges:
  711. is_extendable = True
  712. else:
  713. is_extendable = False
  714. desc = descriptor.Descriptor(
  715. name=desc_proto.name,
  716. full_name=desc_name,
  717. filename=file_name,
  718. containing_type=None,
  719. fields=fields,
  720. oneofs=oneofs,
  721. nested_types=nested,
  722. enum_types=enums,
  723. extensions=extensions,
  724. options=_OptionsOrNone(desc_proto),
  725. is_extendable=is_extendable,
  726. extension_ranges=extension_ranges,
  727. file=file_desc,
  728. serialized_start=None,
  729. serialized_end=None,
  730. syntax=syntax,
  731. # pylint: disable=protected-access
  732. create_key=descriptor._internal_create_key)
  733. for nested in desc.nested_types:
  734. nested.containing_type = desc
  735. for enum in desc.enum_types:
  736. enum.containing_type = desc
  737. for field_index, field_desc in enumerate(desc_proto.field):
  738. if field_desc.HasField('oneof_index'):
  739. oneof_index = field_desc.oneof_index
  740. oneofs[oneof_index].fields.append(fields[field_index])
  741. fields[field_index].containing_oneof = oneofs[oneof_index]
  742. scope[_PrefixWithDot(desc_name)] = desc
  743. self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
  744. self._descriptors[desc_name] = desc
  745. return desc
  746. def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None,
  747. containing_type=None, scope=None, top_level=False):
  748. """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.
  749. Args:
  750. enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message.
  751. package: Optional package name for the new message EnumDescriptor.
  752. file_desc: The file containing the enum descriptor.
  753. containing_type: The type containing this enum.
  754. scope: Scope containing available types.
  755. top_level: If True, the enum is a top level symbol. If False, the enum
  756. is defined inside a message.
  757. Returns:
  758. The added descriptor
  759. """
  760. if package:
  761. enum_name = '.'.join((package, enum_proto.name))
  762. else:
  763. enum_name = enum_proto.name
  764. if file_desc is None:
  765. file_name = None
  766. else:
  767. file_name = file_desc.name
  768. values = [self._MakeEnumValueDescriptor(value, index)
  769. for index, value in enumerate(enum_proto.value)]
  770. desc = descriptor.EnumDescriptor(name=enum_proto.name,
  771. full_name=enum_name,
  772. filename=file_name,
  773. file=file_desc,
  774. values=values,
  775. containing_type=containing_type,
  776. options=_OptionsOrNone(enum_proto),
  777. # pylint: disable=protected-access
  778. create_key=descriptor._internal_create_key)
  779. scope['.%s' % enum_name] = desc
  780. self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
  781. self._enum_descriptors[enum_name] = desc
  782. # Add top level enum values.
  783. if top_level:
  784. for value in values:
  785. full_name = _NormalizeFullyQualifiedName(
  786. '.'.join((package, value.name)))
  787. self._CheckConflictRegister(value, full_name, file_name)
  788. self._top_enum_values[full_name] = value
  789. return desc
  790. def _MakeFieldDescriptor(self, field_proto, message_name, index,
  791. file_desc, is_extension=False):
  792. """Creates a field descriptor from a FieldDescriptorProto.
  793. For message and enum type fields, this method will do a look up
  794. in the pool for the appropriate descriptor for that type. If it
  795. is unavailable, it will fall back to the _source function to
  796. create it. If this type is still unavailable, construction will
  797. fail.
  798. Args:
  799. field_proto: The proto describing the field.
  800. message_name: The name of the containing message.
  801. index: Index of the field
  802. file_desc: The file containing the field descriptor.
  803. is_extension: Indication that this field is for an extension.
  804. Returns:
  805. An initialized FieldDescriptor object
  806. """
  807. if message_name:
  808. full_name = '.'.join((message_name, field_proto.name))
  809. else:
  810. full_name = field_proto.name
  811. if field_proto.json_name:
  812. json_name = field_proto.json_name
  813. else:
  814. json_name = None
  815. return descriptor.FieldDescriptor(
  816. name=field_proto.name,
  817. full_name=full_name,
  818. index=index,
  819. number=field_proto.number,
  820. type=field_proto.type,
  821. cpp_type=None,
  822. message_type=None,
  823. enum_type=None,
  824. containing_type=None,
  825. label=field_proto.label,
  826. has_default_value=False,
  827. default_value=None,
  828. is_extension=is_extension,
  829. extension_scope=None,
  830. options=_OptionsOrNone(field_proto),
  831. json_name=json_name,
  832. file=file_desc,
  833. # pylint: disable=protected-access
  834. create_key=descriptor._internal_create_key)
  835. def _SetAllFieldTypes(self, package, desc_proto, scope):
  836. """Sets all the descriptor's fields's types.
  837. This method also sets the containing types on any extensions.
  838. Args:
  839. package: The current package of desc_proto.
  840. desc_proto: The message descriptor to update.
  841. scope: Enclosing scope of available types.
  842. """
  843. package = _PrefixWithDot(package)
  844. main_desc = self._GetTypeFromScope(package, desc_proto.name, scope)
  845. if package == '.':
  846. nested_package = _PrefixWithDot(desc_proto.name)
  847. else:
  848. nested_package = '.'.join([package, desc_proto.name])
  849. for field_proto, field_desc in zip(desc_proto.field, main_desc.fields):
  850. self._SetFieldType(field_proto, field_desc, nested_package, scope)
  851. for extension_proto, extension_desc in (
  852. zip(desc_proto.extension, main_desc.extensions)):
  853. extension_desc.containing_type = self._GetTypeFromScope(
  854. nested_package, extension_proto.extendee, scope)
  855. self._SetFieldType(extension_proto, extension_desc, nested_package, scope)
  856. for nested_type in desc_proto.nested_type:
  857. self._SetAllFieldTypes(nested_package, nested_type, scope)
  858. def _SetFieldType(self, field_proto, field_desc, package, scope):
  859. """Sets the field's type, cpp_type, message_type and enum_type.
  860. Args:
  861. field_proto: Data about the field in proto format.
  862. field_desc: The descriptor to modify.
  863. package: The package the field's container is in.
  864. scope: Enclosing scope of available types.
  865. """
  866. if field_proto.type_name:
  867. desc = self._GetTypeFromScope(package, field_proto.type_name, scope)
  868. else:
  869. desc = None
  870. if not field_proto.HasField('type'):
  871. if isinstance(desc, descriptor.Descriptor):
  872. field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE
  873. else:
  874. field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM
  875. field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType(
  876. field_proto.type)
  877. if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE
  878. or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP):
  879. field_desc.message_type = desc
  880. if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  881. field_desc.enum_type = desc
  882. if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  883. field_desc.has_default_value = False
  884. field_desc.default_value = []
  885. elif field_proto.HasField('default_value'):
  886. field_desc.has_default_value = True
  887. if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
  888. field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
  889. field_desc.default_value = float(field_proto.default_value)
  890. elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
  891. field_desc.default_value = field_proto.default_value
  892. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
  893. field_desc.default_value = field_proto.default_value.lower() == 'true'
  894. elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  895. field_desc.default_value = field_desc.enum_type.values_by_name[
  896. field_proto.default_value].number
  897. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
  898. field_desc.default_value = text_encoding.CUnescape(
  899. field_proto.default_value)
  900. elif field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE:
  901. field_desc.default_value = None
  902. else:
  903. # All other types are of the "int" type.
  904. field_desc.default_value = int(field_proto.default_value)
  905. else:
  906. field_desc.has_default_value = False
  907. if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
  908. field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
  909. field_desc.default_value = 0.0
  910. elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
  911. field_desc.default_value = u''
  912. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
  913. field_desc.default_value = False
  914. elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  915. field_desc.default_value = field_desc.enum_type.values[0].number
  916. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
  917. field_desc.default_value = b''
  918. elif field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE:
  919. field_desc.default_value = None
  920. elif field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP:
  921. field_desc.default_value = None
  922. else:
  923. # All other types are of the "int" type.
  924. field_desc.default_value = 0
  925. field_desc.type = field_proto.type
  926. def _MakeEnumValueDescriptor(self, value_proto, index):
  927. """Creates a enum value descriptor object from a enum value proto.
  928. Args:
  929. value_proto: The proto describing the enum value.
  930. index: The index of the enum value.
  931. Returns:
  932. An initialized EnumValueDescriptor object.
  933. """
  934. return descriptor.EnumValueDescriptor(
  935. name=value_proto.name,
  936. index=index,
  937. number=value_proto.number,
  938. options=_OptionsOrNone(value_proto),
  939. type=None,
  940. # pylint: disable=protected-access
  941. create_key=descriptor._internal_create_key)
  942. def _MakeServiceDescriptor(self, service_proto, service_index, scope,
  943. package, file_desc):
  944. """Make a protobuf ServiceDescriptor given a ServiceDescriptorProto.
  945. Args:
  946. service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message.
  947. service_index: The index of the service in the File.
  948. scope: Dict mapping short and full symbols to message and enum types.
  949. package: Optional package name for the new message EnumDescriptor.
  950. file_desc: The file containing the service descriptor.
  951. Returns:
  952. The added descriptor.
  953. """
  954. if package:
  955. service_name = '.'.join((package, service_proto.name))
  956. else:
  957. service_name = service_proto.name
  958. methods = [self._MakeMethodDescriptor(method_proto, service_name, package,
  959. scope, index)
  960. for index, method_proto in enumerate(service_proto.method)]
  961. desc = descriptor.ServiceDescriptor(
  962. name=service_proto.name,
  963. full_name=service_name,
  964. index=service_index,
  965. methods=methods,
  966. options=_OptionsOrNone(service_proto),
  967. file=file_desc,
  968. # pylint: disable=protected-access
  969. create_key=descriptor._internal_create_key)
  970. self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
  971. self._service_descriptors[service_name] = desc
  972. return desc
  973. def _MakeMethodDescriptor(self, method_proto, service_name, package, scope,
  974. index):
  975. """Creates a method descriptor from a MethodDescriptorProto.
  976. Args:
  977. method_proto: The proto describing the method.
  978. service_name: The name of the containing service.
  979. package: Optional package name to look up for types.
  980. scope: Scope containing available types.
  981. index: Index of the method in the service.
  982. Returns:
  983. An initialized MethodDescriptor object.
  984. """
  985. full_name = '.'.join((service_name, method_proto.name))
  986. input_type = self._GetTypeFromScope(
  987. package, method_proto.input_type, scope)
  988. output_type = self._GetTypeFromScope(
  989. package, method_proto.output_type, scope)
  990. return descriptor.MethodDescriptor(
  991. name=method_proto.name,
  992. full_name=full_name,
  993. index=index,
  994. containing_service=None,
  995. input_type=input_type,
  996. output_type=output_type,
  997. client_streaming=method_proto.client_streaming,
  998. server_streaming=method_proto.server_streaming,
  999. options=_OptionsOrNone(method_proto),
  1000. # pylint: disable=protected-access
  1001. create_key=descriptor._internal_create_key)
  1002. def _ExtractSymbols(self, descriptors):
  1003. """Pulls out all the symbols from descriptor protos.
  1004. Args:
  1005. descriptors: The messages to extract descriptors from.
  1006. Yields:
  1007. A two element tuple of the type name and descriptor object.
  1008. """
  1009. for desc in descriptors:
  1010. yield (_PrefixWithDot(desc.full_name), desc)
  1011. for symbol in self._ExtractSymbols(desc.nested_types):
  1012. yield symbol
  1013. for enum in desc.enum_types:
  1014. yield (_PrefixWithDot(enum.full_name), enum)
  1015. def _GetDeps(self, dependencies, visited=None):
  1016. """Recursively finds dependencies for file protos.
  1017. Args:
  1018. dependencies: The names of the files being depended on.
  1019. visited: The names of files already found.
  1020. Yields:
  1021. Each direct and indirect dependency.
  1022. """
  1023. visited = visited or set()
  1024. for dependency in dependencies:
  1025. if dependency not in visited:
  1026. visited.add(dependency)
  1027. dep_desc = self.FindFileByName(dependency)
  1028. yield dep_desc
  1029. public_files = [d.name for d in dep_desc.public_dependencies]
  1030. yield from self._GetDeps(public_files, visited)
  1031. def _GetTypeFromScope(self, package, type_name, scope):
  1032. """Finds a given type name in the current scope.
  1033. Args:
  1034. package: The package the proto should be located in.
  1035. type_name: The name of the type to be found in the scope.
  1036. scope: Dict mapping short and full symbols to message and enum types.
  1037. Returns:
  1038. The descriptor for the requested type.
  1039. """
  1040. if type_name not in scope:
  1041. components = _PrefixWithDot(package).split('.')
  1042. while components:
  1043. possible_match = '.'.join(components + [type_name])
  1044. if possible_match in scope:
  1045. type_name = possible_match
  1046. break
  1047. else:
  1048. components.pop(-1)
  1049. return scope[type_name]
  1050. def _PrefixWithDot(name):
  1051. return name if name.startswith('.') else '.%s' % name
  1052. if _USE_C_DESCRIPTORS:
  1053. # TODO(amauryfa): This pool could be constructed from Python code, when we
  1054. # support a flag like 'use_cpp_generated_pool=True'.
  1055. # pylint: disable=protected-access
  1056. _DEFAULT = descriptor._message.default_pool
  1057. else:
  1058. _DEFAULT = DescriptorPool()
  1059. def Default():
  1060. return _DEFAULT