descriptor_pool.py 43 KB

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