Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-31 10:12:07

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