descriptor_pool.py 43 KB

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