Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-10-01 08:56:09

0001 // Protocol Buffers - Google's data interchange format
0002 // Copyright 2008 Google Inc.  All rights reserved.
0003 //
0004 // Use of this source code is governed by a BSD-style
0005 // license that can be found in the LICENSE file or at
0006 // https://developers.google.com/open-source/licenses/bsd
0007 
0008 // Author: kenton@google.com (Kenton Varda)
0009 //  Based on original Protocol Buffers design by
0010 //  Sanjay Ghemawat, Jeff Dean, and others.
0011 //
0012 // This file contains classes which describe a type of protocol message.
0013 // You can use a message's descriptor to learn at runtime what fields
0014 // it contains and what the types of those fields are.  The Message
0015 // interface also allows you to dynamically access and modify individual
0016 // fields by passing the FieldDescriptor of the field you are interested
0017 // in.
0018 //
0019 // Most users will not care about descriptors, because they will write
0020 // code specific to certain protocol types and will simply use the classes
0021 // generated by the protocol compiler directly.  Advanced users who want
0022 // to operate on arbitrary types (not known at compile time) may want to
0023 // read descriptors in order to learn about the contents of a message.
0024 // A very small number of users will want to construct their own
0025 // Descriptors, either because they are implementing Message manually or
0026 // because they are writing something like the protocol compiler.
0027 //
0028 // For an example of how you might use descriptors, see the code example
0029 // at the top of message.h.
0030 
0031 #ifndef GOOGLE_PROTOBUF_DESCRIPTOR_H__
0032 #define GOOGLE_PROTOBUF_DESCRIPTOR_H__
0033 
0034 #include <atomic>
0035 #include <cstdint>
0036 #include <iterator>
0037 #include <memory>
0038 #include <string>
0039 #include <type_traits>
0040 #include <utility>
0041 #include <vector>
0042 
0043 #include "absl/base/attributes.h"
0044 #include "absl/base/call_once.h"
0045 #include "absl/base/macros.h"
0046 #include "absl/base/optimization.h"
0047 #include "absl/container/flat_hash_map.h"
0048 #include "absl/functional/any_invocable.h"
0049 #include "absl/functional/function_ref.h"
0050 #include "absl/log/absl_check.h"
0051 #include "absl/log/absl_log.h"
0052 #include "absl/strings/str_format.h"
0053 #include "absl/strings/string_view.h"
0054 #include "absl/synchronization/mutex.h"
0055 #include "google/protobuf/descriptor_lite.h"
0056 #include "google/protobuf/extension_set.h"
0057 #include "google/protobuf/port.h"
0058 
0059 // Must be included last.
0060 #include "google/protobuf/port_def.inc"
0061 
0062 #ifdef SWIG
0063 #define PROTOBUF_EXPORT
0064 #define PROTOBUF_IGNORE_DEPRECATION_START
0065 #define PROTOBUF_IGNORE_DEPRECATION_STOP
0066 #endif
0067 
0068 
0069 namespace google {
0070 namespace protobuf {
0071 // Defined in this file.
0072 class Descriptor;
0073 class FieldDescriptor;
0074 class OneofDescriptor;
0075 class EnumDescriptor;
0076 class EnumValueDescriptor;
0077 class ServiceDescriptor;
0078 class MethodDescriptor;
0079 class FileDescriptor;
0080 class DescriptorDatabase;
0081 class DescriptorPool;
0082 
0083 // Defined in descriptor.proto
0084 #ifndef SWIG
0085 enum Edition : int;
0086 enum SymbolVisibility : int;
0087 #else   // !SWIG
0088 typedef int Edition;
0089 typedef int SymbolVisibility;
0090 #endif  // !SWIG
0091 class DescriptorProto;
0092 class DescriptorProto_ExtensionRange;
0093 class FieldDescriptorProto;
0094 class OneofDescriptorProto;
0095 class EnumDescriptorProto;
0096 class EnumValueDescriptorProto;
0097 class ServiceDescriptorProto;
0098 class MethodDescriptorProto;
0099 class FileDescriptorProto;
0100 class MessageOptions;
0101 class FieldOptions;
0102 class OneofOptions;
0103 class EnumOptions;
0104 class EnumValueOptions;
0105 class ExtensionRangeOptions;
0106 class ServiceOptions;
0107 class MethodOptions;
0108 class FileOptions;
0109 class UninterpretedOption;
0110 class FeatureSet;
0111 class FeatureSetDefaults;
0112 class SourceCodeInfo;
0113 
0114 // Defined in message_lite.h
0115 class MessageLite;
0116 
0117 // Defined in message.h
0118 class Message;
0119 class Reflection;
0120 
0121 // Defined in descriptor.cc
0122 class DescriptorBuilder;
0123 class FileDescriptorTables;
0124 class Symbol;
0125 
0126 // Defined in unknown_field_set.h.
0127 class UnknownField;
0128 
0129 // Defined in command_line_interface.cc
0130 namespace compiler {
0131 class CodeGenerator;
0132 class CommandLineInterface;
0133 namespace cpp {
0134 class CppGenerator;
0135 // Defined in helpers.h
0136 class Formatter;
0137 }  // namespace cpp
0138 namespace java {
0139 class MemoizeProjection;
0140 }  // namespace java
0141 }  // namespace compiler
0142 
0143 namespace descriptor_unittest {
0144 class DescriptorPoolMemoizationTest;
0145 class DescriptorTest;
0146 class ValidationErrorTest;
0147 }  // namespace descriptor_unittest
0148 
0149 // Defined in printer.h
0150 namespace io {
0151 class Printer;
0152 }  // namespace io
0153 
0154 namespace internal {
0155 class InternalFeatureHelper;
0156 }  // namespace internal
0157 
0158 // NB, all indices are zero-based.
0159 struct SourceLocation {
0160   int start_line;
0161   int end_line;
0162   int start_column;
0163   int end_column;
0164 
0165   // Doc comments found at the source location.
0166   // See the comments in SourceCodeInfo.Location (descriptor.proto) for details.
0167   std::string leading_comments;
0168   std::string trailing_comments;
0169   std::vector<std::string> leading_detached_comments;
0170 };
0171 
0172 // Options when generating machine-parsable output from a descriptor with
0173 // DebugString().
0174 struct DebugStringOptions {
0175   // include original user comments as recorded in SourceLocation entries. N.B.
0176   // that this must be |false| by default: several other pieces of code (for
0177   // example, the C++ code generation for fields in the proto compiler) rely on
0178   // DebugString() output being unobstructed by user comments.
0179   bool include_comments;
0180   // If true, elide the braced body in the debug string.
0181   bool elide_group_body;
0182   bool elide_oneof_body;
0183 
0184   DebugStringOptions()
0185       : include_comments(false),
0186         elide_group_body(false),
0187         elide_oneof_body(false) {
0188   }
0189 };
0190 
0191 // A class to handle the simplest cases of a lazily linked descriptor
0192 // for a message type that isn't built at the time of cross linking,
0193 // which is needed when a pool has lazily_build_dependencies_ set.
0194 // Must be instantiated as mutable in a descriptor.
0195 namespace internal {
0196 
0197 // The classes in this file represent a significant memory footprint for the
0198 // library. We make sure we are not accidentally making them larger by
0199 // hardcoding the struct size for a specific platform. Use as:
0200 //
0201 //   PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(type, expected_size_in_x84-64);
0202 //
0203 
0204 #if !defined(PROTOBUF_INTERNAL_CHECK_CLASS_SIZE)
0205 #define PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(t, expected)
0206 #endif
0207 
0208 // This class is used to index into the memory it is pointing at.
0209 // The layout is as follows:
0210 //  [ chars .... ] [ data0 (uint16_t) ] [ ... ] [ dataN (uint16_t) ]
0211 //                ^
0212 //       payload_ points here
0213 //
0214 // The offsets are relative to payload_.
0215 //
0216 // The offsets are as follows:
0217 //  (0) `name` size. `name` ends at `payload_`
0218 //  (1) `full_name` size. `full_name` ends at `payload_` and shares bytes with
0219 //      `name`.
0220 //    .. the following offsets only available for `FieldDescriptor` ..
0221 //  (2)/(3) `lowercase` offset/size. The data bytes could be shared.
0222 //  (4)/(5) `camelcase` offset/size. The data bytes could be shared.
0223 //  (6)/(7) `json_name` offset/size. The data bytes could be shared.
0224 //
0225 //  NOTE ABOUT NULL TERMINATION:
0226 //  The name accessors were migrated from `std::string` to `absl::string_view`,
0227 //  which caused valid code to break. In particular, there are previously
0228 //  correct callers calling `foo.name().data()` and using it as a NULL
0229 //  terminated C-string.
0230 //  To prevent further breakage we are adding null termination on all these
0231 //  names even though it is outside the contract for `absl::string_view`.
0232 //  This might change in the future.
0233 class DescriptorNames {
0234  public:
0235   // Uninitialized, to support `= default` of descriptor types.
0236   DescriptorNames() = default;
0237   explicit DescriptorNames(const char* payload) : payload_(payload) {}
0238 
0239   // The full name is just before `payload_`, and the name is the suffix of it.
0240   // We don't need a special offset for them.
0241   // NOTE: the sizes don't include the null terminator, so add +1 to the offset.
0242   absl::string_view name() const { return get(get_size(0) + 1, get_size(0)); }
0243   absl::string_view full_name() const {
0244     return get(get_size(1) + 1, get_size(1));
0245   }
0246 
0247   // Only available for `FieldDescriptor`. This is not checked at runtime.
0248   // NOTE: The offsets here already take into account the null terminator.
0249   absl::string_view lowercase_name() const {
0250     return get(get_size(2), get_size(3));
0251   }
0252   absl::string_view camelcase_name() const {
0253     return get(get_size(4), get_size(5));
0254   }
0255   absl::string_view json_name() const { return get(get_size(6), get_size(7)); }
0256 
0257   static constexpr size_t AllocationSizeForSimpleNames(size_t full_name_size) {
0258     return full_name_size + /* \0 */ 1 + 2 * sizeof(uint16_t);
0259   }
0260 
0261  private:
0262   size_t get_size(int index) const {
0263     // We don't use `uint16_t` in the payload type to avoid having to align it.
0264     // Instead, we read via memcpy.
0265     uint16_t size;
0266     memcpy(&size, payload_ + index * sizeof(size), sizeof(size));
0267     return size;
0268   }
0269 
0270   absl::string_view get(size_t offset, size_t size) const {
0271     return absl::string_view(payload_ - offset, size);
0272   }
0273 
0274   const char* payload_;
0275 };
0276 
0277 class FlatAllocator;
0278 
0279 class PROTOBUF_EXPORT LazyDescriptor {
0280  public:
0281   // Init function to be called at init time of a descriptor containing
0282   // a LazyDescriptor.
0283   void Init() {
0284     descriptor_ = nullptr;
0285     once_ = nullptr;
0286   }
0287 
0288   // Sets the value of the descriptor if it is known during the descriptor
0289   // building process. Not thread safe, should only be called during the
0290   // descriptor build process. Should not be called after SetLazy has been
0291   // called.
0292   void Set(const Descriptor* descriptor);
0293 
0294   // Sets the information needed to lazily cross link the descriptor at a later
0295   // time, SetLazy is not thread safe, should be called only once at descriptor
0296   // build time if the symbol wasn't found and building of the file containing
0297   // that type is delayed because lazily_build_dependencies_ is set on the pool.
0298   // Should not be called after Set() has been called.
0299   void SetLazy(absl::string_view name, const FileDescriptor* file);
0300 
0301   // Returns the current value of the descriptor, thread-safe. If SetLazy(...)
0302   // has been called, will do a one-time cross link of the type specified,
0303   // building the descriptor file that contains the type if necessary.
0304   inline const Descriptor* Get(const ServiceDescriptor* service) {
0305     Once(service);
0306     return descriptor_;
0307   }
0308 
0309  private:
0310   void Once(const ServiceDescriptor* service);
0311 
0312   const Descriptor* descriptor_;
0313   // The once_ flag is followed by a NUL terminated string for the type name.
0314   absl::once_flag* once_;
0315 };
0316 
0317 class PROTOBUF_EXPORT SymbolBase {
0318  private:
0319   friend class google::protobuf::Symbol;
0320   uint8_t symbol_type_;
0321 };
0322 
0323 // Some types have more than one SymbolBase because they have multiple
0324 // identities in the table. We can't have duplicate direct bases, so we use this
0325 // intermediate base to do so.
0326 // See BuildEnumValue for details.
0327 template <int N>
0328 class PROTOBUF_EXPORT SymbolBaseN : public SymbolBase {};
0329 
0330 PROTOBUF_EXPORT absl::string_view ShortEditionName(Edition edition);
0331 
0332 bool IsEnumFullySequential(const EnumDescriptor* enum_desc);
0333 
0334 const std::string& DefaultValueStringAsString(const FieldDescriptor* field);
0335 const std::string& NameOfEnumAsString(const EnumValueDescriptor* descriptor);
0336 
0337 }  // namespace internal
0338 
0339 // Provide an Abseil formatter for edition names.
0340 template <typename Sink>
0341 void AbslStringify(Sink& sink, Edition edition) {
0342   absl::Format(&sink, "%v", internal::ShortEditionName(edition));
0343 }
0344 
0345 // Describes a type of protocol message, or a particular group within a
0346 // message.  To obtain the Descriptor for a given message object, call
0347 // Message::GetDescriptor().  Generated message classes also have a
0348 // static method called descriptor() which returns the type's descriptor.
0349 // Use DescriptorPool to construct your own descriptors.
0350 class PROTOBUF_EXPORT Descriptor : private internal::SymbolBase {
0351  public:
0352   typedef DescriptorProto Proto;
0353 #ifndef SWIG
0354   Descriptor(const Descriptor&) = delete;
0355   Descriptor& operator=(const Descriptor&) = delete;
0356 #endif
0357 
0358   // The name of the message type, not including its scope.
0359   absl::string_view name() const;
0360 
0361   // The fully-qualified name of the message type, scope delimited by
0362   // periods.  For example, message type "Foo" which is declared in package
0363   // "bar" has full name "bar.Foo".  If a type "Baz" is nested within
0364   // Foo, Baz's full_name is "bar.Foo.Baz".  To get only the part that
0365   // comes after the last '.', use name().
0366   absl::string_view full_name() const;
0367 
0368   // Index of this descriptor within the file or containing type's message
0369   // type array.
0370   int index() const;
0371 
0372   // The .proto file in which this message type was defined.  Never nullptr.
0373   const FileDescriptor* file() const;
0374 
0375   // If this Descriptor describes a nested type, this returns the type
0376   // in which it is nested.  Otherwise, returns nullptr.
0377   const Descriptor* containing_type() const;
0378 
0379   // Get options for this message type.  These are specified in the .proto file
0380   // by placing lines like "option foo = 1234;" in the message definition.
0381   // Allowed options are defined by MessageOptions in descriptor.proto, and any
0382   // available extensions of that message.
0383   const MessageOptions& options() const;
0384 
0385   // Write the contents of this Descriptor into the given DescriptorProto.
0386   // The target DescriptorProto must be clear before calling this; if it
0387   // isn't, the result may be garbage.
0388   void CopyTo(DescriptorProto* proto) const;
0389 
0390   // Fills in the message-level settings of this message (e.g. name, reserved
0391   // fields, message options) to `proto`.  This is essentially all of the
0392   // metadata owned exclusively by this descriptor, and not any nested
0393   // descriptors.
0394   void CopyHeadingTo(DescriptorProto* proto) const;
0395 
0396   // Write the contents of this descriptor in a human-readable form. Output
0397   // will be suitable for re-parsing.
0398   std::string DebugString() const;
0399 
0400   // Similar to DebugString(), but additionally takes options (e.g.,
0401   // include original user comments in output).
0402   std::string DebugStringWithOptions(const DebugStringOptions& options) const;
0403 
0404   // Allows formatting with absl and gtest.
0405   template <typename Sink>
0406   friend void AbslStringify(Sink& sink, const Descriptor& d) {
0407     absl::Format(&sink, "%s", d.DebugString());
0408   }
0409 
0410   // Returns true if this is a placeholder for an unknown type. This will
0411   // only be the case if this descriptor comes from a DescriptorPool
0412   // with AllowUnknownDependencies() set.
0413   bool is_placeholder() const;
0414 
0415   enum WellKnownType {
0416     WELLKNOWNTYPE_UNSPECIFIED,  // Not a well-known type.
0417 
0418     // Wrapper types.
0419     WELLKNOWNTYPE_DOUBLEVALUE,  // google.protobuf.DoubleValue
0420     WELLKNOWNTYPE_FLOATVALUE,   // google.protobuf.FloatValue
0421     WELLKNOWNTYPE_INT64VALUE,   // google.protobuf.Int64Value
0422     WELLKNOWNTYPE_UINT64VALUE,  // google.protobuf.UInt64Value
0423     WELLKNOWNTYPE_INT32VALUE,   // google.protobuf.Int32Value
0424     WELLKNOWNTYPE_UINT32VALUE,  // google.protobuf.UInt32Value
0425     WELLKNOWNTYPE_STRINGVALUE,  // google.protobuf.StringValue
0426     WELLKNOWNTYPE_BYTESVALUE,   // google.protobuf.BytesValue
0427     WELLKNOWNTYPE_BOOLVALUE,    // google.protobuf.BoolValue
0428 
0429     // Other well known types.
0430     WELLKNOWNTYPE_ANY,        // google.protobuf.Any
0431     WELLKNOWNTYPE_FIELDMASK,  // google.protobuf.FieldMask
0432     WELLKNOWNTYPE_DURATION,   // google.protobuf.Duration
0433     WELLKNOWNTYPE_TIMESTAMP,  // google.protobuf.Timestamp
0434     WELLKNOWNTYPE_VALUE,      // google.protobuf.Value
0435     WELLKNOWNTYPE_LISTVALUE,  // google.protobuf.ListValue
0436     WELLKNOWNTYPE_STRUCT,     // google.protobuf.Struct
0437 
0438     // New well-known types may be added in the future.
0439     // Please make sure any switch() statements have a 'default' case.
0440     __WELLKNOWNTYPE__DO_NOT_USE__ADD_DEFAULT_INSTEAD__,
0441   };
0442 
0443   WellKnownType well_known_type() const;
0444 
0445   // Field stuff -----------------------------------------------------
0446 
0447   // The number of fields in this message type.
0448   int field_count() const;
0449   // Gets a field by index, where 0 <= index < field_count().
0450   // These are returned in the order they were defined in the .proto file, not
0451   // the field number order. (Use `FindFieldByNumber()` for
0452   // tag number -> value lookup).
0453   const FieldDescriptor* field(int index) const;
0454 
0455   // Looks up a field by declared tag number.  Returns nullptr if no such field
0456   // exists.
0457   const FieldDescriptor* FindFieldByNumber(int number) const;
0458   // Looks up a field by name.  Returns nullptr if no such field exists.
0459   const FieldDescriptor* FindFieldByName(absl::string_view name) const;
0460 
0461   // Looks up a field by lowercased name (as returned by lowercase_name()).
0462   // This lookup may be ambiguous if multiple field names differ only by case,
0463   // in which case the field returned is chosen arbitrarily from the matches.
0464   const FieldDescriptor* FindFieldByLowercaseName(
0465       absl::string_view lowercase_name) const;
0466 
0467   // Looks up a field by camel-case name (as returned by camelcase_name()).
0468   // This lookup may be ambiguous if multiple field names differ in a way that
0469   // leads them to have identical camel-case names, in which case the field
0470   // returned is chosen arbitrarily from the matches.
0471   const FieldDescriptor* FindFieldByCamelcaseName(
0472       absl::string_view camelcase_name) const;
0473 
0474   // The number of oneofs in this message type.
0475   int oneof_decl_count() const;
0476   // The number of oneofs in this message type, excluding synthetic oneofs.
0477   // Real oneofs always come first, so iterating up to real_oneof_decl_cout()
0478   // will yield all real oneofs.
0479   int real_oneof_decl_count() const;
0480   // Get a oneof by index, where 0 <= index < oneof_decl_count().
0481   // These are returned in the order they were defined in the .proto file.
0482   const OneofDescriptor* oneof_decl(int index) const;
0483   // Get a oneof by index, excluding synthetic oneofs, where 0 <= index <
0484   // real_oneof_decl_count(). These are returned in the order they were defined
0485   // in the .proto file.
0486   const OneofDescriptor* real_oneof_decl(int index) const;
0487 
0488   // Looks up a oneof by name.  Returns nullptr if no such oneof exists.
0489   const OneofDescriptor* FindOneofByName(absl::string_view name) const;
0490 
0491   // Nested type stuff -----------------------------------------------
0492 
0493   // The number of nested types in this message type.
0494   int nested_type_count() const;
0495   // Gets a nested type by index, where 0 <= index < nested_type_count().
0496   // These are returned in the order they were defined in the .proto file.
0497   const Descriptor* nested_type(int index) const;
0498 
0499   // Looks up a nested type by name.  Returns nullptr if no such nested type
0500   // exists.
0501   const Descriptor* FindNestedTypeByName(absl::string_view name) const;
0502 
0503   // Enum stuff ------------------------------------------------------
0504 
0505   // The number of enum types in this message type.
0506   int enum_type_count() const;
0507   // Gets an enum type by index, where 0 <= index < enum_type_count().
0508   // These are returned in the order they were defined in the .proto file.
0509   const EnumDescriptor* enum_type(int index) const;
0510 
0511   // Looks up an enum type by name.  Returns nullptr if no such enum type
0512   // exists.
0513   const EnumDescriptor* FindEnumTypeByName(absl::string_view name) const;
0514 
0515   // Looks up an enum value by name, among all enum types in this message.
0516   // Returns nullptr if no such value exists.
0517   const EnumValueDescriptor* FindEnumValueByName(absl::string_view name) const;
0518 
0519   // Extensions ------------------------------------------------------
0520 
0521   // A range of field numbers which are designated for third-party
0522   // extensions.
0523   class PROTOBUF_EXPORT ExtensionRange {
0524    public:
0525     typedef DescriptorProto_ExtensionRange Proto;
0526 
0527     typedef ExtensionRangeOptions OptionsType;
0528 
0529     // See Descriptor::CopyTo().
0530     void CopyTo(DescriptorProto_ExtensionRange* proto) const;
0531 
0532     // Returns the start field number of this range (inclusive).
0533     int start_number() const { return start_; }
0534 
0535     // Returns the end field number of this range (exclusive).
0536     int end_number() const { return end_; }
0537 
0538     // Returns the index of this extension range within the message's extension
0539     // range array.
0540     int index() const;
0541 
0542     // Returns the ExtensionRangeOptions for this range.
0543     const ExtensionRangeOptions& options() const { return *options_; }
0544 
0545     // Returns the name of the containing type.
0546     absl::string_view name() const { return containing_type_->name(); }
0547 
0548     // Returns the full name of the containing type.
0549     absl::string_view full_name() const {
0550       return containing_type_->full_name();
0551     }
0552 
0553     // Returns the .proto file in which this range was defined.
0554     // Never nullptr.
0555     const FileDescriptor* file() const { return containing_type_->file(); }
0556 
0557     // Returns the Descriptor for the message containing this range.
0558     // Never nullptr.
0559     const Descriptor* containing_type() const { return containing_type_; }
0560 
0561    private:
0562     int start_;
0563     int end_;
0564     const ExtensionRangeOptions* options_;
0565 
0566    private:
0567     const Descriptor* containing_type_;
0568     const FeatureSet* proto_features_;
0569     const FeatureSet* merged_features_;
0570 
0571     // Get the merged features that apply to this extension range.  These are
0572     // specified in the .proto file through the feature options in the message
0573     // definition. Allowed features are defined by Features in descriptor.proto,
0574     // along with any backend-specific extensions to it.
0575     const FeatureSet& features() const { return *merged_features_; }
0576     friend class internal::InternalFeatureHelper;
0577 
0578     // Walks up the descriptor tree to generate the source location path
0579     // to this descriptor from the file root.
0580     void GetLocationPath(std::vector<int>* output) const;
0581 
0582     friend class Descriptor;
0583     friend class DescriptorPool;
0584     friend class DescriptorBuilder;
0585   };
0586 
0587   // The number of extension ranges in this message type.
0588   int extension_range_count() const;
0589   // Gets an extension range by index, where 0 <= index <
0590   // extension_range_count(). These are returned in the order they were defined
0591   // in the .proto file.
0592   const ExtensionRange* extension_range(int index) const;
0593 
0594   // Returns true if the number is in one of the extension ranges.
0595   bool IsExtensionNumber(int number) const;
0596 
0597   // Returns nullptr if no extension range contains the given number.
0598   const ExtensionRange* FindExtensionRangeContainingNumber(int number) const;
0599 
0600   // The number of extensions defined nested within this message type's scope.
0601   // See doc:
0602   // https://developers.google.com/protocol-buffers/docs/proto#nested-extensions
0603   //
0604   // Note that the extensions may be extending *other* messages.
0605   //
0606   // For example:
0607   // message M1 {
0608   //   extensions 1 to max;
0609   // }
0610   //
0611   // message M2 {
0612   //   extend M1 {
0613   //     optional int32 foo = 1;
0614   //   }
0615   // }
0616   //
0617   // In this case,
0618   // DescriptorPool::generated_pool()
0619   //     ->FindMessageTypeByName("M2")
0620   //     ->extension(0)
0621   // will return "foo", even though "foo" is an extension of M1.
0622   // To find all known extensions of a given message, instead use
0623   // DescriptorPool::FindAllExtensions.
0624   int extension_count() const;
0625   // Get an extension by index, where 0 <= index < extension_count().
0626   // These are returned in the order they were defined in the .proto file.
0627   const FieldDescriptor* extension(int index) const;
0628 
0629   // Looks up a named extension (which extends some *other* message type)
0630   // defined within this message type's scope.
0631   const FieldDescriptor* FindExtensionByName(absl::string_view name) const;
0632 
0633   // Similar to FindFieldByLowercaseName(), but finds extensions defined within
0634   // this message type's scope.
0635   const FieldDescriptor* FindExtensionByLowercaseName(
0636       absl::string_view name) const;
0637 
0638   // Similar to FindFieldByCamelcaseName(), but finds extensions defined within
0639   // this message type's scope.
0640   const FieldDescriptor* FindExtensionByCamelcaseName(
0641       absl::string_view name) const;
0642 
0643   // Reserved fields -------------------------------------------------
0644 
0645   // A range of reserved field numbers.
0646   struct ReservedRange {
0647     int start;  // inclusive
0648     int end;    // exclusive
0649   };
0650 
0651   // The number of reserved ranges in this message type.
0652   int reserved_range_count() const;
0653   // Gets an reserved range by index, where 0 <= index <
0654   // reserved_range_count(). These are returned in the order they were defined
0655   // in the .proto file.
0656   const ReservedRange* reserved_range(int index) const;
0657 
0658   // Returns true if the number is in one of the reserved ranges.
0659   bool IsReservedNumber(int number) const;
0660 
0661   // Returns nullptr if no reserved range contains the given number.
0662   const ReservedRange* FindReservedRangeContainingNumber(int number) const;
0663 
0664   // The number of reserved field names in this message type.
0665   int reserved_name_count() const;
0666 
0667   // Gets a reserved name by index, where 0 <= index < reserved_name_count().
0668   absl::string_view reserved_name(int index) const;
0669 
0670   // Returns true if the field name is reserved.
0671   bool IsReservedName(absl::string_view name) const;
0672 
0673   // Source Location ---------------------------------------------------
0674 
0675   // Updates |*out_location| to the source location of the complete
0676   // extent of this message declaration.  Returns false and leaves
0677   // |*out_location| unchanged iff location information was not available.
0678   bool GetSourceLocation(SourceLocation* out_location) const;
0679 
0680   // Maps --------------------------------------------------------------
0681 
0682   // Returns the FieldDescriptor for the "key" field. If this isn't a map entry
0683   // field, returns nullptr.
0684   const FieldDescriptor* map_key() const;
0685 
0686   // Returns the FieldDescriptor for the "value" field. If this isn't a map
0687   // entry field, returns nullptr.
0688   const FieldDescriptor* map_value() const;
0689 
0690  private:
0691   friend class Symbol;
0692   typedef MessageOptions OptionsType;
0693 
0694   // Allows tests to test CopyTo(proto, true).
0695   friend class descriptor_unittest::DescriptorTest;
0696 
0697   // Allows access to GetLocationPath for annotations.
0698   friend class io::Printer;
0699   friend class compiler::cpp::Formatter;
0700 
0701   // Get the merged features that apply to this message type.  These are
0702   // specified in the .proto file through the feature options in the message
0703   // definition.  Allowed features are defined by Features in descriptor.proto,
0704   // along with any backend-specific extensions to it.
0705   const FeatureSet& features() const { return *merged_features_; }
0706   friend class internal::InternalFeatureHelper;
0707 
0708   // Fill the json_name field of FieldDescriptorProto.
0709   void CopyJsonNameTo(DescriptorProto* proto) const;
0710 
0711   // Internal version of DebugString; controls the level of indenting for
0712   // correct depth. Takes |options| to control debug-string options, and
0713   // |include_opening_clause| to indicate whether the "message ... " part of the
0714   // clause has already been generated (this varies depending on context).
0715   void DebugString(int depth, std::string* contents,
0716                    const DebugStringOptions& options,
0717                    bool include_opening_clause) const;
0718 
0719   // Walks up the descriptor tree to generate the source location path
0720   // to this descriptor from the file root.
0721   void GetLocationPath(std::vector<int>* output) const;
0722 
0723   // visibility declared on the message
0724   SymbolVisibility visibility_keyword() const;
0725 
0726   // True if this is a placeholder for an unknown type.
0727   bool is_placeholder_ : 1;
0728   // True if this is a placeholder and the type name wasn't fully-qualified.
0729   bool is_unqualified_placeholder_ : 1;
0730   // Well known type.  Stored like this to conserve space.
0731   uint8_t well_known_type_ : 5;
0732   // bitfield representation of SymbolVisibility, which only requires 2 bits
0733   uint8_t visibility_ : 2;
0734 
0735   // This points to the last field _number_ that is part of the sequence
0736   // starting at 1, where
0737   //     `desc->field(i)->number() == i + 1`
0738   // A value of `0` means no field matches. That is, there are no fields or the
0739   // first field is not field `1`.
0740   // Uses 16-bit to avoid extra padding. Unlikely to have more than 2^16
0741   // sequentially numbered fields in a message.
0742   uint16_t sequential_field_limit_;
0743 
0744   int field_count_;
0745 
0746   internal::DescriptorNames all_names_;
0747   const FileDescriptor* file_;
0748   const Descriptor* containing_type_;
0749   const MessageOptions* options_;
0750   const FeatureSet* proto_features_;
0751   const FeatureSet* merged_features_;
0752 
0753   // These arrays are separated from their sizes to minimize padding on 64-bit.
0754   FieldDescriptor* fields_;
0755   OneofDescriptor* oneof_decls_;
0756   Descriptor* nested_types_;
0757   EnumDescriptor* enum_types_;
0758   ExtensionRange* extension_ranges_;
0759   FieldDescriptor* extensions_;
0760   ReservedRange* reserved_ranges_;
0761   const std::string** reserved_names_;
0762 
0763   int oneof_decl_count_;
0764   int real_oneof_decl_count_;
0765   int nested_type_count_;
0766   int enum_type_count_;
0767   int extension_range_count_;
0768   int extension_count_;
0769   int reserved_range_count_;
0770   int reserved_name_count_;
0771 
0772   // IMPORTANT:  If you add a new field, make sure to search for all instances
0773   // of Allocate<Descriptor>() and AllocateArray<Descriptor>() in descriptor.cc
0774   // and update them to initialize the field.
0775 
0776   // Must be constructed using DescriptorPool.
0777   Descriptor();
0778   friend class DescriptorBuilder;
0779   friend class DescriptorPool;
0780   friend class EnumDescriptor;
0781   friend class FieldDescriptor;
0782   friend class FileDescriptorTables;
0783   friend class OneofDescriptor;
0784   friend class MethodDescriptor;
0785   friend class FileDescriptor;
0786 };
0787 
0788 PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(Descriptor, 160);
0789 
0790 // Describes a single field of a message.  To get the descriptor for a given
0791 // field, first get the Descriptor for the message in which it is defined,
0792 // then call Descriptor::FindFieldByName().  To get a FieldDescriptor for
0793 // an extension, do one of the following:
0794 // - Get the Descriptor or FileDescriptor for its containing scope, then
0795 //   call Descriptor::FindExtensionByName() or
0796 //   FileDescriptor::FindExtensionByName().
0797 // - Given a DescriptorPool, call DescriptorPool::FindExtensionByNumber() or
0798 //   DescriptorPool::FindExtensionByPrintableName().
0799 // Use DescriptorPool to construct your own descriptors.
0800 class PROTOBUF_EXPORT FieldDescriptor : private internal::SymbolBase,
0801                                         public internal::FieldDescriptorLite {
0802  public:
0803   typedef FieldDescriptorProto Proto;
0804 
0805 #ifndef SWIG
0806   FieldDescriptor(const FieldDescriptor&) = delete;
0807   FieldDescriptor& operator=(const FieldDescriptor&) = delete;
0808 #endif
0809 
0810   // Identifies a field type.  0 is reserved for errors.  The order is weird
0811   // for historical reasons.  Types 12 and up are new in proto2.
0812   // Inherited from FieldDescriptorLite:
0813   // enum Type {
0814   //   TYPE_DOUBLE = 1,    // double, exactly eight bytes on the wire.
0815   //   TYPE_FLOAT = 2,     // float, exactly four bytes on the wire.
0816   //   TYPE_INT64 = 3,     // int64, varint on the wire.  Negative numbers
0817   //                       // take 10 bytes.  Use TYPE_SINT64 if negative
0818   //                       // values are likely.
0819   //   TYPE_UINT64 = 4,    // uint64, varint on the wire.
0820   //   TYPE_INT32 = 5,     // int32, varint on the wire.  Negative numbers
0821   //                       // take 10 bytes.  Use TYPE_SINT32 if negative
0822   //                       // values are likely.
0823   //   TYPE_FIXED64 = 6,   // uint64, exactly eight bytes on the wire.
0824   //   TYPE_FIXED32 = 7,   // uint32, exactly four bytes on the wire.
0825   //   TYPE_BOOL = 8,      // bool, varint on the wire.
0826   //   TYPE_STRING = 9,    // UTF-8 text.
0827   //   TYPE_GROUP = 10,    // Tag-delimited message.  Deprecated.
0828   //   TYPE_MESSAGE = 11,  // Length-delimited message.
0829 
0830   //   TYPE_BYTES = 12,     // Arbitrary byte array.
0831   //   TYPE_UINT32 = 13,    // uint32, varint on the wire
0832   //   TYPE_ENUM = 14,      // Enum, varint on the wire
0833   //   TYPE_SFIXED32 = 15,  // int32, exactly four bytes on the wire
0834   //   TYPE_SFIXED64 = 16,  // int64, exactly eight bytes on the wire
0835   //   TYPE_SINT32 = 17,    // int32, ZigZag-encoded varint on the wire
0836   //   TYPE_SINT64 = 18,    // int64, ZigZag-encoded varint on the wire
0837 
0838   //   MAX_TYPE = 18,  // Constant useful for defining lookup tables
0839   //                   // indexed by Type.
0840   // };
0841 
0842   // Specifies the C++ data type used to represent the field.  There is a
0843   // fixed mapping from Type to CppType where each Type maps to exactly one
0844   // CppType.  0 is reserved for errors.
0845   // Inherited from FieldDescriptorLite:
0846   // enum CppType {
0847   //   CPPTYPE_INT32 = 1,     // TYPE_INT32, TYPE_SINT32, TYPE_SFIXED32
0848   //   CPPTYPE_INT64 = 2,     // TYPE_INT64, TYPE_SINT64, TYPE_SFIXED64
0849   //   CPPTYPE_UINT32 = 3,    // TYPE_UINT32, TYPE_FIXED32
0850   //   CPPTYPE_UINT64 = 4,    // TYPE_UINT64, TYPE_FIXED64
0851   //   CPPTYPE_DOUBLE = 5,    // TYPE_DOUBLE
0852   //   CPPTYPE_FLOAT = 6,     // TYPE_FLOAT
0853   //   CPPTYPE_BOOL = 7,      // TYPE_BOOL
0854   //   CPPTYPE_ENUM = 8,      // TYPE_ENUM
0855   //   CPPTYPE_STRING = 9,    // TYPE_STRING, TYPE_BYTES
0856   //   CPPTYPE_MESSAGE = 10,  // TYPE_MESSAGE, TYPE_GROUP
0857 
0858   //   MAX_CPPTYPE = 10,  // Constant useful for defining lookup tables
0859   //                      // indexed by CppType.
0860   // };
0861 
0862   // Identifies whether the field is optional, required, or repeated.  0 is
0863   // reserved for errors.
0864   // Inherited from FieldDescriptorLite:
0865   // enum Label {
0866   //   LABEL_OPTIONAL = 1,  // optional
0867   //   LABEL_REQUIRED = 2,  // required
0868   //   LABEL_REPEATED = 3,  // repeated
0869 
0870   //   MAX_LABEL = 3,  // Constant useful for defining lookup tables
0871   //                   // indexed by Label.
0872   // };
0873 
0874   // Valid field numbers are positive integers up to kMaxNumber.
0875   static const int kMaxNumber = (1 << 29) - 1;
0876 
0877   // First field number reserved for the protocol buffer library implementation.
0878   // Users may not declare fields that use reserved numbers.
0879   static const int kFirstReservedNumber = 19000;
0880   // Last field number reserved for the protocol buffer library implementation.
0881   // Users may not declare fields that use reserved numbers.
0882   static const int kLastReservedNumber = 19999;
0883 
0884   // Name of this field within the message.
0885   absl::string_view name() const;
0886   // Fully-qualified name of the field.
0887   absl::string_view full_name() const;
0888   // JSON name of this field.
0889   absl::string_view json_name() const;
0890 
0891   const FileDescriptor* file() const;  // File in which this field was defined.
0892   bool is_extension() const;           // Is this an extension field?
0893   int number() const;                  // Declared tag number.
0894 
0895   // Same as name() except converted to lower-case.  This (and especially the
0896   // FindFieldByLowercaseName() method) can be useful when parsing formats
0897   // which prefer to use lowercase naming style.  (Although, technically
0898   // field names should be lowercased anyway according to the protobuf style
0899   // guide, so this only makes a difference when dealing with old .proto files
0900   // which do not follow the guide.)
0901   absl::string_view lowercase_name() const;
0902 
0903   // Same as name() except converted to camel-case.  In this conversion, any
0904   // time an underscore appears in the name, it is removed and the next
0905   // letter is capitalized.  Furthermore, the first letter of the name is
0906   // lower-cased.  Examples:
0907   //   FooBar -> fooBar
0908   //   foo_bar -> fooBar
0909   //   fooBar -> fooBar
0910   // This (and especially the FindFieldByCamelcaseName() method) can be useful
0911   // when parsing formats which prefer to use camel-case naming style.
0912   absl::string_view camelcase_name() const;
0913 
0914   Type type() const;  // Declared type of this field.
0915   // Name of the declared type.
0916   absl::string_view type_name() const;
0917   CppType cpp_type() const;  // C++ type of this field.
0918   // Name of the C++ type.
0919   absl::string_view cpp_type_name() const;
0920 
0921   // This should never be called directly. Use is_required() and is_repeated()
0922   // helper methods instead.
0923   ABSL_DEPRECATED("Use is_required() or is_repeated() instead.")
0924   Label label() const;  // optional/required/repeated
0925 
0926 #ifndef SWIG
0927   CppStringType cpp_string_type() const;  // The C++ string type of this field.
0928 #endif
0929 
0930   // Whether or not the field is required. For proto2 required fields and
0931   // Editions LEGACY_REQUIRED fields.
0932   bool is_required() const;
0933   bool is_repeated() const;  // Whether or not the field is repeated/map field.
0934 
0935   ABSL_DEPRECATE_AND_INLINE()
0936   bool is_optional() const;  // Use !is_required() && !is_repeated() instead.
0937 
0938   bool is_packable() const;  // shorthand for is_repeated() &&
0939                              //               IsTypePackable(type())
0940   bool is_map() const;       // shorthand for type() == TYPE_MESSAGE &&
0941                              // message_type()->options().map_entry()
0942 
0943   // Whether or not this field is packable and packed.  In proto2, packable
0944   // fields must have `packed = true` specified.  In proto3, all packable fields
0945   // are packed by default unless `packed = false` is specified.
0946   bool is_packed() const;
0947 
0948   // Returns true if this field tracks presence, ie. does the field
0949   // distinguish between "unset" and "present with default value."
0950   // This includes required, optional, and oneof fields. It excludes maps,
0951   // repeated fields, and singular proto3 fields without "optional".
0952   //
0953   // For fields where has_presence() == true, the return value of
0954   // Reflection::HasField() is semantically meaningful.
0955   bool has_presence() const;
0956 
0957   // Returns true if this TYPE_STRING-typed field requires UTF-8 validation on
0958   // parse.
0959   bool requires_utf8_validation() const;
0960 
0961   // Determines if the given enum field is treated as closed based on legacy
0962   // non-conformant behavior.
0963   //
0964   // Conformant behavior determines closedness based on the enum and
0965   // can be queried using EnumDescriptor::is_closed().
0966   //
0967   // Some runtimes currently have a quirk where non-closed enums are
0968   // treated as closed when used as the type of fields defined in a
0969   // `syntax = proto2;` file. This quirk is not present in all runtimes; as of
0970   // writing, we know that:
0971   //
0972   // - C++, Java, and C++-based Python share this quirk.
0973   // - UPB and UPB-based Python do not.
0974   // - PHP and Ruby treat all enums as open regardless of declaration.
0975   //
0976   // Care should be taken when using this function to respect the target
0977   // runtime's enum handling quirks.
0978   bool legacy_enum_field_treated_as_closed() const;
0979 
0980   // Index of this field within the message's field array, or the file or
0981   // extension scope's extensions array.
0982   int index() const;
0983 
0984   // Does this field have an explicitly-declared default value?
0985   bool has_default_value() const;
0986 
0987   // Whether the user has specified the json_name field option in the .proto
0988   // file.
0989   bool has_json_name() const;
0990 
0991   // Get the field default value if cpp_type() == CPPTYPE_INT32.  If no
0992   // explicit default was defined, the default is 0.
0993   int32_t default_value_int32_t() const;
0994   int32_t default_value_int32() const { return default_value_int32_t(); }
0995   // Get the field default value if cpp_type() == CPPTYPE_INT64.  If no
0996   // explicit default was defined, the default is 0.
0997   int64_t default_value_int64_t() const;
0998   int64_t default_value_int64() const { return default_value_int64_t(); }
0999   // Get the field default value if cpp_type() == CPPTYPE_UINT32.  If no
1000   // explicit default was defined, the default is 0.
1001   uint32_t default_value_uint32_t() const;
1002   uint32_t default_value_uint32() const { return default_value_uint32_t(); }
1003   // Get the field default value if cpp_type() == CPPTYPE_UINT64.  If no
1004   // explicit default was defined, the default is 0.
1005   uint64_t default_value_uint64_t() const;
1006   uint64_t default_value_uint64() const { return default_value_uint64_t(); }
1007   // Get the field default value if cpp_type() == CPPTYPE_FLOAT.  If no
1008   // explicit default was defined, the default is 0.0.
1009   float default_value_float() const;
1010   // Get the field default value if cpp_type() == CPPTYPE_DOUBLE.  If no
1011   // explicit default was defined, the default is 0.0.
1012   double default_value_double() const;
1013   // Get the field default value if cpp_type() == CPPTYPE_BOOL.  If no
1014   // explicit default was defined, the default is false.
1015   bool default_value_bool() const;
1016   // Get the field default value if cpp_type() == CPPTYPE_ENUM.  If no
1017   // explicit default was defined, the default is the first value defined
1018   // in the enum type (all enum types are required to have at least one value).
1019   // This never returns nullptr.
1020   const EnumValueDescriptor* default_value_enum() const;
1021   // Get the field default value if cpp_type() == CPPTYPE_STRING.  If no
1022   // explicit default was defined, the default is the empty string.
1023   absl::string_view default_value_string() const;
1024 
1025   // The Descriptor for the message of which this is a field.  For extensions,
1026   // this is the extended type.  Never nullptr.
1027   const Descriptor* containing_type() const;
1028 
1029   // If the field is a member of a oneof, this is the one, otherwise this is
1030   // nullptr.
1031   const OneofDescriptor* containing_oneof() const;
1032 
1033   // If the field is a member of a non-synthetic oneof, returns the descriptor
1034   // for the oneof, otherwise returns nullptr.
1035   const OneofDescriptor* real_containing_oneof() const;
1036 
1037   // If the field is a member of a oneof, returns the index in that oneof.
1038   int index_in_oneof() const;
1039 
1040   // An extension may be declared within the scope of another message.  If this
1041   // field is an extension (is_extension() is true), then extension_scope()
1042   // returns that message, or nullptr if the extension was declared at global
1043   // scope.  If this is not an extension, extension_scope() is undefined (may
1044   // assert-fail).
1045   const Descriptor* extension_scope() const;
1046 
1047   // If type is TYPE_MESSAGE or TYPE_GROUP, returns a descriptor for the
1048   // message or the group type.  Otherwise, returns null.
1049   const Descriptor* message_type() const;
1050   // If type is TYPE_ENUM, returns a descriptor for the enum.  Otherwise,
1051   // returns null.
1052   const EnumDescriptor* enum_type() const;
1053 
1054   // Get the FieldOptions for this field.  This includes things listed in
1055   // square brackets after the field definition.  E.g., the field:
1056   //   optional string text = 1 [ctype=CORD];
1057   // has the "ctype" option set.  Allowed options are defined by FieldOptions in
1058   // descriptor.proto, and any available extensions of that message.
1059   const FieldOptions& options() const;
1060 
1061   // See Descriptor::CopyTo().
1062   void CopyTo(FieldDescriptorProto* proto) const;
1063 
1064   // See Descriptor::DebugString().
1065   std::string DebugString() const;
1066 
1067   // See Descriptor::DebugStringWithOptions().
1068   std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1069 
1070   // Allows formatting with absl and gtest.
1071   template <typename Sink>
1072   friend void AbslStringify(Sink& sink, const FieldDescriptor& d) {
1073     absl::Format(&sink, "%s", d.DebugString());
1074   }
1075 
1076   // Helper method to get the CppType for a particular Type.
1077   static CppType TypeToCppType(Type type);
1078 
1079   // Helper method to get the name of a Type.
1080   static absl::string_view TypeName(Type type);
1081 
1082   // Helper method to get the name of a CppType.
1083   static absl::string_view CppTypeName(CppType cpp_type);
1084 
1085   // Return true iff [packed = true] is valid for fields of this type.
1086   static inline bool IsTypePackable(Type field_type);
1087 
1088   // Returns full_name() except if the field is a MessageSet extension,
1089   // in which case it returns the full_name() of the containing message type
1090   // for backwards compatibility with proto1.
1091   //
1092   // A MessageSet extension is defined as an optional message extension
1093   // whose containing type has the message_set_wire_format option set.
1094   // This should be true of extensions of google.protobuf.bridge.MessageSet;
1095   // by convention, such extensions are named "message_set_extension".
1096   //
1097   // The opposite operation (looking up an extension's FieldDescriptor given
1098   // its printable name) can be accomplished with
1099   //     message->file()->pool()->FindExtensionByPrintableName(message, name)
1100   // where the extension extends "message".
1101   absl::string_view PrintableNameForExtension() const;
1102 
1103   // Source Location ---------------------------------------------------
1104 
1105   // Updates |*out_location| to the source location of the complete
1106   // extent of this field declaration.  Returns false and leaves
1107   // |*out_location| unchanged iff location information was not available.
1108   bool GetSourceLocation(SourceLocation* out_location) const;
1109 
1110  private:
1111   friend class Symbol;
1112   typedef FieldOptions OptionsType;
1113 
1114   // Allows access to GetLocationPath for annotations.
1115   friend class io::Printer;
1116   friend class compiler::cpp::Formatter;
1117   friend class Reflection;
1118   friend class FieldDescriptorLegacy;
1119   friend const std::string& internal::DefaultValueStringAsString(
1120       const FieldDescriptor* field);
1121 
1122   // Returns the original ctype specified in the .proto file.  This should not
1123   // be relied on, as it no longer uniquely determines behavior.  The
1124   // cpp_string_type() method should be used instead, which takes feature
1125   // settings into account.  Needed by CppGenerator for validation only.
1126   friend class compiler::cpp::CppGenerator;
1127   int legacy_proto_ctype() const { return legacy_proto_ctype_; }
1128   bool has_legacy_proto_ctype() const;
1129 
1130   // Returns true if this field was syntactically written with "optional" in the
1131   // .proto file. Excludes singular proto3 fields that do not have a label.
1132   ABSL_DEPRECATED("Use has_presence() instead.")
1133   bool has_optional_keyword() const;
1134 
1135   // Get the merged features that apply to this field.  These are specified in
1136   // the .proto file through the feature options in the message definition.
1137   // Allowed features are defined by Features in descriptor.proto, along with
1138   // any backend-specific extensions to it.
1139   const FeatureSet& features() const { return *merged_features_; }
1140   friend class internal::InternalFeatureHelper;
1141 
1142   // Fill the json_name field of FieldDescriptorProto.
1143   void CopyJsonNameTo(FieldDescriptorProto* proto) const;
1144 
1145   // See Descriptor::DebugString().
1146   void DebugString(int depth, std::string* contents,
1147                    const DebugStringOptions& options) const;
1148 
1149   // formats the default value appropriately and returns it as a string.
1150   // Must have a default value to call this. If quote_string_type is true, then
1151   // types of CPPTYPE_STRING will be surrounded by quotes and CEscaped.
1152   std::string DefaultValueAsString(bool quote_string_type) const;
1153 
1154   // Helper function that returns the field type name for DebugString.
1155   std::string FieldTypeNameDebugString() const;
1156 
1157   // Walks up the descriptor tree to generate the source location path
1158   // to this descriptor from the file root.
1159   void GetLocationPath(std::vector<int>* output) const;
1160 
1161   // Returns true if this is a map message type.
1162   bool is_map_message_type() const;
1163 
1164   CppStringType CalculateCppStringType() const;
1165 
1166   bool has_default_value_ : 1;
1167   bool proto3_optional_ : 1;
1168   // Whether the user has specified the json_name field option in the .proto
1169   // file.
1170   bool has_json_name_ : 1;
1171   bool is_extension_ : 1;
1172   bool is_oneof_ : 1;
1173   bool is_repeated_ : 1;  // Redundant with label_, but it is queried a lot.
1174 
1175   // Actually a `Label` but stored as uint8_t to save space.
1176   uint8_t label_ : 2;
1177 
1178   // Actually a `Type`, but stored as uint8_t to save space.
1179   uint8_t type_;
1180 
1181   // Actually a `CppStringType`, but stored as uint8_t to save space.
1182   // We cache it because it's expensive to calculate.
1183   uint8_t cpp_string_type_ : 3;
1184 
1185   // Can be calculated from containing_oneof(), but we cache it for performance.
1186   // Located here for bitpacking.
1187   bool in_real_oneof_ : 1;
1188 
1189   // We could calculate as `message_type()->options().map_entry()`, but that is
1190   // way more expensive and can potentially force load extra lazy files.
1191   bool is_map_ : 1;
1192 
1193   // Actually an optional `CType`, but stored as uint8_t to save space.  This
1194   // contains the original ctype option specified in the .proto file.
1195   uint8_t legacy_proto_ctype_ : 2;
1196 
1197   // Sadly, `number_` located here to reduce padding. Unrelated to all_names_
1198   // and its indices above.
1199   int number_;
1200   internal::DescriptorNames all_names_;
1201   const FileDescriptor* file_;
1202 
1203   // The once_flag is followed by a NUL terminated string for the type name and
1204   // enum default value (or empty string if no default enum).
1205   absl::once_flag* type_once_;
1206   static void TypeOnceInit(const FieldDescriptor* to_init);
1207   void InternalTypeOnceInit() const;
1208   const Descriptor* containing_type_;
1209   union {
1210     const OneofDescriptor* containing_oneof;
1211     const Descriptor* extension_scope;
1212   } scope_;
1213   union {
1214     mutable const Descriptor* message_type;
1215     mutable const EnumDescriptor* enum_type;
1216   } type_descriptor_;
1217   const FieldOptions* options_;
1218   const FeatureSet* proto_features_;
1219   const FeatureSet* merged_features_;
1220   // IMPORTANT:  If you add a new field, make sure to search for all instances
1221   // of Allocate<FieldDescriptor>() and AllocateArray<FieldDescriptor>() in
1222   // descriptor.cc and update them to initialize the field.
1223 
1224   union {
1225     int32_t default_value_int32_t_;
1226     int64_t default_value_int64_t_;
1227     uint32_t default_value_uint32_t_;
1228     uint64_t default_value_uint64_t_;
1229     float default_value_float_;
1230     double default_value_double_;
1231     bool default_value_bool_;
1232 
1233     mutable const EnumValueDescriptor* default_value_enum_;
1234     const std::string* default_value_string_;
1235     mutable std::atomic<const Message*> default_generated_instance_;
1236   };
1237 
1238   static const CppType kTypeToCppTypeMap[MAX_TYPE + 1];
1239 
1240   static const char* const kTypeToName[MAX_TYPE + 1];
1241 
1242   static const char* const kCppTypeToName[MAX_CPPTYPE + 1];
1243 
1244   static const char* const kLabelToName[MAX_LABEL + 1];
1245 
1246   // Must be constructed using DescriptorPool.
1247   FieldDescriptor();
1248   friend class DescriptorBuilder;
1249   friend class FileDescriptor;
1250   friend class Descriptor;
1251   friend class OneofDescriptor;
1252 };
1253 
1254 PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(FieldDescriptor, 88);
1255 
1256 // Describes a oneof defined in a message type.
1257 class PROTOBUF_EXPORT OneofDescriptor : private internal::SymbolBase {
1258  public:
1259   typedef OneofDescriptorProto Proto;
1260 
1261 #ifndef SWIG
1262   OneofDescriptor(const OneofDescriptor&) = delete;
1263   OneofDescriptor& operator=(const OneofDescriptor&) = delete;
1264 #endif
1265 
1266   // Name of this oneof.
1267   absl::string_view name() const;
1268   // Fully-qualified name of the oneof.
1269   absl::string_view full_name() const;
1270 
1271   // Index of this oneof within the message's oneof array.
1272   int index() const;
1273 
1274   // The .proto file in which this oneof was defined.  Never nullptr.
1275   const FileDescriptor* file() const;
1276   // The Descriptor for the message containing this oneof.
1277   const Descriptor* containing_type() const;
1278 
1279   // The number of (non-extension) fields which are members of this oneof.
1280   int field_count() const;
1281   // Get a member of this oneof, in the order in which they were declared in the
1282   // .proto file.  Does not include extensions.
1283   const FieldDescriptor* field(int index) const;
1284 
1285   const OneofOptions& options() const;
1286 
1287   // See Descriptor::CopyTo().
1288   void CopyTo(OneofDescriptorProto* proto) const;
1289 
1290   // See Descriptor::DebugString().
1291   std::string DebugString() const;
1292 
1293   // See Descriptor::DebugStringWithOptions().
1294   std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1295 
1296   // Allows formatting with absl and gtest.
1297   template <typename Sink>
1298   friend void AbslStringify(Sink& sink, const OneofDescriptor& d) {
1299     absl::Format(&sink, "%s", d.DebugString());
1300   }
1301 
1302   // Source Location ---------------------------------------------------
1303 
1304   // Updates |*out_location| to the source location of the complete
1305   // extent of this oneof declaration.  Returns false and leaves
1306   // |*out_location| unchanged iff location information was not available.
1307   bool GetSourceLocation(SourceLocation* out_location) const;
1308 
1309  private:
1310   friend class Symbol;
1311   typedef OneofOptions OptionsType;
1312 
1313   // Allows access to GetLocationPath for annotations.
1314   friend class io::Printer;
1315   friend class compiler::cpp::Formatter;
1316   friend class OneofDescriptorLegacy;
1317 
1318   // Returns whether this oneof was inserted by the compiler to wrap a proto3
1319   // optional field. If this returns true, code generators should *not* emit it.
1320   bool is_synthetic() const;
1321 
1322   // Get the merged features that apply to this oneof.  These are specified in
1323   // the .proto file through the feature options in the oneof definition.
1324   // Allowed features are defined by Features in descriptor.proto, along with
1325   // any backend-specific extensions to it.
1326   const FeatureSet& features() const { return *merged_features_; }
1327   friend class internal::InternalFeatureHelper;
1328 
1329   // See Descriptor::DebugString().
1330   void DebugString(int depth, std::string* contents,
1331                    const DebugStringOptions& options) const;
1332 
1333   // Walks up the descriptor tree to generate the source location path
1334   // to this descriptor from the file root.
1335   void GetLocationPath(std::vector<int>* output) const;
1336 
1337   int field_count_;
1338 
1339   internal::DescriptorNames all_names_;
1340   const Descriptor* containing_type_;
1341   const OneofOptions* options_;
1342   const FeatureSet* proto_features_;
1343   const FeatureSet* merged_features_;
1344   const FieldDescriptor* fields_;
1345 
1346   // IMPORTANT:  If you add a new field, make sure to search for all instances
1347   // of Allocate<OneofDescriptor>() and AllocateArray<OneofDescriptor>()
1348   // in descriptor.cc and update them to initialize the field.
1349 
1350   // Must be constructed using DescriptorPool.
1351   OneofDescriptor();
1352   friend class DescriptorBuilder;
1353   friend class Descriptor;
1354   friend class FieldDescriptor;
1355   friend class Reflection;
1356 };
1357 
1358 PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(OneofDescriptor, 56);
1359 
1360 // Describes an enum type defined in a .proto file.  To get the EnumDescriptor
1361 // for a generated enum type, call TypeName_descriptor().  Use DescriptorPool
1362 // to construct your own descriptors.
1363 class PROTOBUF_EXPORT EnumDescriptor : private internal::SymbolBase {
1364  public:
1365   typedef EnumDescriptorProto Proto;
1366 
1367 #ifndef SWIG
1368   EnumDescriptor(const EnumDescriptor&) = delete;
1369   EnumDescriptor& operator=(const EnumDescriptor&) = delete;
1370 #endif
1371 
1372   // The name of this enum type in the containing scope.
1373   absl::string_view name() const;
1374 
1375   // The fully-qualified name of the enum type, scope delimited by periods.
1376   absl::string_view full_name() const;
1377 
1378   // Index of this enum within the file or containing message's enum array.
1379   int index() const;
1380 
1381   // The .proto file in which this enum type was defined.  Never nullptr.
1382   const FileDescriptor* file() const;
1383 
1384   // The number of values for this EnumDescriptor.  Guaranteed to be greater
1385   // than zero.
1386   int value_count() const;
1387   // Gets a value by index, where 0 <= index < value_count().
1388   // These are returned in the order they were defined in the .proto file, not
1389   // the enum value order. (Use `FindValueByNumber()` for enum -> value lookup).
1390   const EnumValueDescriptor* value(int index) const;
1391 
1392   // Looks up a value by name.  Returns nullptr if no such value exists.
1393   const EnumValueDescriptor* FindValueByName(absl::string_view name) const;
1394   // Looks up a value by number.  Returns nullptr if no such value exists.  If
1395   // multiple values have this number, the first one defined is returned.
1396   const EnumValueDescriptor* FindValueByNumber(int number) const;
1397 
1398   // If this enum type is nested in a message type, this is that message type.
1399   // Otherwise, nullptr.
1400   const Descriptor* containing_type() const;
1401 
1402   // Get options for this enum type.  These are specified in the .proto file by
1403   // placing lines like "option foo = 1234;" in the enum definition.  Allowed
1404   // options are defined by EnumOptions in descriptor.proto, and any available
1405   // extensions of that message.
1406   const EnumOptions& options() const;
1407 
1408   // See Descriptor::CopyTo().
1409   void CopyTo(EnumDescriptorProto* proto) const;
1410 
1411   // See Descriptor::DebugString().
1412   std::string DebugString() const;
1413 
1414   // See Descriptor::DebugStringWithOptions().
1415   std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1416 
1417   // Allows formatting with absl and gtest.
1418   template <typename Sink>
1419   friend void AbslStringify(Sink& sink, const EnumDescriptor& d) {
1420     absl::Format(&sink, "%s", d.DebugString());
1421   }
1422 
1423   // Returns true if this is a placeholder for an unknown enum. This will
1424   // only be the case if this descriptor comes from a DescriptorPool
1425   // with AllowUnknownDependencies() set.
1426   bool is_placeholder() const;
1427 
1428   // Returns true whether this is a "closed" enum, meaning that it:
1429   // - Has a fixed set of values, rather than being equivalent to an int32.
1430   // - Encountering values not in this set causes them to be treated as unknown
1431   //   fields.
1432   // - The first value (i.e., the default) may be nonzero.
1433   //
1434   // WARNING: Some runtimes currently have a quirk where non-closed enums are
1435   // treated as closed when used as the type of fields defined in a
1436   // `syntax = proto2;` file. This quirk is not present in all runtimes; as of
1437   // writing, we know that:
1438   //
1439   // - C++, Java, and C++-based Python share this quirk.
1440   // - UPB and UPB-based Python do not.
1441   // - PHP and Ruby treat all enums as open regardless of declaration.
1442   //
1443   // Care should be taken when using this function to respect the target
1444   // runtime's enum handling quirks.
1445   bool is_closed() const;
1446 
1447   // Reserved fields -------------------------------------------------
1448 
1449   // A range of reserved field numbers.
1450   struct ReservedRange {
1451     int start;  // inclusive
1452     int end;    // inclusive
1453   };
1454 
1455   // The number of reserved ranges in this message type.
1456   int reserved_range_count() const;
1457   // Gets an reserved range by index, where 0 <= index <
1458   // reserved_range_count(). These are returned in the order they were defined
1459   // in the .proto file.
1460   const EnumDescriptor::ReservedRange* reserved_range(int index) const;
1461 
1462   // Returns true if the number is in one of the reserved ranges.
1463   bool IsReservedNumber(int number) const;
1464 
1465   // Returns nullptr if no reserved range contains the given number.
1466   const EnumDescriptor::ReservedRange* FindReservedRangeContainingNumber(
1467       int number) const;
1468 
1469   // The number of reserved field names in this message type.
1470   int reserved_name_count() const;
1471 
1472   // Gets a reserved name by index, where 0 <= index < reserved_name_count().
1473   absl::string_view reserved_name(int index) const;
1474 
1475   // Returns true if the field name is reserved.
1476   bool IsReservedName(absl::string_view name) const;
1477 
1478   // Source Location ---------------------------------------------------
1479 
1480   // Updates |*out_location| to the source location of the complete
1481   // extent of this enum declaration.  Returns false and leaves
1482   // |*out_location| unchanged iff location information was not available.
1483   bool GetSourceLocation(SourceLocation* out_location) const;
1484 
1485  private:
1486   friend class Symbol;
1487   friend bool internal::IsEnumFullySequential(const EnumDescriptor* enum_desc);
1488   typedef EnumOptions OptionsType;
1489 
1490   // Allows access to GetLocationPath for annotations.
1491   friend class io::Printer;
1492   friend class compiler::cpp::Formatter;
1493 
1494   // Allow access to FindValueByNumberCreatingIfUnknown.
1495   friend class descriptor_unittest::DescriptorTest;
1496 
1497   // Get the merged features that apply to this enum type.  These are specified
1498   // in the .proto file through the feature options in the message definition.
1499   // Allowed features are defined by Features in descriptor.proto, along with
1500   // any backend-specific extensions to it.
1501   const FeatureSet& features() const { return *merged_features_; }
1502   friend class internal::InternalFeatureHelper;
1503 
1504   // Looks up a value by number.  If the value does not exist, dynamically
1505   // creates a new EnumValueDescriptor for that value, assuming that it was
1506   // unknown. If a new descriptor is created, this is done in a thread-safe way,
1507   // and future calls will return the same value descriptor pointer.
1508   //
1509   // This is private but is used by Reflection (which is friended below) to
1510   // return a valid EnumValueDescriptor from GetEnum() when this feature is
1511   // enabled.
1512   const EnumValueDescriptor* FindValueByNumberCreatingIfUnknown(
1513       int number) const;
1514 
1515   // See Descriptor::DebugString().
1516   void DebugString(int depth, std::string* contents,
1517                    const DebugStringOptions& options) const;
1518 
1519   // Walks up the descriptor tree to generate the source location path
1520   // to this descriptor from the file root.
1521   void GetLocationPath(std::vector<int>* output) const;
1522 
1523   // visibility declared on the enum
1524   SymbolVisibility visibility_keyword() const;
1525 
1526   // True if this is a placeholder for an unknown type.
1527   bool is_placeholder_ : 1;
1528   // True if this is a placeholder and the type name wasn't fully-qualified.
1529   bool is_unqualified_placeholder_ : 1;
1530 
1531   // bitfield representation of SymbolVisibility, which only requires 2 bits
1532   uint8_t visibility_ : 2;
1533 
1534   // This points to the last value _index_ that is part of the sequence starting
1535   // with the first label, where
1536   //   `enum->value(i)->number() == enum->value(0)->number() + i`
1537   // We measure relative to the first label to adapt to enum labels starting at
1538   // 0 or 1.
1539   // Uses 16-bit to avoid extra padding. Unlikely to have more than 2^15
1540   // sequentially numbered labels in an enum.
1541   int16_t sequential_value_limit_;
1542 
1543   int value_count_;
1544 
1545   internal::DescriptorNames all_names_;
1546   const FileDescriptor* file_;
1547   const Descriptor* containing_type_;
1548   const EnumOptions* options_;
1549   const FeatureSet* proto_features_;
1550   const FeatureSet* merged_features_;
1551   EnumValueDescriptor* values_;
1552 
1553   int reserved_range_count_;
1554   int reserved_name_count_;
1555   EnumDescriptor::ReservedRange* reserved_ranges_;
1556   const std::string** reserved_names_;
1557 
1558   // IMPORTANT:  If you add a new field, make sure to search for all instances
1559   // of Allocate<EnumDescriptor>() and AllocateArray<EnumDescriptor>() in
1560   // descriptor.cc and update them to initialize the field.
1561 
1562   // Must be constructed using DescriptorPool.
1563   EnumDescriptor();
1564   friend class DescriptorBuilder;
1565   friend class Descriptor;
1566   friend class FieldDescriptor;
1567   friend class FileDescriptorTables;
1568   friend class EnumValueDescriptor;
1569   friend class FileDescriptor;
1570   friend class DescriptorPool;
1571   friend class Reflection;
1572 };
1573 
1574 PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(EnumDescriptor, 88);
1575 
1576 // Describes an individual enum constant of a particular type.  To get the
1577 // EnumValueDescriptor for a given enum value, first get the EnumDescriptor
1578 // for its type, then use EnumDescriptor::FindValueByName() or
1579 // EnumDescriptor::FindValueByNumber().  Use DescriptorPool to construct
1580 // your own descriptors.
1581 class PROTOBUF_EXPORT EnumValueDescriptor : private internal::SymbolBaseN<0>,
1582                                             private internal::SymbolBaseN<1> {
1583  public:
1584   typedef EnumValueDescriptorProto Proto;
1585 
1586 #ifndef SWIG
1587   EnumValueDescriptor(const EnumValueDescriptor&) = delete;
1588   EnumValueDescriptor& operator=(const EnumValueDescriptor&) = delete;
1589 #endif
1590 
1591   absl::string_view name() const;   // Name of this enum constant.
1592   int index() const;                // Index within the enums's Descriptor.
1593   int number() const;               // Numeric value of this enum constant.
1594 
1595   // The full_name of an enum value is a sibling symbol of the enum type.
1596   // e.g. the full name of FieldDescriptorProto::TYPE_INT32 is actually
1597   // "google.protobuf.FieldDescriptorProto.TYPE_INT32", NOT
1598   // "google.protobuf.FieldDescriptorProto.Type.TYPE_INT32".  This is to conform
1599   // with C++ scoping rules for enums.
1600   absl::string_view full_name() const;
1601 
1602   // The .proto file in which this value was defined.  Never nullptr.
1603   const FileDescriptor* file() const;
1604   // The type of this value.  Never nullptr.
1605   const EnumDescriptor* type() const;
1606 
1607   // Get options for this enum value.  These are specified in the .proto file by
1608   // adding text like "[foo = 1234]" after an enum value definition.  Allowed
1609   // options are defined by EnumValueOptions in descriptor.proto, and any
1610   // available extensions of that message.
1611   const EnumValueOptions& options() const;
1612 
1613   // See Descriptor::CopyTo().
1614   void CopyTo(EnumValueDescriptorProto* proto) const;
1615 
1616   // See Descriptor::DebugString().
1617   std::string DebugString() const;
1618 
1619   // See Descriptor::DebugStringWithOptions().
1620   std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1621 
1622   // Allows formatting with absl and gtest.
1623   template <typename Sink>
1624   friend void AbslStringify(Sink& sink, const EnumValueDescriptor& d) {
1625     absl::Format(&sink, "%s", d.DebugString());
1626   }
1627 
1628   // Source Location ---------------------------------------------------
1629 
1630   // Updates |*out_location| to the source location of the complete
1631   // extent of this enum value declaration.  Returns false and leaves
1632   // |*out_location| unchanged iff location information was not available.
1633   bool GetSourceLocation(SourceLocation* out_location) const;
1634 
1635  private:
1636   friend class Symbol;
1637   typedef EnumValueOptions OptionsType;
1638 
1639   // Allows access to GetLocationPath for annotations.
1640   friend class io::Printer;
1641   friend class compiler::cpp::Formatter;
1642   friend const std::string& internal::NameOfEnumAsString(
1643       const EnumValueDescriptor* descriptor);
1644 
1645   // Get the merged features that apply to this enum value.  These are specified
1646   // in the .proto file through the feature options in the message definition.
1647   // Allowed features are defined by Features in descriptor.proto, along with
1648   // any backend-specific extensions to it.
1649   const FeatureSet& features() const { return *merged_features_; }
1650   friend class internal::InternalFeatureHelper;
1651 
1652   // See Descriptor::DebugString().
1653   void DebugString(int depth, std::string* contents,
1654                    const DebugStringOptions& options) const;
1655 
1656   // Walks up the descriptor tree to generate the source location path
1657   // to this descriptor from the file root.
1658   void GetLocationPath(std::vector<int>* output) const;
1659 
1660   int number_;
1661   // We keep the old-style std::string payload to support `NameOfEnumAsString`
1662   // Once we start migrating Enum_Name functions to string_view we can switch
1663   // this too.
1664   const std::string* all_names_;
1665   const EnumDescriptor* type_;
1666   const EnumValueOptions* options_;
1667   const FeatureSet* proto_features_;
1668   const FeatureSet* merged_features_;
1669   // IMPORTANT:  If you add a new field, make sure to search for all instances
1670   // of Allocate<EnumValueDescriptor>() and AllocateArray<EnumValueDescriptor>()
1671   // in descriptor.cc and update them to initialize the field.
1672 
1673   // Must be constructed using DescriptorPool.
1674   EnumValueDescriptor();
1675   friend class DescriptorBuilder;
1676   friend class EnumDescriptor;
1677   friend class DescriptorPool;
1678   friend class FileDescriptorTables;
1679   friend class Reflection;
1680 };
1681 
1682 PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(EnumValueDescriptor, 48);
1683 
1684 // Describes an RPC service. Use DescriptorPool to construct your own
1685 // descriptors.
1686 class PROTOBUF_EXPORT ServiceDescriptor : private internal::SymbolBase {
1687  public:
1688   typedef ServiceDescriptorProto Proto;
1689 
1690 #ifndef SWIG
1691   ServiceDescriptor(const ServiceDescriptor&) = delete;
1692   ServiceDescriptor& operator=(const ServiceDescriptor&) = delete;
1693 #endif
1694 
1695   // The name of the service, not including its containing scope.
1696   absl::string_view name() const;
1697   // The fully-qualified name of the service, scope delimited by periods.
1698   absl::string_view full_name() const;
1699   // Index of this service within the file's services array.
1700   int index() const;
1701 
1702   // The .proto file in which this service was defined.  Never nullptr.
1703   const FileDescriptor* file() const;
1704 
1705   // Get options for this service type.  These are specified in the .proto file
1706   // by placing lines like "option foo = 1234;" in the service definition.
1707   // Allowed options are defined by ServiceOptions in descriptor.proto, and any
1708   // available extensions of that message.
1709   const ServiceOptions& options() const;
1710 
1711   // The number of methods this service defines.
1712   int method_count() const;
1713   // Gets a MethodDescriptor by index, where 0 <= index < method_count().
1714   // These are returned in the order they were defined in the .proto file.
1715   const MethodDescriptor* method(int index) const;
1716 
1717   // Look up a MethodDescriptor by name.
1718   const MethodDescriptor* FindMethodByName(absl::string_view name) const;
1719 
1720   // See Descriptor::CopyTo().
1721   void CopyTo(ServiceDescriptorProto* proto) const;
1722 
1723   // See Descriptor::DebugString().
1724   std::string DebugString() const;
1725 
1726   // See Descriptor::DebugStringWithOptions().
1727   std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1728 
1729   // Allows formatting with absl and gtest.
1730   template <typename Sink>
1731   friend void AbslStringify(Sink& sink, const ServiceDescriptor& d) {
1732     absl::Format(&sink, "%s", d.DebugString());
1733   }
1734 
1735   // Source Location ---------------------------------------------------
1736 
1737   // Updates |*out_location| to the source location of the complete
1738   // extent of this service declaration.  Returns false and leaves
1739   // |*out_location| unchanged iff location information was not available.
1740   bool GetSourceLocation(SourceLocation* out_location) const;
1741 
1742  private:
1743   friend class Symbol;
1744   typedef ServiceOptions OptionsType;
1745 
1746   // Allows access to GetLocationPath for annotations.
1747   friend class io::Printer;
1748   friend class compiler::cpp::Formatter;
1749 
1750   // Get the merged features that apply to this service type.  These are
1751   // specified in the .proto file through the feature options in the service
1752   // definition. Allowed features are defined by Features in descriptor.proto,
1753   // along with any backend-specific extensions to it.
1754   const FeatureSet& features() const { return *merged_features_; }
1755   friend class internal::InternalFeatureHelper;
1756 
1757   // See Descriptor::DebugString().
1758   void DebugString(std::string* contents,
1759                    const DebugStringOptions& options) const;
1760 
1761   // Walks up the descriptor tree to generate the source location path
1762   // to this descriptor from the file root.
1763   void GetLocationPath(std::vector<int>* output) const;
1764 
1765   internal::DescriptorNames all_names_;
1766   const FileDescriptor* file_;
1767   const ServiceOptions* options_;
1768   const FeatureSet* proto_features_;
1769   const FeatureSet* merged_features_;
1770   MethodDescriptor* methods_;
1771   int method_count_;
1772   // IMPORTANT:  If you add a new field, make sure to search for all instances
1773   // of Allocate<ServiceDescriptor>() and AllocateArray<ServiceDescriptor>() in
1774   // descriptor.cc and update them to initialize the field.
1775 
1776   // Must be constructed using DescriptorPool.
1777   ServiceDescriptor();
1778   friend class DescriptorBuilder;
1779   friend class FileDescriptor;
1780   friend class MethodDescriptor;
1781 };
1782 
1783 PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(ServiceDescriptor, 64);
1784 
1785 // Describes an individual service method.  To obtain a MethodDescriptor given
1786 // a service, first get its ServiceDescriptor, then call
1787 // ServiceDescriptor::FindMethodByName().  Use DescriptorPool to construct your
1788 // own descriptors.
1789 class PROTOBUF_EXPORT MethodDescriptor : private internal::SymbolBase {
1790  public:
1791   typedef MethodDescriptorProto Proto;
1792 
1793 #ifndef SWIG
1794   MethodDescriptor(const MethodDescriptor&) = delete;
1795   MethodDescriptor& operator=(const MethodDescriptor&) = delete;
1796 #endif
1797 
1798   // Name of this method, not including containing scope.
1799   absl::string_view name() const;
1800   // The fully-qualified name of the method, scope delimited by periods.
1801   absl::string_view full_name() const;
1802   // Index within the service's Descriptor.
1803   int index() const;
1804 
1805   // The .proto file in which this method was defined.  Never nullptr.
1806   const FileDescriptor* file() const;
1807   // Gets the service to which this method belongs.  Never nullptr.
1808   const ServiceDescriptor* service() const;
1809 
1810   // Gets the type of protocol message which this method accepts as input.
1811   const Descriptor* input_type() const;
1812   // Gets the type of protocol message which this message produces as output.
1813   const Descriptor* output_type() const;
1814 
1815   // Gets whether the client streams multiple requests.
1816   bool client_streaming() const;
1817   // Gets whether the server streams multiple responses.
1818   bool server_streaming() const;
1819 
1820   // Get options for this method.  These are specified in the .proto file by
1821   // placing lines like "option foo = 1234;" in curly-braces after a method
1822   // declaration.  Allowed options are defined by MethodOptions in
1823   // descriptor.proto, and any available extensions of that message.
1824   const MethodOptions& options() const;
1825 
1826   // See Descriptor::CopyTo().
1827   void CopyTo(MethodDescriptorProto* proto) const;
1828 
1829   // See Descriptor::DebugString().
1830   std::string DebugString() const;
1831 
1832   // See Descriptor::DebugStringWithOptions().
1833   std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1834 
1835   // Allows formatting with absl and gtest.
1836   template <typename Sink>
1837   friend void AbslStringify(Sink& sink, const MethodDescriptor& d) {
1838     absl::Format(&sink, "%s", d.DebugString());
1839   }
1840 
1841   // Source Location ---------------------------------------------------
1842 
1843   // Updates |*out_location| to the source location of the complete
1844   // extent of this method declaration.  Returns false and leaves
1845   // |*out_location| unchanged iff location information was not available.
1846   bool GetSourceLocation(SourceLocation* out_location) const;
1847 
1848  private:
1849   friend class Symbol;
1850   typedef MethodOptions OptionsType;
1851 
1852   // Allows access to GetLocationPath for annotations.
1853   friend class io::Printer;
1854   friend class compiler::cpp::Formatter;
1855 
1856   // Get the merged features that apply to this method.  These are specified in
1857   // the .proto file through the feature options in the method definition.
1858   // Allowed features are defined by Features in descriptor.proto, along with
1859   // any backend-specific extensions to it.
1860   const FeatureSet& features() const { return *merged_features_; }
1861   friend class internal::InternalFeatureHelper;
1862 
1863   // See Descriptor::DebugString().
1864   void DebugString(int depth, std::string* contents,
1865                    const DebugStringOptions& options) const;
1866 
1867   // Walks up the descriptor tree to generate the source location path
1868   // to this descriptor from the file root.
1869   void GetLocationPath(std::vector<int>* output) const;
1870 
1871   bool client_streaming_;
1872   bool server_streaming_;
1873   internal::DescriptorNames all_names_;
1874   const ServiceDescriptor* service_;
1875   mutable internal::LazyDescriptor input_type_;
1876   mutable internal::LazyDescriptor output_type_;
1877   const MethodOptions* options_;
1878   const FeatureSet* proto_features_;
1879   const FeatureSet* merged_features_;
1880   // IMPORTANT:  If you add a new field, make sure to search for all instances
1881   // of Allocate<MethodDescriptor>() and AllocateArray<MethodDescriptor>() in
1882   // descriptor.cc and update them to initialize the field.
1883 
1884   // Must be constructed using DescriptorPool.
1885   MethodDescriptor();
1886   friend class DescriptorBuilder;
1887   friend class ServiceDescriptor;
1888 };
1889 
1890 PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(MethodDescriptor, 80);
1891 
1892 // Describes a whole .proto file.  To get the FileDescriptor for a compiled-in
1893 // file, get the descriptor for something defined in that file and call
1894 // descriptor->file().  Use DescriptorPool to construct your own descriptors.
1895 class PROTOBUF_EXPORT FileDescriptor : private internal::SymbolBase {
1896  public:
1897   typedef FileDescriptorProto Proto;
1898 
1899 #ifndef SWIG
1900   FileDescriptor(const FileDescriptor&) = delete;
1901   FileDescriptor& operator=(const FileDescriptor&) = delete;
1902 #endif
1903 
1904   // The filename, relative to the source tree.
1905   // e.g. "foo/bar/baz.proto"
1906   absl::string_view name() const;
1907 
1908   // The package, e.g. "google.protobuf.compiler".
1909   absl::string_view package() const;
1910 
1911   // The DescriptorPool in which this FileDescriptor and all its contents were
1912   // allocated.  Never nullptr.
1913   const DescriptorPool* pool() const;
1914 
1915   // The number of files imported by this one.
1916   int dependency_count() const;
1917   // Gets an imported file by index, where 0 <= index < dependency_count().
1918   // These are returned in the order they were defined in the .proto file.
1919   const FileDescriptor* dependency(int index) const;
1920 
1921   // The number of files public imported by this one.
1922   // The public dependency list is a subset of the dependency list.
1923   int public_dependency_count() const;
1924   // Gets a public imported file by index, where 0 <= index <
1925   // public_dependency_count().
1926   // These are returned in the order they were defined in the .proto file.
1927   const FileDescriptor* public_dependency(int index) const;
1928 
1929   // The number of files that are imported for weak fields.
1930   // The weak dependency list is a subset of the dependency list.
1931   int weak_dependency_count() const;
1932   // Gets a weak imported file by index, where 0 <= index <
1933   // weak_dependency_count().
1934   // These are returned in the order they were defined in the .proto file.
1935   const FileDescriptor* weak_dependency(int index) const;
1936 
1937   // The number of files that are imported for options.
1938   // The option dependency list is separate from the dependency list.
1939   int option_dependency_count() const;
1940   // Gets name of an option imported file by index, where
1941   //     0 <= index < option_dependency_count()
1942   // These are returned in the relative order they were defined in the .proto
1943   // file.
1944   absl::string_view option_dependency_name(int index) const;
1945 
1946   // Number of top-level message types defined in this file.  (This does not
1947   // include nested types.)
1948   int message_type_count() const;
1949   // Gets a top-level message type, where 0 <= index < message_type_count().
1950   // These are returned in the order they were defined in the .proto file.
1951   const Descriptor* message_type(int index) const;
1952 
1953   // Number of top-level enum types defined in this file.  (This does not
1954   // include nested types.)
1955   int enum_type_count() const;
1956   // Gets a top-level enum type, where 0 <= index < enum_type_count().
1957   // These are returned in the order they were defined in the .proto file.
1958   const EnumDescriptor* enum_type(int index) const;
1959 
1960   // Number of services defined in this file.
1961   int service_count() const;
1962   // Gets a service, where 0 <= index < service_count().
1963   // These are returned in the order they were defined in the .proto file.
1964   const ServiceDescriptor* service(int index) const;
1965 
1966   // Number of extensions defined at file scope.  (This does not include
1967   // extensions nested within message types.)
1968   int extension_count() const;
1969   // Gets an extension's descriptor, where 0 <= index < extension_count().
1970   // These are returned in the order they were defined in the .proto file.
1971   const FieldDescriptor* extension(int index) const;
1972 
1973   // Get options for this file.  These are specified in the .proto file by
1974   // placing lines like "option foo = 1234;" at the top level, outside of any
1975   // other definitions.  Allowed options are defined by FileOptions in
1976   // descriptor.proto, and any available extensions of that message.
1977   const FileOptions& options() const;
1978 
1979   // Find a top-level message type by name (not full_name).  Returns nullptr if
1980   // not found.
1981   const Descriptor* FindMessageTypeByName(absl::string_view name) const;
1982   // Find a top-level enum type by name.  Returns nullptr if not found.
1983   const EnumDescriptor* FindEnumTypeByName(absl::string_view name) const;
1984   // Find an enum value defined in any top-level enum by name.  Returns nullptr
1985   // if not found.
1986   const EnumValueDescriptor* FindEnumValueByName(absl::string_view name) const;
1987   // Find a service definition by name.  Returns nullptr if not found.
1988   const ServiceDescriptor* FindServiceByName(absl::string_view name) const;
1989   // Find a top-level extension definition by name.  Returns nullptr if not
1990   // found.
1991   const FieldDescriptor* FindExtensionByName(absl::string_view name) const;
1992   // Similar to FindExtensionByName(), but searches by lowercased-name.  See
1993   // Descriptor::FindFieldByLowercaseName().
1994   const FieldDescriptor* FindExtensionByLowercaseName(
1995       absl::string_view name) const;
1996   // Similar to FindExtensionByName(), but searches by camelcased-name.  See
1997   // Descriptor::FindFieldByCamelcaseName().
1998   const FieldDescriptor* FindExtensionByCamelcaseName(
1999       absl::string_view name) const;
2000 
2001   // See Descriptor::CopyTo().
2002   // Notes:
2003   // - This method does NOT copy source code information since it is relatively
2004   //   large and rarely needed.  See CopySourceCodeInfoTo() below.
2005   void CopyTo(FileDescriptorProto* proto) const;
2006   // Write the source code information of this FileDescriptor into the given
2007   // FileDescriptorProto.  See CopyTo() above.
2008   void CopySourceCodeInfoTo(FileDescriptorProto* proto) const;
2009   // Fill the json_name field of FieldDescriptorProto for all fields. Can only
2010   // be called after CopyTo().
2011   void CopyJsonNameTo(FileDescriptorProto* proto) const;
2012   // Fills in the file-level settings of this file (e.g. edition, package,
2013   // file options) to `proto`.
2014   void CopyHeadingTo(FileDescriptorProto* proto) const;
2015 
2016   // See Descriptor::DebugString().
2017   std::string DebugString() const;
2018 
2019   // See Descriptor::DebugStringWithOptions().
2020   std::string DebugStringWithOptions(const DebugStringOptions& options) const;
2021 
2022   // Allows formatting with absl and gtest.
2023   template <typename Sink>
2024   friend void AbslStringify(Sink& sink, const FileDescriptor& d) {
2025     absl::Format(&sink, "%s", d.DebugString());
2026   }
2027 
2028   // Returns true if this is a placeholder for an unknown file. This will
2029   // only be the case if this descriptor comes from a DescriptorPool
2030   // with AllowUnknownDependencies() set.
2031   bool is_placeholder() const;
2032 
2033   // Updates |*out_location| to the source location of the complete extent of
2034   // this file declaration (namely, the empty path).
2035   bool GetSourceLocation(SourceLocation* out_location) const;
2036 
2037   // Updates |*out_location| to the source location of the complete
2038   // extent of the declaration or declaration-part denoted by |path|.
2039   // Returns false and leaves |*out_location| unchanged iff location
2040   // information was not available.  (See SourceCodeInfo for
2041   // description of path encoding.)
2042   bool GetSourceLocation(const std::vector<int>& path,
2043                          SourceLocation* out_location) const;
2044 
2045  private:
2046   friend class Symbol;
2047   friend class FileDescriptorLegacy;
2048   typedef FileOptions OptionsType;
2049 
2050   bool is_placeholder_;
2051   // Indicates the FileDescriptor is completed building. Used to verify
2052   // that type accessor functions that can possibly build a dependent file
2053   // aren't called during the process of building the file.
2054   bool finished_building_;
2055   // This one is here to fill the padding.
2056   int extension_count_;
2057 
2058   const std::string* name_;
2059   const std::string* package_;
2060   const DescriptorPool* pool_;
2061   Edition edition_;
2062 
2063   // Returns edition of this file.  For legacy proto2/proto3 files, special
2064   // EDITION_PROTO2 and EDITION_PROTO3 values are used.
2065   Edition edition() const;
2066 
2067   // Get the merged features that apply to this file.  These are specified in
2068   // the .proto file through the feature options in the message definition.
2069   // Allowed features are defined by FeatureSet in descriptor.proto, along with
2070   // any backend-specific extensions to it.
2071   const FeatureSet& features() const { return *merged_features_; }
2072   friend class internal::InternalFeatureHelper;
2073 
2074   // dependencies_once_ contain a once_flag followed by N NUL terminated
2075   // strings. Dependencies that do not need to be loaded will be empty. ie just
2076   // {'\0'}
2077   absl::once_flag* dependencies_once_;
2078   static void DependenciesOnceInit(const FileDescriptor* to_init);
2079   void InternalDependenciesOnceInit() const;
2080 
2081   // These are arranged to minimize padding on 64-bit.
2082   int dependency_count_;
2083   int public_dependency_count_;
2084   int weak_dependency_count_;
2085   int option_dependency_count_;
2086   int message_type_count_;
2087   int enum_type_count_;
2088   int service_count_;
2089 
2090   mutable const FileDescriptor** dependencies_;
2091   int* public_dependencies_;
2092   int* weak_dependencies_;
2093   absl::string_view* option_dependencies_;
2094 
2095   Descriptor* message_types_;
2096   EnumDescriptor* enum_types_;
2097   ServiceDescriptor* services_;
2098   FieldDescriptor* extensions_;
2099   const FileOptions* options_;
2100   const FeatureSet* proto_features_;
2101   const FeatureSet* merged_features_;
2102 
2103   const FileDescriptorTables* tables_;
2104   const SourceCodeInfo* source_code_info_;
2105 
2106   // IMPORTANT:  If you add a new field, make sure to search for all instances
2107   // of Allocate<FileDescriptor>() and AllocateArray<FileDescriptor>() in
2108   // descriptor.cc and update them to initialize the field.
2109 
2110   FileDescriptor();
2111   friend class DescriptorBuilder;
2112   friend class DescriptorPool;
2113   friend class Descriptor;
2114   friend class FieldDescriptor;
2115   friend class internal::LazyDescriptor;
2116   friend class OneofDescriptor;
2117   friend class EnumDescriptor;
2118   friend class EnumValueDescriptor;
2119   friend class MethodDescriptor;
2120   friend class ServiceDescriptor;
2121 };
2122 
2123 PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(FileDescriptor, 184);
2124 
2125 #ifndef SWIG
2126 enum class ExtDeclEnforcementLevel : uint8_t {
2127   // No enforcement.
2128   kNoEnforcement = 0,
2129   // All extensions excluding descriptor.proto extensions
2130   // (go/extension-declarations#descriptor-proto)
2131   kCustomExtensions = 1,
2132   // All extensions including descriptor.proto extensions.
2133   kAllExtensions = 2,
2134 };
2135 #endif  // !SWIG
2136 
2137 // ===================================================================
2138 
2139 // Used to construct descriptors.
2140 //
2141 // Normally you won't want to build your own descriptors.  Message classes
2142 // constructed by the protocol compiler will provide them for you.  However,
2143 // if you are implementing Message on your own, or if you are writing a
2144 // program which can operate on totally arbitrary types and needs to load
2145 // them from some sort of database, you might need to.
2146 //
2147 // Since Descriptors are composed of a whole lot of cross-linked bits of
2148 // data that would be a pain to put together manually, the
2149 // DescriptorPool class is provided to make the process easier.  It can
2150 // take a FileDescriptorProto (defined in descriptor.proto), validate it,
2151 // and convert it to a set of nicely cross-linked Descriptors.
2152 //
2153 // DescriptorPool also helps with memory management.  Descriptors are
2154 // composed of many objects containing static data and pointers to each
2155 // other.  In all likelihood, when it comes time to delete this data,
2156 // you'll want to delete it all at once.  In fact, it is not uncommon to
2157 // have a whole pool of descriptors all cross-linked with each other which
2158 // you wish to delete all at once.  This class represents such a pool, and
2159 // handles the memory management for you.
2160 //
2161 // You can also search for descriptors within a DescriptorPool by name, and
2162 // extensions by number.
2163 class PROTOBUF_EXPORT DescriptorPool {
2164  public:
2165   // Create a normal, empty DescriptorPool.
2166   DescriptorPool();
2167 
2168   // Constructs a DescriptorPool that, when it can't find something among the
2169   // descriptors already in the pool, looks for it in the given
2170   // DescriptorDatabase.
2171   // Notes:
2172   // - If a DescriptorPool is constructed this way, its BuildFile*() methods
2173   //   must not be called (they will assert-fail).  The only way to populate
2174   //   the pool with descriptors is to call the Find*By*() methods.
2175   // - The Find*By*() methods may block the calling thread if the
2176   //   DescriptorDatabase blocks.  This in turn means that parsing messages
2177   //   may block if they need to look up extensions.
2178   // - The Find*By*() methods will use mutexes for thread-safety, thus making
2179   //   them slower even when they don't have to fall back to the database.
2180   //   In fact, even the Find*By*() methods of descriptor objects owned by
2181   //   this pool will be slower, since they will have to obtain locks too.
2182   // - An ErrorCollector may optionally be given to collect validation errors
2183   //   in files loaded from the database.  If not given, errors will be printed
2184   //   to ABSL_LOG(ERROR).  Remember that files are built on-demand, so this
2185   //   ErrorCollector may be called from any thread that calls one of the
2186   //   Find*By*() methods.
2187   // - The DescriptorDatabase must not be mutated during the lifetime of
2188   //   the DescriptorPool. Even if the client takes care to avoid data races,
2189   //   changes to the content of the DescriptorDatabase may not be reflected
2190   //   in subsequent lookups in the DescriptorPool.
2191   class ErrorCollector;
2192   explicit DescriptorPool(DescriptorDatabase* fallback_database,
2193                           ErrorCollector* error_collector = nullptr);
2194 
2195 #ifndef SWIG
2196   DescriptorPool(const DescriptorPool&) = delete;
2197   DescriptorPool& operator=(const DescriptorPool&) = delete;
2198 #endif
2199   ~DescriptorPool();
2200 
2201   // Get a pointer to the generated pool.  Generated protocol message classes
2202   // which are compiled into the binary will allocate their descriptors in
2203   // this pool.  Do not add your own descriptors to this pool.
2204   static const DescriptorPool* generated_pool();
2205 
2206 
2207   // Find a FileDescriptor in the pool by file name.  Returns nullptr if not
2208   // found.
2209   const FileDescriptor* FindFileByName(absl::string_view name) const;
2210 
2211   // Find the FileDescriptor in the pool which defines the given symbol.
2212   // If any of the Find*ByName() methods below would succeed, then this is
2213   // equivalent to calling that method and calling the result's file() method.
2214   // Otherwise this returns nullptr.
2215   const FileDescriptor* FindFileContainingSymbol(
2216       absl::string_view symbol_name) const;
2217 
2218   // Looking up descriptors ------------------------------------------
2219   // These find descriptors by fully-qualified name.  These will find both
2220   // top-level descriptors and nested descriptors.  They return nullptr if not
2221   // found.
2222 
2223   const Descriptor* FindMessageTypeByName(absl::string_view name) const;
2224   const FieldDescriptor* FindFieldByName(absl::string_view name) const;
2225   const FieldDescriptor* FindExtensionByName(absl::string_view name) const;
2226   const OneofDescriptor* FindOneofByName(absl::string_view name) const;
2227   const EnumDescriptor* FindEnumTypeByName(absl::string_view name) const;
2228   const EnumValueDescriptor* FindEnumValueByName(absl::string_view name) const;
2229   const ServiceDescriptor* FindServiceByName(absl::string_view name) const;
2230   const MethodDescriptor* FindMethodByName(absl::string_view name) const;
2231 
2232   // Finds an extension of the given type by number.  The extendee must be
2233   // a member of this DescriptorPool or one of its underlays.
2234   const FieldDescriptor* FindExtensionByNumber(const Descriptor* extendee,
2235                                                int number) const;
2236 
2237   // Finds an extension of the given type by its printable name.
2238   // See comments above PrintableNameForExtension() for the definition of
2239   // "printable name".  The extendee must be a member of this DescriptorPool
2240   // or one of its underlays.  Returns nullptr if there is no known message
2241   // extension with the given printable name.
2242   const FieldDescriptor* FindExtensionByPrintableName(
2243       const Descriptor* extendee, absl::string_view printable_name) const;
2244 
2245   // Finds extensions of extendee. The extensions will be appended to
2246   // out in an undefined order. Only extensions defined directly in
2247   // this DescriptorPool or one of its underlays are guaranteed to be
2248   // found: extensions defined in the fallback database might not be found
2249   // depending on the database implementation.
2250   void FindAllExtensions(const Descriptor* extendee,
2251                          std::vector<const FieldDescriptor*>* out) const;
2252 
2253   // Building descriptors --------------------------------------------
2254 
2255   // When converting a FileDescriptorProto to a FileDescriptor, various
2256   // errors might be detected in the input.  The caller may handle these
2257   // programmatically by implementing an ErrorCollector.
2258   class PROTOBUF_EXPORT ErrorCollector {
2259    public:
2260     inline ErrorCollector() {}
2261 #ifndef SWIG
2262     ErrorCollector(const ErrorCollector&) = delete;
2263     ErrorCollector& operator=(const ErrorCollector&) = delete;
2264 #endif
2265     virtual ~ErrorCollector();
2266 
2267     // These constants specify what exact part of the construct is broken.
2268     // This is useful e.g. for mapping the error back to an exact location
2269     // in a .proto file.
2270     enum ErrorLocation {
2271       NAME,           // the symbol name, or the package name for files
2272       NUMBER,         // field, extension range or extension decl number
2273       TYPE,           // field type
2274       EXTENDEE,       // field extendee
2275       DEFAULT_VALUE,  // field default value
2276       INPUT_TYPE,     // method input type
2277       OUTPUT_TYPE,    // method output type
2278       OPTION_NAME,    // name in assignment
2279       OPTION_VALUE,   // value in option assignment
2280       IMPORT,         // import error
2281       EDITIONS,       // editions-related error
2282       OTHER           // some other problem
2283     };
2284     static absl::string_view ErrorLocationName(ErrorLocation location);
2285 
2286     // Reports an error in the FileDescriptorProto. Use this function if the
2287     // problem occurred should interrupt building the FileDescriptorProto.
2288     // Provided the following arguments:
2289     // filename - File name in which the error occurred.
2290     // element_name - Full name of the erroneous element.
2291     // descriptor - Descriptor of the erroneous element.
2292     // location - One of the location constants, above.
2293     // message - Human-readable error message.
2294     virtual void RecordError(absl::string_view filename,
2295                              absl::string_view element_name,
2296                              const Message* descriptor, ErrorLocation location,
2297                              absl::string_view message)
2298         = 0;
2299 
2300     // Reports a warning in the FileDescriptorProto. Use this function if the
2301     // problem occurred should NOT interrupt building the FileDescriptorProto.
2302     // Provided the following arguments:
2303     // filename - File name in which the error occurred.
2304     // element_name - Full name of the erroneous element.
2305     // descriptor - Descriptor of the erroneous element.
2306     // location - One of the location constants, above.
2307     // message - Human-readable error message.
2308     virtual void RecordWarning([[maybe_unused]] absl::string_view filename,
2309                                [[maybe_unused]] absl::string_view element_name,
2310                                [[maybe_unused]] const Message* descriptor,
2311                                [[maybe_unused]] ErrorLocation location,
2312                                [[maybe_unused]] absl::string_view message) {
2313     }
2314 
2315   };
2316 
2317   // Convert the FileDescriptorProto to real descriptors and place them in
2318   // this DescriptorPool.  All dependencies of the file must already be in
2319   // the pool.  Returns the resulting FileDescriptor, or nullptr if there were
2320   // problems with the input (e.g. the message was invalid, or dependencies
2321   // were missing).  Details about the errors are written to ABSL_LOG(ERROR).
2322   const FileDescriptor* BuildFile(const FileDescriptorProto& proto);
2323 
2324   // Same as BuildFile() except errors are sent to the given ErrorCollector.
2325   const FileDescriptor* BuildFileCollectingErrors(
2326       const FileDescriptorProto& proto, ErrorCollector* error_collector);
2327 
2328   // By default, it is an error if a FileDescriptorProto contains references
2329   // to types or other files that are not found in the DescriptorPool (or its
2330   // backing DescriptorDatabase, if any).  If you call
2331   // AllowUnknownDependencies(), however, then unknown types and files
2332   // will be replaced by placeholder descriptors (which can be identified by
2333   // the is_placeholder() method).  This can allow you to
2334   // perform some useful operations with a .proto file even if you do not
2335   // have access to other .proto files on which it depends.  However, some
2336   // heuristics must be used to fill in the gaps in information, and these
2337   // can lead to descriptors which are inaccurate.  For example, the
2338   // DescriptorPool may be forced to guess whether an unknown type is a message
2339   // or an enum, as well as what package it resides in.  Furthermore,
2340   // placeholder types will not be discoverable via FindMessageTypeByName()
2341   // and similar methods, which could confuse some descriptor-based algorithms.
2342   // Generally, the results of this option should be handled with extreme care.
2343   void AllowUnknownDependencies() { allow_unknown_ = true; }
2344 
2345   // By default, weak imports are allowed to be missing, in which case we will
2346   // use a placeholder for the dependency and convert the field to be an Empty
2347   // message field. If you call EnforceWeakDependencies(true), however, the
2348   // DescriptorPool will report a import not found error.
2349   void EnforceWeakDependencies(bool enforce) { enforce_weak_ = enforce; }
2350 
2351   // Enforce the naming style rules. This applies the intended style rules
2352   // corresponding to the edition of the file, and was first introduced
2353   // with Edition 2024. Proto2, Proto3 and Edition 2023 are never considered
2354   // to be in violation and so are unaffected by this.
2355   //
2356   // In Edition 2024+, the 'enforce_naming_style` feature can be used to opt out
2357   // of this enforcement.
2358   void EnforceNamingStyle(bool enforce) { enforce_naming_style_ = enforce; }
2359 
2360   // Enforce symbol visibility rules.  This will enable enforcement of the
2361   // `export` and `local` keywords added in edition 2024, honoring the behavior
2362   // of the `default_symbol_visibility` feature.
2363   void EnforceSymbolVisibility(bool enforce) {
2364     enforce_symbol_visibility_ = enforce;
2365   }
2366 
2367   // By default, option imports are allowed to be missing.
2368   // If you call EnforceOptionDependencies(true), however, the DescriptorPool
2369   // will report a import not found error.
2370   void EnforceOptionDependencies(bool enforce) { enforce_option_ = enforce; }
2371 
2372   // Sets the default feature mappings used during the build. If this function
2373   // isn't called, the C++ feature set defaults are used.  If this function is
2374   // called, these defaults will be used instead.
2375   // FeatureSetDefaults includes a minimum/maximum supported edition, which will
2376   // be enforced while building proto files.
2377   absl::Status SetFeatureSetDefaults(FeatureSetDefaults spec);
2378 
2379   // Returns true if the descriptor pool resolves features for the given
2380   // extension.
2381   template <typename TypeTraitsT, uint8_t field_type, bool is_packed>
2382   bool ResolvesFeaturesFor(
2383       const google::protobuf::internal::ExtensionIdentifier<
2384           FeatureSet, TypeTraitsT, field_type, is_packed>& extension) const {
2385     return ResolvesFeaturesForImpl(extension.number());
2386   }
2387 
2388   // Toggles enforcement of extension declarations.
2389   // This enforcement is disabled by default because it requires full
2390   // descriptors with source-retention options, which are generally not
2391   // available at runtime.
2392   void EnforceExtensionDeclarations(google::protobuf::ExtDeclEnforcementLevel enforce) {
2393     enforce_extension_declarations_ = enforce;
2394   }
2395 
2396   bool ShouldEnforceDescriptorExtensionDeclarations() const {
2397     return enforce_extension_declarations_ ==
2398            ExtDeclEnforcementLevel::kAllExtensions;
2399   }
2400 
2401   bool ShouldEnforceExtensionDeclaration(const FieldDescriptor& field) const;
2402 
2403 #ifndef SWIG
2404   // Dispatch recursive builds to a callback that may stick them onto a separate
2405   // thread.  This is primarily to avoid stack overflows on untrusted inputs.
2406   // The dispatcher must always synchronously execute the provided callback.
2407   // Asynchronous execution is undefined behavior.
2408   void SetRecursiveBuildDispatcher(
2409       absl::AnyInvocable<void(absl::FunctionRef<void()>) const> dispatcher) {
2410     if (dispatcher != nullptr) {
2411       dispatcher_ = std::make_unique<
2412           absl::AnyInvocable<void(absl::FunctionRef<void()>) const>>(
2413           std::move(dispatcher));
2414     } else {
2415       dispatcher_.reset(nullptr);
2416     }
2417   }
2418 #endif  // SWIG
2419 
2420   // Internal stuff --------------------------------------------------
2421   // These methods MUST NOT be called from outside the proto2 library.
2422   // These methods may contain hidden pitfalls and may be removed in a
2423   // future library version.
2424 
2425   // Create a DescriptorPool which is overlaid on top of some other pool.
2426   // If you search for a descriptor in the overlay and it is not found, the
2427   // underlay will be searched as a backup.  If the underlay has its own
2428   // underlay, that will be searched next, and so on.  This also means that
2429   // files built in the overlay will be cross-linked with the underlay's
2430   // descriptors if necessary.  The underlay remains property of the caller;
2431   // it must remain valid for the lifetime of the newly-constructed pool.
2432   //
2433   // Example:  Say you want to parse a .proto file at runtime in order to use
2434   // its type with a DynamicMessage.  Say this .proto file has dependencies,
2435   // but you know that all the dependencies will be things that are already
2436   // compiled into the binary.  For ease of use, you'd like to load the types
2437   // right out of generated_pool() rather than have to parse redundant copies
2438   // of all these .protos and runtime.  But, you don't want to add the parsed
2439   // types directly into generated_pool(): this is not allowed, and would be
2440   // bad design anyway.  So, instead, you could use generated_pool() as an
2441   // underlay for a new DescriptorPool in which you add only the new file.
2442   //
2443   // WARNING:  Use of underlays can lead to many subtle gotchas.  Instead,
2444   //   try to formulate what you want to do in terms of DescriptorDatabases.
2445   explicit DescriptorPool(const DescriptorPool* underlay);
2446 
2447   // Called by generated classes at init time to add their descriptors to
2448   // generated_pool.  Do NOT call this in your own code!  filename must be a
2449   // permanent string (e.g. a string literal).
2450   static void InternalAddGeneratedFile(const void* encoded_file_descriptor,
2451                                        int size);
2452 
2453   // Disallow [enforce_utf8 = false] in .proto files.
2454   void DisallowEnforceUtf8() { disallow_enforce_utf8_ = true; }
2455 
2456   // Use the deprecated legacy behavior for handling JSON field name conflicts.
2457   ABSL_DEPRECATED("Deprecated treatment of field name conflicts is enabled.")
2458   void UseDeprecatedLegacyJsonFieldConflicts() {
2459     deprecated_legacy_json_field_conflicts_ = true;
2460   }
2461 
2462 
2463   // For internal use only:  Gets a non-const pointer to the generated pool.
2464   // This is called at static-initialization time only, so thread-safety is
2465   // not a concern.  If both an underlay and a fallback database are present,
2466   // the underlay takes precedence.
2467   static DescriptorPool* internal_generated_pool();
2468 
2469   // For internal use only:  Gets a non-const pointer to the generated
2470   // descriptor database.
2471   // Only used for testing.
2472   static DescriptorDatabase* internal_generated_database();
2473 
2474   // For internal use only:  Changes the behavior of BuildFile() such that it
2475   // allows the file to make reference to message types declared in other files
2476   // which it did not officially declare as dependencies.
2477   void InternalDontEnforceDependencies();
2478 
2479   // For internal use only: Enables lazy building of dependencies of a file.
2480   // Delay the building of dependencies of a file descriptor until absolutely
2481   // necessary, like when message_type() is called on a field that is defined
2482   // in that dependency's file. This will cause functional issues if a proto
2483   // or one of its dependencies has errors. Should only be enabled for the
2484   // generated_pool_ (because no descriptor build errors are guaranteed by
2485   // the compilation generation process), testing, or if a lack of descriptor
2486   // build errors can be guaranteed for a pool.
2487   void InternalSetLazilyBuildDependencies() {
2488     lazily_build_dependencies_ = true;
2489     // This needs to be set when lazily building dependencies, as it breaks
2490     // dependency checking.
2491     InternalDontEnforceDependencies();
2492   }
2493 
2494   // For internal use only.
2495   void internal_set_underlay(const DescriptorPool* underlay) {
2496     underlay_ = underlay;
2497   }
2498 
2499   // For internal (unit test) use only:  Returns true if a FileDescriptor has
2500   // been constructed for the given file, false otherwise.  Useful for testing
2501   // lazy descriptor initialization behavior.
2502   bool InternalIsFileLoaded(absl::string_view filename) const;
2503 
2504   // Add a file to to apply more strict checks to.
2505   // - unused imports will log either warnings or errors.
2506   // - deprecated features will log warnings.
2507   void AddDirectInputFile(absl::string_view file_name,
2508                           bool unused_import_is_error = false);
2509   void ClearDirectInputFiles();
2510 
2511 #if !defined(PROTOBUF_FUTURE_RENAME_ADD_UNUSED_IMPORT) && !defined(SWIG)
2512   ABSL_DEPRECATED("Use AddDirectInputFile")
2513   void AddUnusedImportTrackFile(absl::string_view file_name,
2514                                 bool is_error = false) {
2515     AddDirectInputFile(file_name, is_error);
2516   }
2517   ABSL_DEPRECATED("Use AddDirectInputFile")
2518   void ClearUnusedImportTrackFiles() { ClearDirectInputFiles(); }
2519 #endif  // !PROTOBUF_FUTURE_RENAME_ADD_UNUSED_IMPORT && !SWIG
2520 
2521 
2522  private:
2523   friend class Descriptor;
2524   friend class internal::LazyDescriptor;
2525   friend class FieldDescriptor;
2526   friend class EnumDescriptor;
2527   friend class ServiceDescriptor;
2528   friend class MethodDescriptor;
2529   friend class FileDescriptor;
2530   friend class DescriptorBuilder;
2531   friend class FileDescriptorTables;
2532   friend class google::protobuf::descriptor_unittest::DescriptorPoolMemoizationTest;
2533   friend class google::protobuf::descriptor_unittest::ValidationErrorTest;
2534   friend class ::google::protobuf::compiler::CommandLineInterface;
2535   friend class TextFormat;
2536   friend Reflection;
2537   friend class ::google::protobuf::compiler::java::MemoizeProjection;
2538 
2539   struct MemoBase {
2540     virtual ~MemoBase() = default;
2541   };
2542   template <typename T>
2543   struct MemoData : MemoBase {
2544     T value;
2545   };
2546 
2547   template <typename Desc>
2548   static const DescriptorPool* GetPool(const Desc* descriptor) {
2549     return descriptor->file()->pool();
2550   }
2551 
2552   static const DescriptorPool* GetPool(const FileDescriptor* descriptor) {
2553     return descriptor->pool();
2554   }
2555 
2556   // Memoize a projection of a descriptor. This is used to cache the results of
2557   // calling a function on a descriptor, used for expensive descriptor
2558   // calculations.
2559   template <typename Desc, typename Func>
2560   static const auto& MemoizeProjection(const Desc* descriptor, Func func) {
2561     using ResultT = std::decay_t<decltype(func(descriptor))>;
2562     auto* pool = GetPool(descriptor);
2563     static_assert(std::is_empty_v<Func> ||
2564                   std::is_function_v<std::remove_pointer_t<Func>>);
2565     // This static bool is unique per-Func, so its address can be used as a key.
2566     static bool type_key;
2567     auto key = std::pair<const void*, const void*>(descriptor, &type_key);
2568     {
2569       absl::ReaderMutexLock lock(&pool->field_memo_table_mutex_);
2570       auto it = pool->field_memo_table_->find(key);
2571       if (it != pool->field_memo_table_->end()) {
2572         return internal::DownCast<const MemoData<ResultT>&>(*it->second).value;
2573       }
2574     }
2575     auto result = std::make_unique<MemoData<ResultT>>();
2576     result->value = func(descriptor);
2577     {
2578       absl::MutexLock lock(&pool->field_memo_table_mutex_);
2579       auto insert_result =
2580           pool->field_memo_table_->insert({key, std::move(result)});
2581       auto it = insert_result.first;
2582       return internal::DownCast<const MemoData<ResultT>&>(*it->second).value;
2583     }
2584   }
2585   // Return true if the given name is a sub-symbol of any non-package
2586   // descriptor that already exists in the descriptor pool.  (The full
2587   // definition of such types is already known.)
2588   bool IsSubSymbolOfBuiltType(absl::string_view name) const;
2589 
2590   // Tries to find something in the fallback database and link in the
2591   // corresponding proto file.  Returns true if successful, in which case
2592   // the caller should search for the thing again.  These are declared
2593   // const because they are called by (semantically) const methods.
2594   // DeferredValidation stores temporary information necessary to run validation
2595   // checks that can't be done inside the database lock.  This is generally
2596   // reflective operations that also require the lock to do safely.
2597   class DeferredValidation;
2598   bool TryFindFileInFallbackDatabase(
2599       absl::string_view name, DeferredValidation& deferred_validation) const;
2600   bool TryFindSymbolInFallbackDatabase(
2601       absl::string_view name, DeferredValidation& deferred_validation) const;
2602   bool TryFindExtensionInFallbackDatabase(
2603       const Descriptor* containing_type, int field_number,
2604       DeferredValidation& deferred_validation) const;
2605 
2606   // This internal find extension method only check with its table and underlay
2607   // descriptor_pool's table. It does not check with fallback DB and no
2608   // additional proto file will be build in this method.
2609   const FieldDescriptor* InternalFindExtensionByNumberNoLock(
2610       const Descriptor* extendee, int number) const;
2611 
2612   // Like BuildFile() but called internally when the file has been loaded from
2613   // fallback_database_.  Declared const because it is called by (semantically)
2614   // const methods.
2615   const FileDescriptor* BuildFileFromDatabase(
2616       const FileDescriptorProto& proto,
2617       DeferredValidation& deferred_validation) const;
2618 
2619   // Helper for when lazily_build_dependencies_ is set, can look up a symbol
2620   // after the file's descriptor is built, and can build the file where that
2621   // symbol is defined if necessary. Will create a placeholder if the type
2622   // doesn't exist in the fallback database, or the file doesn't build
2623   // successfully.
2624   Symbol CrossLinkOnDemandHelper(absl::string_view name,
2625                                  bool expecting_enum) const;
2626 
2627   // Create a placeholder FileDescriptor of the specified name
2628   FileDescriptor* NewPlaceholderFile(absl::string_view name) const;
2629   FileDescriptor* NewPlaceholderFileWithMutexHeld(
2630       absl::string_view name, internal::FlatAllocator& alloc) const;
2631 
2632   enum PlaceholderType {
2633     PLACEHOLDER_MESSAGE,
2634     PLACEHOLDER_ENUM,
2635     PLACEHOLDER_EXTENDABLE_MESSAGE
2636   };
2637   // Create a placeholder Descriptor of the specified name
2638   Symbol NewPlaceholder(absl::string_view name,
2639                         PlaceholderType placeholder_type) const;
2640   Symbol NewPlaceholderWithMutexHeld(absl::string_view name,
2641                                      PlaceholderType placeholder_type) const;
2642 
2643 #ifndef SWIG
2644   mutable absl::Mutex field_memo_table_mutex_;
2645   mutable std::unique_ptr<absl::flat_hash_map<
2646       std::pair<const void*, const void*>, std::unique_ptr<MemoBase>>>
2647       field_memo_table_ ABSL_GUARDED_BY(field_memo_table_mutex_) =
2648           std::make_unique<
2649               absl::flat_hash_map<std::pair<const void*, const void*>,
2650                                   std::unique_ptr<MemoBase>>>();
2651 #endif  // SWIG
2652 
2653   // If fallback_database_ is nullptr, this is nullptr.  Otherwise, this is a
2654   // mutex which must be locked while accessing tables_.
2655   absl::Mutex* mutex_;
2656 
2657   // See constructor.
2658   DescriptorDatabase* fallback_database_;
2659   ErrorCollector* default_error_collector_;
2660   const DescriptorPool* underlay_;
2661 
2662 #ifndef SWIG
2663   // Dispatcher for recursive calls during builds.
2664   std::unique_ptr<absl::AnyInvocable<void(absl::FunctionRef<void()>) const>>
2665       dispatcher_;
2666 #endif  // SWIG
2667 
2668   // This class contains a lot of hash maps with complicated types that
2669   // we'd like to keep out of the header.
2670   class Tables;
2671   std::unique_ptr<Tables> tables_;
2672 
2673   bool enforce_dependencies_;
2674   bool lazily_build_dependencies_;
2675   bool allow_unknown_;
2676   bool enforce_weak_;
2677   bool enforce_option_ = false;
2678   ExtDeclEnforcementLevel enforce_extension_declarations_;
2679   bool disallow_enforce_utf8_;
2680   bool deprecated_legacy_json_field_conflicts_;
2681   bool enforce_naming_style_;
2682   bool enforce_symbol_visibility_ = false;
2683   mutable bool build_started_ = false;
2684 
2685   // Set of files to track for additional validation. The bool value when true
2686   // means unused imports are treated as errors (and as warnings when false).
2687   absl::flat_hash_map<std::string, bool> direct_input_files_;
2688 
2689   // Specification of defaults to use for feature resolution.  This defaults to
2690   // just the global and C++ features, but can be overridden for other runtimes.
2691   std::unique_ptr<FeatureSetDefaults> feature_set_defaults_spec_;
2692 
2693   // Returns true if the field extends an option message of descriptor.proto.
2694   bool IsReadyForCheckingDescriptorExtDecl(
2695       absl::string_view message_name) const;
2696 
2697 
2698   bool ResolvesFeaturesForImpl(int extension_number) const;
2699 
2700   const FeatureSetDefaults& GetFeatureSetDefaults() const;
2701 };
2702 
2703 
2704 // inline methods ====================================================
2705 
2706 // These macros makes this repetitive code more readable.
2707 #define PROTOBUF_DEFINE_ACCESSOR(CLASS, FIELD, TYPE) \
2708   inline TYPE CLASS::FIELD() const { return FIELD##_; }
2709 
2710 // Strings fields are stored as pointers but returned as const references.
2711 #define PROTOBUF_DEFINE_STRING_ACCESSOR(CLASS, FIELD) \
2712   inline absl::string_view CLASS::FIELD() const { return *FIELD##_; }
2713 
2714 // Name and full name are stored in a single array to save space.
2715 #define PROTOBUF_DEFINE_NAME_ACCESSOR(CLASS)                                 \
2716   inline absl::string_view CLASS::name() const { return all_names_.name(); } \
2717   inline absl::string_view CLASS::full_name() const {                        \
2718     return all_names_.full_name();                                           \
2719   }
2720 
2721 // Arrays take an index parameter, obviously.
2722 #define PROTOBUF_DEFINE_ARRAY_ACCESSOR(CLASS, FIELD, TYPE) \
2723   inline TYPE CLASS::FIELD(int index) const {              \
2724     ABSL_DCHECK_LE(0, index);                              \
2725     ABSL_DCHECK_LT(index, FIELD##_count());                \
2726     return FIELD##s_ + index;                              \
2727   }
2728 
2729 #define PROTOBUF_DEFINE_OPTIONS_ACCESSOR(CLASS, TYPE) \
2730   inline const TYPE& CLASS::options() const { return *options_; }
2731 
2732 PROTOBUF_DEFINE_NAME_ACCESSOR(Descriptor)
2733 PROTOBUF_DEFINE_ACCESSOR(Descriptor, file, const FileDescriptor*)
2734 PROTOBUF_DEFINE_ACCESSOR(Descriptor, containing_type, const Descriptor*)
2735 
2736 PROTOBUF_DEFINE_ACCESSOR(Descriptor, field_count, int)
2737 PROTOBUF_DEFINE_ACCESSOR(Descriptor, oneof_decl_count, int)
2738 PROTOBUF_DEFINE_ACCESSOR(Descriptor, real_oneof_decl_count, int)
2739 PROTOBUF_DEFINE_ACCESSOR(Descriptor, nested_type_count, int)
2740 PROTOBUF_DEFINE_ACCESSOR(Descriptor, enum_type_count, int)
2741 
2742 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, field, const FieldDescriptor*)
2743 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, oneof_decl, const OneofDescriptor*)
2744 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, nested_type, const Descriptor*)
2745 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, enum_type, const EnumDescriptor*)
2746 inline const OneofDescriptor* Descriptor::real_oneof_decl(int index) const {
2747   ABSL_DCHECK(index < real_oneof_decl_count());
2748   return oneof_decl(index);
2749 }
2750 
2751 PROTOBUF_DEFINE_ACCESSOR(Descriptor, extension_range_count, int)
2752 PROTOBUF_DEFINE_ACCESSOR(Descriptor, extension_count, int)
2753 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension_range,
2754                                const Descriptor::ExtensionRange*)
2755 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension, const FieldDescriptor*)
2756 
2757 PROTOBUF_DEFINE_ACCESSOR(Descriptor, reserved_range_count, int)
2758 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, reserved_range,
2759                                const Descriptor::ReservedRange*)
2760 PROTOBUF_DEFINE_ACCESSOR(Descriptor, reserved_name_count, int)
2761 
2762 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(Descriptor, MessageOptions)
2763 PROTOBUF_DEFINE_ACCESSOR(Descriptor, is_placeholder, bool)
2764 
2765 PROTOBUF_DEFINE_NAME_ACCESSOR(FieldDescriptor)
2766 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, file, const FileDescriptor*)
2767 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, number, int)
2768 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, is_extension, bool)
2769 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, containing_type, const Descriptor*)
2770 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(FieldDescriptor, FieldOptions)
2771 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_default_value, bool)
2772 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_json_name, bool)
2773 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int32_t, int32_t)
2774 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int64_t, int64_t)
2775 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint32_t, uint32_t)
2776 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint64_t, uint64_t)
2777 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_float, float)
2778 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_double, double)
2779 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_bool, bool)
2780 PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, default_value_string)
2781 
2782 PROTOBUF_DEFINE_NAME_ACCESSOR(OneofDescriptor)
2783 PROTOBUF_DEFINE_ACCESSOR(OneofDescriptor, containing_type, const Descriptor*)
2784 PROTOBUF_DEFINE_ACCESSOR(OneofDescriptor, field_count, int)
2785 PROTOBUF_DEFINE_ARRAY_ACCESSOR(OneofDescriptor, field, const FieldDescriptor*)
2786 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(OneofDescriptor, OneofOptions)
2787 
2788 PROTOBUF_DEFINE_NAME_ACCESSOR(EnumDescriptor)
2789 PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, file, const FileDescriptor*)
2790 PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, containing_type, const Descriptor*)
2791 PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, value_count, int)
2792 PROTOBUF_DEFINE_ARRAY_ACCESSOR(EnumDescriptor, value,
2793                                const EnumValueDescriptor*)
2794 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(EnumDescriptor, EnumOptions)
2795 PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, is_placeholder, bool)
2796 PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, reserved_range_count, int)
2797 PROTOBUF_DEFINE_ARRAY_ACCESSOR(EnumDescriptor, reserved_range,
2798                                const EnumDescriptor::ReservedRange*)
2799 PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, reserved_name_count, int)
2800 
2801 inline absl::string_view EnumValueDescriptor::name() const {
2802   return all_names_[0];
2803 }
2804 inline absl::string_view EnumValueDescriptor::full_name() const {
2805   return all_names_[1];
2806 }
2807 PROTOBUF_DEFINE_ACCESSOR(EnumValueDescriptor, number, int)
2808 PROTOBUF_DEFINE_ACCESSOR(EnumValueDescriptor, type, const EnumDescriptor*)
2809 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(EnumValueDescriptor, EnumValueOptions)
2810 
2811 PROTOBUF_DEFINE_NAME_ACCESSOR(ServiceDescriptor)
2812 PROTOBUF_DEFINE_ACCESSOR(ServiceDescriptor, file, const FileDescriptor*)
2813 PROTOBUF_DEFINE_ACCESSOR(ServiceDescriptor, method_count, int)
2814 PROTOBUF_DEFINE_ARRAY_ACCESSOR(ServiceDescriptor, method,
2815                                const MethodDescriptor*)
2816 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(ServiceDescriptor, ServiceOptions)
2817 
2818 PROTOBUF_DEFINE_NAME_ACCESSOR(MethodDescriptor)
2819 PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, service, const ServiceDescriptor*)
2820 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(MethodDescriptor, MethodOptions)
2821 PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, client_streaming, bool)
2822 PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, server_streaming, bool)
2823 
2824 PROTOBUF_DEFINE_STRING_ACCESSOR(FileDescriptor, name)
2825 PROTOBUF_DEFINE_STRING_ACCESSOR(FileDescriptor, package)
2826 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, pool, const DescriptorPool*)
2827 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, dependency_count, int)
2828 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, public_dependency_count, int)
2829 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, weak_dependency_count, int)
2830 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, option_dependency_count, int)
2831 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, message_type_count, int)
2832 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, enum_type_count, int)
2833 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, service_count, int)
2834 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, extension_count, int)
2835 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(FileDescriptor, FileOptions)
2836 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, is_placeholder, bool)
2837 
2838 PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, message_type, const Descriptor*)
2839 PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, enum_type, const EnumDescriptor*)
2840 PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, service,
2841                                const ServiceDescriptor*)
2842 PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, extension,
2843                                const FieldDescriptor*)
2844 
2845 #undef PROTOBUF_DEFINE_ACCESSOR
2846 #undef PROTOBUF_DEFINE_STRING_ACCESSOR
2847 #undef PROTOBUF_DEFINE_ARRAY_ACCESSOR
2848 
2849 // A few accessors differ from the macros...
2850 
2851 inline Descriptor::WellKnownType Descriptor::well_known_type() const {
2852   return static_cast<Descriptor::WellKnownType>(well_known_type_);
2853 }
2854 
2855 inline bool Descriptor::IsExtensionNumber(int number) const {
2856   return FindExtensionRangeContainingNumber(number) != nullptr;
2857 }
2858 
2859 inline bool Descriptor::IsReservedNumber(int number) const {
2860   return FindReservedRangeContainingNumber(number) != nullptr;
2861 }
2862 
2863 inline bool Descriptor::IsReservedName(absl::string_view name) const {
2864   for (int i = 0; i < reserved_name_count(); i++) {
2865     if (name == static_cast<absl::string_view>(reserved_name(i))) {
2866       return true;
2867     }
2868   }
2869   return false;
2870 }
2871 
2872 // Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually
2873 // an array of pointers rather than the usual array of objects.
2874 inline absl::string_view Descriptor::reserved_name(int index) const {
2875   return *reserved_names_[index];
2876 }
2877 
2878 inline bool EnumDescriptor::IsReservedNumber(int number) const {
2879   return FindReservedRangeContainingNumber(number) != nullptr;
2880 }
2881 
2882 inline bool EnumDescriptor::IsReservedName(absl::string_view name) const {
2883   for (int i = 0; i < reserved_name_count(); i++) {
2884     if (name == static_cast<absl::string_view>(reserved_name(i))) {
2885       return true;
2886     }
2887   }
2888   return false;
2889 }
2890 
2891 // Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually
2892 // an array of pointers rather than the usual array of objects.
2893 inline absl::string_view EnumDescriptor::reserved_name(int index) const {
2894   return *reserved_names_[index];
2895 }
2896 
2897 inline absl::string_view FieldDescriptor::lowercase_name() const {
2898   return all_names_.lowercase_name();
2899 }
2900 
2901 inline absl::string_view FieldDescriptor::camelcase_name() const {
2902   return all_names_.camelcase_name();
2903 }
2904 
2905 inline absl::string_view FieldDescriptor::json_name() const {
2906   return all_names_.json_name();
2907 }
2908 
2909 inline const OneofDescriptor* FieldDescriptor::containing_oneof() const {
2910   if (is_oneof_) {
2911     auto* res = scope_.containing_oneof;
2912     PROTOBUF_ASSUME(res != nullptr);
2913     return res;
2914   }
2915   return nullptr;
2916 }
2917 
2918 inline int FieldDescriptor::index_in_oneof() const {
2919   ABSL_DCHECK(is_oneof_);
2920   return static_cast<int>(this - scope_.containing_oneof->field(0));
2921 }
2922 
2923 inline const Descriptor* FieldDescriptor::extension_scope() const {
2924   ABSL_CHECK(is_extension_);
2925   return scope_.extension_scope;
2926 }
2927 
2928 inline FieldDescriptor::Label FieldDescriptor::label() const {
2929   if (is_required()) {
2930     return LABEL_REQUIRED;
2931   } else if (is_repeated()) {
2932     return LABEL_REPEATED;
2933   } else {
2934     return LABEL_OPTIONAL;
2935   }
2936 }
2937 
2938 inline FieldDescriptor::Type FieldDescriptor::type() const {
2939   return static_cast<Type>(type_);
2940 }
2941 
2942 inline FieldDescriptor::CppStringType FieldDescriptor::cpp_string_type() const {
2943   ABSL_DCHECK_EQ(cpp_string_type_,
2944                  static_cast<uint8_t>(CalculateCppStringType()));
2945   return static_cast<FieldDescriptor::CppStringType>(cpp_string_type_);
2946 }
2947 
2948 inline bool FieldDescriptor::is_optional() const {
2949   return !is_repeated() && !is_required();
2950 }
2951 
2952 inline bool FieldDescriptor::is_repeated() const {
2953   ABSL_DCHECK_EQ(is_repeated_, static_cast<Label>(label_) == LABEL_REPEATED);
2954   return is_repeated_;
2955 }
2956 
2957 inline bool FieldDescriptor::is_packable() const {
2958   return is_repeated() && IsTypePackable(type());
2959 }
2960 
2961 inline bool FieldDescriptor::is_map() const {
2962   ABSL_DCHECK_EQ(is_map_, type() == TYPE_MESSAGE && is_map_message_type());
2963   return is_map_;
2964 }
2965 
2966 inline const OneofDescriptor* FieldDescriptor::real_containing_oneof() const {
2967   if (in_real_oneof_) {
2968     auto* res = containing_oneof();
2969     PROTOBUF_ASSUME(res != nullptr);
2970     ABSL_DCHECK(!res->is_synthetic());
2971     return res;
2972   }
2973   return nullptr;
2974 }
2975 
2976 // To save space, index() is computed by looking at the descriptor's position
2977 // in the parent's array of children.
2978 inline int FieldDescriptor::index() const {
2979   if (!is_extension_) {
2980     return static_cast<int>(this - containing_type()->fields_);
2981   } else if (extension_scope() != nullptr) {
2982     return static_cast<int>(this - extension_scope()->extensions_);
2983   } else {
2984     return static_cast<int>(this - file_->extensions_);
2985   }
2986 }
2987 
2988 inline int Descriptor::index() const {
2989   if (containing_type_ == nullptr) {
2990     return static_cast<int>(this - file_->message_types_);
2991   } else {
2992     return static_cast<int>(this - containing_type_->nested_types_);
2993   }
2994 }
2995 
2996 inline int Descriptor::ExtensionRange::index() const {
2997   return static_cast<int>(this - containing_type_->extension_ranges_);
2998 }
2999 
3000 inline const FileDescriptor* OneofDescriptor::file() const {
3001   return containing_type()->file();
3002 }
3003 
3004 inline int OneofDescriptor::index() const {
3005   return static_cast<int>(this - containing_type_->oneof_decls_);
3006 }
3007 
3008 inline bool OneofDescriptor::is_synthetic() const {
3009   return field_count() == 1 && field(0)->proto3_optional_;
3010 }
3011 
3012 inline int EnumDescriptor::index() const {
3013   if (containing_type_ == nullptr) {
3014     return static_cast<int>(this - file_->enum_types_);
3015   } else {
3016     return static_cast<int>(this - containing_type_->enum_types_);
3017   }
3018 }
3019 
3020 inline const FileDescriptor* EnumValueDescriptor::file() const {
3021   return type()->file();
3022 }
3023 
3024 inline int EnumValueDescriptor::index() const {
3025   return static_cast<int>(this - type_->values_);
3026 }
3027 
3028 inline int ServiceDescriptor::index() const {
3029   return static_cast<int>(this - file_->services_);
3030 }
3031 
3032 inline const FileDescriptor* MethodDescriptor::file() const {
3033   return service()->file();
3034 }
3035 
3036 inline int MethodDescriptor::index() const {
3037   return static_cast<int>(this - service_->methods_);
3038 }
3039 
3040 inline absl::string_view FieldDescriptor::type_name() const {
3041   return kTypeToName[type()];
3042 }
3043 
3044 inline FieldDescriptor::CppType FieldDescriptor::cpp_type() const {
3045   return kTypeToCppTypeMap[type()];
3046 }
3047 
3048 inline absl::string_view FieldDescriptor::cpp_type_name() const {
3049   return kCppTypeToName[kTypeToCppTypeMap[type()]];
3050 }
3051 
3052 inline FieldDescriptor::CppType FieldDescriptor::TypeToCppType(Type type) {
3053   return kTypeToCppTypeMap[type];
3054 }
3055 
3056 inline absl::string_view FieldDescriptor::TypeName(Type type) {
3057   return kTypeToName[type];
3058 }
3059 
3060 inline absl::string_view FieldDescriptor::CppTypeName(CppType cpp_type) {
3061   return kCppTypeToName[cpp_type];
3062 }
3063 
3064 inline bool FieldDescriptor::IsTypePackable(Type field_type) {
3065   return (field_type != FieldDescriptor::TYPE_STRING &&
3066           field_type != FieldDescriptor::TYPE_GROUP &&
3067           field_type != FieldDescriptor::TYPE_MESSAGE &&
3068           field_type != FieldDescriptor::TYPE_BYTES);
3069 }
3070 
3071 inline const FileDescriptor* FileDescriptor::public_dependency(
3072     int index) const {
3073   return dependency(public_dependencies_[index]);
3074 }
3075 
3076 inline const FileDescriptor* FileDescriptor::weak_dependency(int index) const {
3077   return dependency(weak_dependencies_[index]);
3078 }
3079 
3080 // BitField handling of SymbolVisibility in message/enum
3081 inline SymbolVisibility Descriptor::visibility_keyword() const {
3082   return static_cast<SymbolVisibility>(visibility_);
3083 }
3084 
3085 inline SymbolVisibility EnumDescriptor::visibility_keyword() const {
3086   return static_cast<SymbolVisibility>(visibility_);
3087 }
3088 
3089 namespace internal {
3090 
3091 inline const std::string& DefaultValueStringAsString(
3092     const FieldDescriptor* field) {
3093   return *field->default_value_string_;
3094 }
3095 
3096 inline const std::string& NameOfEnumAsString(
3097     const EnumValueDescriptor* descriptor) {
3098   return descriptor->all_names_[0];
3099 }
3100 
3101 inline bool IsEnumFullySequential(const EnumDescriptor* enum_desc) {
3102   return enum_desc->sequential_value_limit_ == enum_desc->value_count() - 1;
3103 }
3104 
3105 // FieldRange(desc) provides an iterable range for the fields of a
3106 // descriptor type, appropriate for range-for loops.
3107 
3108 template <typename T>
3109 struct FieldRangeImpl;
3110 
3111 template <typename T>
3112 FieldRangeImpl<T> FieldRange(const T* desc) {
3113   return {desc};
3114 }
3115 
3116 template <typename T>
3117 struct FieldRangeImpl {
3118   struct Iterator {
3119     using iterator_category = std::forward_iterator_tag;
3120     using value_type = const FieldDescriptor*;
3121     using difference_type = int;
3122 
3123     value_type operator*() { return descriptor->field(idx); }
3124 
3125     friend bool operator==(const Iterator& a, const Iterator& b) {
3126       ABSL_DCHECK(a.descriptor == b.descriptor);
3127       return a.idx == b.idx;
3128     }
3129     friend bool operator!=(const Iterator& a, const Iterator& b) {
3130       return !(a == b);
3131     }
3132 
3133     Iterator& operator++() {
3134       idx++;
3135       return *this;
3136     }
3137 
3138     int idx;
3139     const T* descriptor;
3140   };
3141 
3142   Iterator begin() const { return {0, descriptor}; }
3143   Iterator end() const { return {descriptor->field_count(), descriptor}; }
3144 
3145   const T* descriptor;
3146 };
3147 
3148 // While building descriptors, we need to avoid using MergeFrom()/CopyFrom() to
3149 // be -fno-rtti friendly. Without RTTI, MergeFrom() and CopyFrom() will fallback
3150 // to the reflection based method, which requires the Descriptor. However, while
3151 // building the descriptors, this causes deadlock. We also must disable lazy
3152 // parsing because that uses reflection to verify consistency.
3153 bool ParseNoReflection(absl::string_view from, google::protobuf::MessageLite& to);
3154 
3155 // The context for these functions under `cpp` is "for the C++ implementation".
3156 // In particular, questions like "does this field have a has bit?" have a
3157 // different answer depending on the language.
3158 namespace cpp {
3159 
3160 // The maximum allowed nesting for message declarations.
3161 // Going over this limit will make the proto definition invalid.
3162 constexpr int MaxMessageDeclarationNestingDepth() { return 32; }
3163 
3164 // Returns true if 'enum' semantics are such that unknown values are preserved
3165 // in the enum field itself, rather than going to the UnknownFieldSet.
3166 PROTOBUF_EXPORT bool HasPreservingUnknownEnumSemantics(
3167     const FieldDescriptor* field);
3168 
3169 #ifndef SWIG
3170 enum class HasbitMode : uint8_t {
3171   // Hasbits do not exist for the field.
3172   kNoHasbit,
3173   // Hasbits exist and indicate field presence.
3174   // Hasbit is set if and only if field is present.
3175   kTrueHasbit,
3176   // Hasbits exist and "hint at" field presence.
3177   // When hasbit is set, field is 'probably' present, but field accessors must
3178   // still check for field presence (i.e. false positives are possible).
3179   // When hasbit is unset, field is guaranteed to be not present.
3180   kHintHasbit,
3181 };
3182 
3183 // Returns the "hasbit mode" of the field. Depending on the implementation, a
3184 // field can:
3185 //   - have no hasbits in its internal object (kNoHasbit);
3186 //   - have hasbits where hasbit == 1 indicates field presence and hasbit == 0
3187 //     indicates an unset field (kTrueHasbit);
3188 //   - have hasbits where hasbit == 1 indicates "field is possibly modified" and
3189 //     hasbit == 0 indicates "field is definitely missing" (kHintHasbit).
3190 //
3191 // Note that this may not match the hasbit mode chosen by the compiler, which
3192 // may be influenced by other factors like PDProto profiles.
3193 PROTOBUF_EXPORT HasbitMode
3194 GetFieldHasbitModeWithoutProfile(const FieldDescriptor* field);
3195 
3196 // Returns true if there are hasbits for the field.
3197 // Note that this does not correlate with "hazzer"s, i.e., whether has_foo APIs
3198 // are emitted.
3199 //
3200 // Note that this may not match the hasbit mode chosen by the compiler, which
3201 // may be influenced by other factors like PDProto profiles.
3202 PROTOBUF_EXPORT bool HasHasbitWithoutProfile(const FieldDescriptor* field);
3203 
3204 enum class Utf8CheckMode : uint8_t {
3205   kStrict = 0,  // Parsing will fail if non UTF-8 data is in string fields.
3206   kVerify = 1,  // Only log an error but parsing will succeed.
3207   kNone = 2,    // No UTF-8 check.
3208 };
3209 PROTOBUF_EXPORT Utf8CheckMode GetUtf8CheckMode(const FieldDescriptor* field,
3210                                                bool is_lite);
3211 
3212 // Returns true if the field is a "group-like field" consistent with a proto2
3213 // group:
3214 //  - Message encoding is DELIMITED (synonymous with type TYPE_GROUP)
3215 //  - Field name is exactly the message name lowercased
3216 //  - Message is defined within the same scope as the field
3217 PROTOBUF_EXPORT bool IsGroupLike(const FieldDescriptor& field);
3218 
3219 // Returns whether or not this file is lazily initialized rather than
3220 // pre-main via static initialization.  This has to be done for our bootstrapped
3221 // protos to avoid linker bloat in lite runtimes.
3222 PROTOBUF_EXPORT bool IsLazilyInitializedFile(absl::string_view filename);
3223 
3224 // Returns true during internal calls that should avoid calling trackers.  These
3225 // calls can be particularly dangerous during build steps like feature
3226 // resolution, where a MergeFrom call can wind up in a deadlock.
3227 PROTOBUF_EXPORT inline bool& IsTrackingEnabledVar() {
3228   static PROTOBUF_THREAD_LOCAL bool is_tracking_enabled = true;
3229   return is_tracking_enabled;
3230 }
3231 PROTOBUF_EXPORT inline bool IsTrackingEnabled() {
3232   return ABSL_PREDICT_TRUE(IsTrackingEnabledVar());
3233 }
3234 
3235 template <typename F>
3236 auto VisitDescriptorsInFileOrder(const Descriptor* desc,
3237                                  F& f) -> decltype(f(desc)) {
3238   for (int i = 0; i < desc->nested_type_count(); i++) {
3239     if (auto res = VisitDescriptorsInFileOrder(desc->nested_type(i), f)) {
3240       return res;
3241     }
3242   }
3243   if (auto res = f(desc)) return res;
3244   return {};
3245 }
3246 
3247 // Visit the messages in post-order traversal.
3248 // We need several pieces of code to follow the same order because we use the
3249 // index of types during array lookups.
3250 // If any call returns a "truthy" value, it stops visitation and returns that
3251 // value right away. Otherwise returns `{}` after visiting all types.
3252 template <typename F>
3253 auto VisitDescriptorsInFileOrder(const FileDescriptor* file,
3254                                  F f) -> decltype(f(file->message_type(0))) {
3255   for (int i = 0; i < file->message_type_count(); i++) {
3256     if (auto res = VisitDescriptorsInFileOrder(file->message_type(i), f)) {
3257       return res;
3258     }
3259   }
3260   return {};
3261 }
3262 #endif  // !SWIG
3263 
3264 // Whether the given string field should have the accessors be privatized due
3265 // to it being an unsupported type. If this returns true, cpp_string_type()
3266 // returns kString for the storage, the C++ Generator will not generate
3267 // public accessors for the type, but the field will sill be accessible via
3268 // reflection.
3269 PROTOBUF_EXPORT bool IsStringFieldWithPrivatizedAccessors(
3270     const FieldDescriptor& field);
3271 
3272 }  // namespace cpp
3273 }  // namespace internal
3274 
3275 }  // namespace protobuf
3276 }  // namespace google
3277 
3278 #undef PROTOBUF_INTERNAL_CHECK_CLASS_SIZE
3279 #include "google/protobuf/port_undef.inc"
3280 
3281 #endif  // GOOGLE_PROTOBUF_DESCRIPTOR_H__