xref: /aosp_15_r20/external/cronet/third_party/protobuf/python/google/protobuf/descriptor_database.py (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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
31"""Provides a container for DescriptorProtos."""
32
33__author__ = '[email protected] (Matt Toia)'
34
35import warnings
36
37
38class Error(Exception):
39  pass
40
41
42class DescriptorDatabaseConflictingDefinitionError(Error):
43  """Raised when a proto is added with the same name & different descriptor."""
44
45
46class DescriptorDatabase(object):
47  """A container accepting FileDescriptorProtos and maps DescriptorProtos."""
48
49  def __init__(self):
50    self._file_desc_protos_by_file = {}
51    self._file_desc_protos_by_symbol = {}
52
53  def Add(self, file_desc_proto):
54    """Adds the FileDescriptorProto and its types to this database.
55
56    Args:
57      file_desc_proto: The FileDescriptorProto to add.
58    Raises:
59      DescriptorDatabaseConflictingDefinitionError: if an attempt is made to
60        add a proto with the same name but different definition than an
61        existing proto in the database.
62    """
63    proto_name = file_desc_proto.name
64    if proto_name not in self._file_desc_protos_by_file:
65      self._file_desc_protos_by_file[proto_name] = file_desc_proto
66    elif self._file_desc_protos_by_file[proto_name] != file_desc_proto:
67      raise DescriptorDatabaseConflictingDefinitionError(
68          '%s already added, but with different descriptor.' % proto_name)
69    else:
70      return
71
72    # Add all the top-level descriptors to the index.
73    package = file_desc_proto.package
74    for message in file_desc_proto.message_type:
75      for name in _ExtractSymbols(message, package):
76        self._AddSymbol(name, file_desc_proto)
77    for enum in file_desc_proto.enum_type:
78      self._AddSymbol(('.'.join((package, enum.name))), file_desc_proto)
79      for enum_value in enum.value:
80        self._file_desc_protos_by_symbol[
81            '.'.join((package, enum_value.name))] = file_desc_proto
82    for extension in file_desc_proto.extension:
83      self._AddSymbol(('.'.join((package, extension.name))), file_desc_proto)
84    for service in file_desc_proto.service:
85      self._AddSymbol(('.'.join((package, service.name))), file_desc_proto)
86
87  def FindFileByName(self, name):
88    """Finds the file descriptor proto by file name.
89
90    Typically the file name is a relative path ending to a .proto file. The
91    proto with the given name will have to have been added to this database
92    using the Add method or else an error will be raised.
93
94    Args:
95      name: The file name to find.
96
97    Returns:
98      The file descriptor proto matching the name.
99
100    Raises:
101      KeyError if no file by the given name was added.
102    """
103
104    return self._file_desc_protos_by_file[name]
105
106  def FindFileContainingSymbol(self, symbol):
107    """Finds the file descriptor proto containing the specified symbol.
108
109    The symbol should be a fully qualified name including the file descriptor's
110    package and any containing messages. Some examples:
111
112    'some.package.name.Message'
113    'some.package.name.Message.NestedEnum'
114    'some.package.name.Message.some_field'
115
116    The file descriptor proto containing the specified symbol must be added to
117    this database using the Add method or else an error will be raised.
118
119    Args:
120      symbol: The fully qualified symbol name.
121
122    Returns:
123      The file descriptor proto containing the symbol.
124
125    Raises:
126      KeyError if no file contains the specified symbol.
127    """
128    try:
129      return self._file_desc_protos_by_symbol[symbol]
130    except KeyError:
131      # Fields, enum values, and nested extensions are not in
132      # _file_desc_protos_by_symbol. Try to find the top level
133      # descriptor. Non-existent nested symbol under a valid top level
134      # descriptor can also be found. The behavior is the same with
135      # protobuf C++.
136      top_level, _, _ = symbol.rpartition('.')
137      try:
138        return self._file_desc_protos_by_symbol[top_level]
139      except KeyError:
140        # Raise the original symbol as a KeyError for better diagnostics.
141        raise KeyError(symbol)
142
143  def FindFileContainingExtension(self, extendee_name, extension_number):
144    # TODO(jieluo): implement this API.
145    return None
146
147  def FindAllExtensionNumbers(self, extendee_name):
148    # TODO(jieluo): implement this API.
149    return []
150
151  def _AddSymbol(self, name, file_desc_proto):
152    if name in self._file_desc_protos_by_symbol:
153      warn_msg = ('Conflict register for file "' + file_desc_proto.name +
154                  '": ' + name +
155                  ' is already defined in file "' +
156                  self._file_desc_protos_by_symbol[name].name + '"')
157      warnings.warn(warn_msg, RuntimeWarning)
158    self._file_desc_protos_by_symbol[name] = file_desc_proto
159
160
161def _ExtractSymbols(desc_proto, package):
162  """Pulls out all the symbols from a descriptor proto.
163
164  Args:
165    desc_proto: The proto to extract symbols from.
166    package: The package containing the descriptor type.
167
168  Yields:
169    The fully qualified name found in the descriptor.
170  """
171  message_name = package + '.' + desc_proto.name if package else desc_proto.name
172  yield message_name
173  for nested_type in desc_proto.nested_type:
174    for symbol in _ExtractSymbols(nested_type, message_name):
175      yield symbol
176  for enum_type in desc_proto.enum_type:
177    yield '.'.join((message_name, enum_type.name))
178