Coverage Report

Created: 2025-04-27 06:20

/src/LPM/external.protobuf/include/google/protobuf/descriptor.h
Line
Count
Source (jump to first uncovered line)
1
// Protocol Buffers - Google's data interchange format
2
// Copyright 2008 Google Inc.  All rights reserved.
3
//
4
// Use of this source code is governed by a BSD-style
5
// license that can be found in the LICENSE file or at
6
// https://developers.google.com/open-source/licenses/bsd
7
8
// Author: kenton@google.com (Kenton Varda)
9
//  Based on original Protocol Buffers design by
10
//  Sanjay Ghemawat, Jeff Dean, and others.
11
//
12
// This file contains classes which describe a type of protocol message.
13
// You can use a message's descriptor to learn at runtime what fields
14
// it contains and what the types of those fields are.  The Message
15
// interface also allows you to dynamically access and modify individual
16
// fields by passing the FieldDescriptor of the field you are interested
17
// in.
18
//
19
// Most users will not care about descriptors, because they will write
20
// code specific to certain protocol types and will simply use the classes
21
// generated by the protocol compiler directly.  Advanced users who want
22
// to operate on arbitrary types (not known at compile time) may want to
23
// read descriptors in order to learn about the contents of a message.
24
// A very small number of users will want to construct their own
25
// Descriptors, either because they are implementing Message manually or
26
// because they are writing something like the protocol compiler.
27
//
28
// For an example of how you might use descriptors, see the code example
29
// at the top of message.h.
30
31
#ifndef GOOGLE_PROTOBUF_DESCRIPTOR_H__
32
#define GOOGLE_PROTOBUF_DESCRIPTOR_H__
33
34
#include <atomic>
35
#include <cstdint>
36
#include <iterator>
37
#include <memory>
38
#include <string>
39
#include <utility>
40
#include <vector>
41
42
#include "google/protobuf/stubs/common.h"
43
#include "absl/base/attributes.h"
44
#include "absl/base/call_once.h"
45
#include "absl/container/btree_map.h"
46
#include "absl/container/flat_hash_map.h"
47
#include "absl/functional/any_invocable.h"
48
#include "absl/functional/function_ref.h"
49
#include "absl/log/absl_check.h"
50
#include "absl/log/absl_log.h"
51
#include "absl/strings/str_format.h"
52
#include "absl/strings/string_view.h"
53
#include "absl/synchronization/mutex.h"
54
#include "absl/types/optional.h"
55
#include "google/protobuf/descriptor_lite.h"
56
#include "google/protobuf/extension_set.h"
57
#include "google/protobuf/port.h"
58
59
// Must be included last.
60
#include "google/protobuf/port_def.inc"
61
62
#ifdef SWIG
63
#define PROTOBUF_EXPORT
64
#define PROTOBUF_IGNORE_DEPRECATION_START
65
#define PROTOBUF_IGNORE_DEPRECATION_STOP
66
#endif
67
68
69
namespace google {
70
namespace protobuf {
71
// Defined in this file.
72
class Descriptor;
73
class FieldDescriptor;
74
class OneofDescriptor;
75
class EnumDescriptor;
76
class EnumValueDescriptor;
77
class ServiceDescriptor;
78
class MethodDescriptor;
79
class FileDescriptor;
80
class DescriptorDatabase;
81
class DescriptorPool;
82
83
// Defined in descriptor.proto
84
#ifndef SWIG
85
enum Edition : int;
86
#else   // !SWIG
87
typedef int Edition;
88
#endif  // !SWIG
89
class DescriptorProto;
90
class DescriptorProto_ExtensionRange;
91
class FieldDescriptorProto;
92
class OneofDescriptorProto;
93
class EnumDescriptorProto;
94
class EnumValueDescriptorProto;
95
class ServiceDescriptorProto;
96
class MethodDescriptorProto;
97
class FileDescriptorProto;
98
class MessageOptions;
99
class FieldOptions;
100
class OneofOptions;
101
class EnumOptions;
102
class EnumValueOptions;
103
class ExtensionRangeOptions;
104
class ServiceOptions;
105
class MethodOptions;
106
class FileOptions;
107
class UninterpretedOption;
108
class FeatureSet;
109
class FeatureSetDefaults;
110
class SourceCodeInfo;
111
112
// Defined in message_lite.h
113
class MessageLite;
114
115
// Defined in message.h
116
class Message;
117
class Reflection;
118
119
// Defined in descriptor.cc
120
class DescriptorBuilder;
121
class FileDescriptorTables;
122
class Symbol;
123
124
// Defined in unknown_field_set.h.
125
class UnknownField;
126
127
// Defined in command_line_interface.cc
128
namespace compiler {
129
class CodeGenerator;
130
class CommandLineInterface;
131
namespace cpp {
132
// Defined in helpers.h
133
class Formatter;
134
}  // namespace cpp
135
}  // namespace compiler
136
137
namespace descriptor_unittest {
138
class DescriptorTest;
139
class ValidationErrorTest;
140
}  // namespace descriptor_unittest
141
142
// Defined in printer.h
143
namespace io {
144
class Printer;
145
}  // namespace io
146
147
// NB, all indices are zero-based.
148
struct SourceLocation {
149
  int start_line;
150
  int end_line;
151
  int start_column;
152
  int end_column;
153
154
  // Doc comments found at the source location.
155
  // See the comments in SourceCodeInfo.Location (descriptor.proto) for details.
156
  std::string leading_comments;
157
  std::string trailing_comments;
158
  std::vector<std::string> leading_detached_comments;
159
};
160
161
// Options when generating machine-parsable output from a descriptor with
162
// DebugString().
163
struct DebugStringOptions {
164
  // include original user comments as recorded in SourceLocation entries. N.B.
165
  // that this must be |false| by default: several other pieces of code (for
166
  // example, the C++ code generation for fields in the proto compiler) rely on
167
  // DebugString() output being unobstructed by user comments.
168
  bool include_comments;
169
  // If true, elide the braced body in the debug string.
170
  bool elide_group_body;
171
  bool elide_oneof_body;
172
173
  DebugStringOptions()
174
      : include_comments(false),
175
        elide_group_body(false),
176
0
        elide_oneof_body(false) {
177
0
  }
178
};
179
180
// A class to handle the simplest cases of a lazily linked descriptor
181
// for a message type that isn't built at the time of cross linking,
182
// which is needed when a pool has lazily_build_dependencies_ set.
183
// Must be instantiated as mutable in a descriptor.
184
namespace internal {
185
186
// The classes in this file represent a significant memory footprint for the
187
// library. We make sure we are not accidentally making them larger by
188
// hardcoding the struct size for a specific platform. Use as:
189
//
190
//   PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(type, expected_size_in_x84-64);
191
//
192
193
#if !defined(PROTOBUF_INTERNAL_CHECK_CLASS_SIZE)
194
#define PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(t, expected)
195
#endif
196
197
// `typedef` instead of `using` for SWIG
198
#if defined(PROTOBUF_FUTURE_STRING_VIEW_RETURN_TYPE)
199
typedef absl::string_view DescriptorStringView;
200
#else
201
typedef const std::string& DescriptorStringView;
202
#endif
203
204
class FlatAllocator;
205
206
class PROTOBUF_EXPORT LazyDescriptor {
207
 public:
208
  // Init function to be called at init time of a descriptor containing
209
  // a LazyDescriptor.
210
0
  void Init() {
211
0
    descriptor_ = nullptr;
212
0
    once_ = nullptr;
213
0
  }
214
215
  // Sets the value of the descriptor if it is known during the descriptor
216
  // building process. Not thread safe, should only be called during the
217
  // descriptor build process. Should not be called after SetLazy has been
218
  // called.
219
  void Set(const Descriptor* descriptor);
220
221
  // Sets the information needed to lazily cross link the descriptor at a later
222
  // time, SetLazy is not thread safe, should be called only once at descriptor
223
  // build time if the symbol wasn't found and building of the file containing
224
  // that type is delayed because lazily_build_dependencies_ is set on the pool.
225
  // Should not be called after Set() has been called.
226
  void SetLazy(absl::string_view name, const FileDescriptor* file);
227
228
  // Returns the current value of the descriptor, thread-safe. If SetLazy(...)
229
  // has been called, will do a one-time cross link of the type specified,
230
  // building the descriptor file that contains the type if necessary.
231
0
  inline const Descriptor* Get(const ServiceDescriptor* service) {
232
0
    Once(service);
233
0
    return descriptor_;
234
0
  }
235
236
 private:
237
  void Once(const ServiceDescriptor* service);
238
239
  const Descriptor* descriptor_;
240
  // The once_ flag is followed by a NUL terminated string for the type name.
241
  absl::once_flag* once_;
242
};
243
244
class PROTOBUF_EXPORT SymbolBase {
245
 private:
246
  friend class google::protobuf::Symbol;
247
  uint8_t symbol_type_;
248
};
249
250
// Some types have more than one SymbolBase because they have multiple
251
// identities in the table. We can't have duplicate direct bases, so we use this
252
// intermediate base to do so.
253
// See BuildEnumValue for details.
254
template <int N>
255
class PROTOBUF_EXPORT SymbolBaseN : public SymbolBase {};
256
257
// This class is for internal use only and provides access to the resolved
258
// runtime FeatureSets of any descriptor.  These features are not designed
259
// to be stable, and depending directly on them (vs the public descriptor APIs)
260
// is not safe.
261
class PROTOBUF_EXPORT InternalFeatureHelper {
262
 public:
263
  template <typename DescriptorT>
264
  static const FeatureSet& GetFeatures(const DescriptorT& desc) {
265
    return desc.features();
266
  }
267
268
 private:
269
  friend class ::google::protobuf::compiler::CodeGenerator;
270
  friend class ::google::protobuf::compiler::CommandLineInterface;
271
272
  // Provides a restricted view exclusively to code generators to query their
273
  // own unresolved features.  Unresolved features are virtually meaningless to
274
  // everyone else. Code generators will need them to validate their own
275
  // features, and runtimes may need them internally to be able to properly
276
  // represent the original proto files from generated code.
277
  template <typename DescriptorT, typename TypeTraitsT, uint8_t field_type,
278
            bool is_packed>
279
  static typename TypeTraitsT::ConstType GetUnresolvedFeatures(
280
      const DescriptorT& descriptor,
281
      const google::protobuf::internal::ExtensionIdentifier<
282
          FeatureSet, TypeTraitsT, field_type, is_packed>& extension) {
283
    return descriptor.proto_features_->GetExtension(extension);
284
  }
285
286
  // Provides a restricted view exclusively to code generators to query the
287
  // edition of files being processed.  While most people should never write
288
  // edition-dependent code, generators frequently will need to.
289
  static Edition GetEdition(const FileDescriptor& desc);
290
};
291
292
PROTOBUF_EXPORT absl::string_view ShortEditionName(Edition edition);
293
294
bool IsEnumFullySequential(const EnumDescriptor* enum_desc);
295
296
const std::string& DefaultValueStringAsString(const FieldDescriptor* field);
297
const std::string& NameOfEnumAsString(const EnumValueDescriptor* descriptor);
298
299
}  // namespace internal
300
301
// Provide an Abseil formatter for edition names.
302
template <typename Sink>
303
void AbslStringify(Sink& sink, Edition edition) {
304
  absl::Format(&sink, "%v", internal::ShortEditionName(edition));
305
}
306
307
// Describes a type of protocol message, or a particular group within a
308
// message.  To obtain the Descriptor for a given message object, call
309
// Message::GetDescriptor().  Generated message classes also have a
310
// static method called descriptor() which returns the type's descriptor.
311
// Use DescriptorPool to construct your own descriptors.
312
class PROTOBUF_EXPORT Descriptor : private internal::SymbolBase {
313
 public:
314
  typedef DescriptorProto Proto;
315
#ifndef SWIG
316
  Descriptor(const Descriptor&) = delete;
317
  Descriptor& operator=(const Descriptor&) = delete;
318
#endif
319
320
  // The name of the message type, not including its scope.
321
  internal::DescriptorStringView name() const;
322
323
  // The fully-qualified name of the message type, scope delimited by
324
  // periods.  For example, message type "Foo" which is declared in package
325
  // "bar" has full name "bar.Foo".  If a type "Baz" is nested within
326
  // Foo, Baz's full_name is "bar.Foo.Baz".  To get only the part that
327
  // comes after the last '.', use name().
328
  internal::DescriptorStringView full_name() const;
329
330
  // Index of this descriptor within the file or containing type's message
331
  // type array.
332
  int index() const;
333
334
  // The .proto file in which this message type was defined.  Never nullptr.
335
  const FileDescriptor* file() const;
336
337
  // If this Descriptor describes a nested type, this returns the type
338
  // in which it is nested.  Otherwise, returns nullptr.
339
  const Descriptor* containing_type() const;
340
341
  // Get options for this message type.  These are specified in the .proto file
342
  // by placing lines like "option foo = 1234;" in the message definition.
343
  // Allowed options are defined by MessageOptions in descriptor.proto, and any
344
  // available extensions of that message.
345
  const MessageOptions& options() const;
346
347
  // Write the contents of this Descriptor into the given DescriptorProto.
348
  // The target DescriptorProto must be clear before calling this; if it
349
  // isn't, the result may be garbage.
350
  void CopyTo(DescriptorProto* proto) const;
351
352
  // Fills in the message-level settings of this message (e.g. name, reserved
353
  // fields, message options) to `proto`.  This is essentially all of the
354
  // metadata owned exclusively by this descriptor, and not any nested
355
  // descriptors.
356
  void CopyHeadingTo(DescriptorProto* proto) const;
357
358
  // Write the contents of this descriptor in a human-readable form. Output
359
  // will be suitable for re-parsing.
360
  std::string DebugString() const;
361
362
  // Similar to DebugString(), but additionally takes options (e.g.,
363
  // include original user comments in output).
364
  std::string DebugStringWithOptions(const DebugStringOptions& options) const;
365
366
  // Allows formatting with absl and gtest.
367
  template <typename Sink>
368
  friend void AbslStringify(Sink& sink, const Descriptor& d) {
369
    absl::Format(&sink, "%s", d.DebugString());
370
  }
371
372
  // Returns true if this is a placeholder for an unknown type. This will
373
  // only be the case if this descriptor comes from a DescriptorPool
374
  // with AllowUnknownDependencies() set.
375
  bool is_placeholder() const;
376
377
  enum WellKnownType {
378
    WELLKNOWNTYPE_UNSPECIFIED,  // Not a well-known type.
379
380
    // Wrapper types.
381
    WELLKNOWNTYPE_DOUBLEVALUE,  // google.protobuf.DoubleValue
382
    WELLKNOWNTYPE_FLOATVALUE,   // google.protobuf.FloatValue
383
    WELLKNOWNTYPE_INT64VALUE,   // google.protobuf.Int64Value
384
    WELLKNOWNTYPE_UINT64VALUE,  // google.protobuf.UInt64Value
385
    WELLKNOWNTYPE_INT32VALUE,   // google.protobuf.Int32Value
386
    WELLKNOWNTYPE_UINT32VALUE,  // google.protobuf.UInt32Value
387
    WELLKNOWNTYPE_STRINGVALUE,  // google.protobuf.StringValue
388
    WELLKNOWNTYPE_BYTESVALUE,   // google.protobuf.BytesValue
389
    WELLKNOWNTYPE_BOOLVALUE,    // google.protobuf.BoolValue
390
391
    // Other well known types.
392
    WELLKNOWNTYPE_ANY,        // google.protobuf.Any
393
    WELLKNOWNTYPE_FIELDMASK,  // google.protobuf.FieldMask
394
    WELLKNOWNTYPE_DURATION,   // google.protobuf.Duration
395
    WELLKNOWNTYPE_TIMESTAMP,  // google.protobuf.Timestamp
396
    WELLKNOWNTYPE_VALUE,      // google.protobuf.Value
397
    WELLKNOWNTYPE_LISTVALUE,  // google.protobuf.ListValue
398
    WELLKNOWNTYPE_STRUCT,     // google.protobuf.Struct
399
400
    // New well-known types may be added in the future.
401
    // Please make sure any switch() statements have a 'default' case.
402
    __WELLKNOWNTYPE__DO_NOT_USE__ADD_DEFAULT_INSTEAD__,
403
  };
404
405
  WellKnownType well_known_type() const;
406
407
  // Field stuff -----------------------------------------------------
408
409
  // The number of fields in this message type.
410
  int field_count() const;
411
  // Gets a field by index, where 0 <= index < field_count().
412
  // These are returned in the order they were defined in the .proto file.
413
  const FieldDescriptor* field(int index) const;
414
415
  // Looks up a field by declared tag number.  Returns nullptr if no such field
416
  // exists.
417
  const FieldDescriptor* FindFieldByNumber(int number) const;
418
  // Looks up a field by name.  Returns nullptr if no such field exists.
419
  const FieldDescriptor* FindFieldByName(absl::string_view name) const;
420
421
  // Looks up a field by lowercased name (as returned by lowercase_name()).
422
  // This lookup may be ambiguous if multiple field names differ only by case,
423
  // in which case the field returned is chosen arbitrarily from the matches.
424
  const FieldDescriptor* FindFieldByLowercaseName(
425
      absl::string_view lowercase_name) const;
426
427
  // Looks up a field by camel-case name (as returned by camelcase_name()).
428
  // This lookup may be ambiguous if multiple field names differ in a way that
429
  // leads them to have identical camel-case names, in which case the field
430
  // returned is chosen arbitrarily from the matches.
431
  const FieldDescriptor* FindFieldByCamelcaseName(
432
      absl::string_view camelcase_name) const;
433
434
  // The number of oneofs in this message type.
435
  int oneof_decl_count() const;
436
  // The number of oneofs in this message type, excluding synthetic oneofs.
437
  // Real oneofs always come first, so iterating up to real_oneof_decl_cout()
438
  // will yield all real oneofs.
439
  int real_oneof_decl_count() const;
440
  // Get a oneof by index, where 0 <= index < oneof_decl_count().
441
  // These are returned in the order they were defined in the .proto file.
442
  const OneofDescriptor* oneof_decl(int index) const;
443
  // Get a oneof by index, excluding synthetic oneofs, where 0 <= index <
444
  // real_oneof_decl_count(). These are returned in the order they were defined
445
  // in the .proto file.
446
  const OneofDescriptor* real_oneof_decl(int index) const;
447
448
  // Looks up a oneof by name.  Returns nullptr if no such oneof exists.
449
  const OneofDescriptor* FindOneofByName(absl::string_view name) const;
450
451
  // Nested type stuff -----------------------------------------------
452
453
  // The number of nested types in this message type.
454
  int nested_type_count() const;
455
  // Gets a nested type by index, where 0 <= index < nested_type_count().
456
  // These are returned in the order they were defined in the .proto file.
457
  const Descriptor* nested_type(int index) const;
458
459
  // Looks up a nested type by name.  Returns nullptr if no such nested type
460
  // exists.
461
  const Descriptor* FindNestedTypeByName(absl::string_view name) const;
462
463
  // Enum stuff ------------------------------------------------------
464
465
  // The number of enum types in this message type.
466
  int enum_type_count() const;
467
  // Gets an enum type by index, where 0 <= index < enum_type_count().
468
  // These are returned in the order they were defined in the .proto file.
469
  const EnumDescriptor* enum_type(int index) const;
470
471
  // Looks up an enum type by name.  Returns nullptr if no such enum type
472
  // exists.
473
  const EnumDescriptor* FindEnumTypeByName(absl::string_view name) const;
474
475
  // Looks up an enum value by name, among all enum types in this message.
476
  // Returns nullptr if no such value exists.
477
  const EnumValueDescriptor* FindEnumValueByName(absl::string_view name) const;
478
479
  // Extensions ------------------------------------------------------
480
481
  // A range of field numbers which are designated for third-party
482
  // extensions.
483
  class PROTOBUF_EXPORT ExtensionRange {
484
   public:
485
    typedef DescriptorProto_ExtensionRange Proto;
486
487
    typedef ExtensionRangeOptions OptionsType;
488
489
    // See Descriptor::CopyTo().
490
    void CopyTo(DescriptorProto_ExtensionRange* proto) const;
491
492
    // Returns the start field number of this range (inclusive).
493
0
    int start_number() const { return start_; }
494
495
    // Returns the end field number of this range (exclusive).
496
0
    int end_number() const { return end_; }
497
498
    // Returns the index of this extension range within the message's extension
499
    // range array.
500
    int index() const;
501
502
    // Returns the ExtensionRangeOptions for this range.
503
0
    const ExtensionRangeOptions& options() const { return *options_; }
504
505
    // Returns the name of the containing type.
506
0
    internal::DescriptorStringView name() const {
507
0
      return containing_type_->name();
508
0
    }
509
510
    // Returns the full name of the containing type.
511
0
    internal::DescriptorStringView full_name() const {
512
0
      return containing_type_->full_name();
513
0
    }
514
515
    // Returns the .proto file in which this range was defined.
516
    // Never nullptr.
517
0
    const FileDescriptor* file() const { return containing_type_->file(); }
518
519
    // Returns the Descriptor for the message containing this range.
520
    // Never nullptr.
521
0
    const Descriptor* containing_type() const { return containing_type_; }
522
523
   private:
524
    int start_;
525
    int end_;
526
    const ExtensionRangeOptions* options_;
527
528
   private:
529
    const Descriptor* containing_type_;
530
    const FeatureSet* proto_features_;
531
    const FeatureSet* merged_features_;
532
533
    // Get the merged features that apply to this extension range.  These are
534
    // specified in the .proto file through the feature options in the message
535
    // definition. Allowed features are defined by Features in descriptor.proto,
536
    // along with any backend-specific extensions to it.
537
0
    const FeatureSet& features() const { return *merged_features_; }
538
    friend class internal::InternalFeatureHelper;
539
540
    // Walks up the descriptor tree to generate the source location path
541
    // to this descriptor from the file root.
542
    void GetLocationPath(std::vector<int>* output) const;
543
544
    friend class Descriptor;
545
    friend class DescriptorPool;
546
    friend class DescriptorBuilder;
547
  };
548
549
  // The number of extension ranges in this message type.
550
  int extension_range_count() const;
551
  // Gets an extension range by index, where 0 <= index <
552
  // extension_range_count(). These are returned in the order they were defined
553
  // in the .proto file.
554
  const ExtensionRange* extension_range(int index) const;
555
556
  // Returns true if the number is in one of the extension ranges.
557
  bool IsExtensionNumber(int number) const;
558
559
  // Returns nullptr if no extension range contains the given number.
560
  const ExtensionRange* FindExtensionRangeContainingNumber(int number) const;
561
562
  // The number of extensions defined nested within this message type's scope.
563
  // See doc:
564
  // https://developers.google.com/protocol-buffers/docs/proto#nested-extensions
565
  //
566
  // Note that the extensions may be extending *other* messages.
567
  //
568
  // For example:
569
  // message M1 {
570
  //   extensions 1 to max;
571
  // }
572
  //
573
  // message M2 {
574
  //   extend M1 {
575
  //     optional int32 foo = 1;
576
  //   }
577
  // }
578
  //
579
  // In this case,
580
  // DescriptorPool::generated_pool()
581
  //     ->FindMessageTypeByName("M2")
582
  //     ->extension(0)
583
  // will return "foo", even though "foo" is an extension of M1.
584
  // To find all known extensions of a given message, instead use
585
  // DescriptorPool::FindAllExtensions.
586
  int extension_count() const;
587
  // Get an extension by index, where 0 <= index < extension_count().
588
  // These are returned in the order they were defined in the .proto file.
589
  const FieldDescriptor* extension(int index) const;
590
591
  // Looks up a named extension (which extends some *other* message type)
592
  // defined within this message type's scope.
593
  const FieldDescriptor* FindExtensionByName(absl::string_view name) const;
594
595
  // Similar to FindFieldByLowercaseName(), but finds extensions defined within
596
  // this message type's scope.
597
  const FieldDescriptor* FindExtensionByLowercaseName(
598
      absl::string_view name) const;
599
600
  // Similar to FindFieldByCamelcaseName(), but finds extensions defined within
601
  // this message type's scope.
602
  const FieldDescriptor* FindExtensionByCamelcaseName(
603
      absl::string_view name) const;
604
605
  // Reserved fields -------------------------------------------------
606
607
  // A range of reserved field numbers.
608
  struct ReservedRange {
609
    int start;  // inclusive
610
    int end;    // exclusive
611
  };
612
613
  // The number of reserved ranges in this message type.
614
  int reserved_range_count() const;
615
  // Gets an reserved range by index, where 0 <= index <
616
  // reserved_range_count(). These are returned in the order they were defined
617
  // in the .proto file.
618
  const ReservedRange* reserved_range(int index) const;
619
620
  // Returns true if the number is in one of the reserved ranges.
621
  bool IsReservedNumber(int number) const;
622
623
  // Returns nullptr if no reserved range contains the given number.
624
  const ReservedRange* FindReservedRangeContainingNumber(int number) const;
625
626
  // The number of reserved field names in this message type.
627
  int reserved_name_count() const;
628
629
  // Gets a reserved name by index, where 0 <= index < reserved_name_count().
630
  internal::DescriptorStringView reserved_name(int index) const;
631
632
  // Returns true if the field name is reserved.
633
  bool IsReservedName(absl::string_view name) const;
634
635
  // Source Location ---------------------------------------------------
636
637
  // Updates |*out_location| to the source location of the complete
638
  // extent of this message declaration.  Returns false and leaves
639
  // |*out_location| unchanged iff location information was not available.
640
  bool GetSourceLocation(SourceLocation* out_location) const;
641
642
  // Maps --------------------------------------------------------------
643
644
  // Returns the FieldDescriptor for the "key" field. If this isn't a map entry
645
  // field, returns nullptr.
646
  const FieldDescriptor* map_key() const;
647
648
  // Returns the FieldDescriptor for the "value" field. If this isn't a map
649
  // entry field, returns nullptr.
650
  const FieldDescriptor* map_value() const;
651
652
 private:
653
  friend class Symbol;
654
  typedef MessageOptions OptionsType;
655
656
  // Allows tests to test CopyTo(proto, true).
657
  friend class descriptor_unittest::DescriptorTest;
658
659
  // Allows access to GetLocationPath for annotations.
660
  friend class io::Printer;
661
  friend class compiler::cpp::Formatter;
662
663
  // Get the merged features that apply to this message type.  These are
664
  // specified in the .proto file through the feature options in the message
665
  // definition.  Allowed features are defined by Features in descriptor.proto,
666
  // along with any backend-specific extensions to it.
667
0
  const FeatureSet& features() const { return *merged_features_; }
668
  friend class internal::InternalFeatureHelper;
669
670
  // Fill the json_name field of FieldDescriptorProto.
671
  void CopyJsonNameTo(DescriptorProto* proto) const;
672
673
  // Internal version of DebugString; controls the level of indenting for
674
  // correct depth. Takes |options| to control debug-string options, and
675
  // |include_opening_clause| to indicate whether the "message ... " part of the
676
  // clause has already been generated (this varies depending on context).
677
  void DebugString(int depth, std::string* contents,
678
                   const DebugStringOptions& options,
679
                   bool include_opening_clause) const;
680
681
  // Walks up the descriptor tree to generate the source location path
682
  // to this descriptor from the file root.
683
  void GetLocationPath(std::vector<int>* output) const;
684
685
  // True if this is a placeholder for an unknown type.
686
  bool is_placeholder_ : 1;
687
  // True if this is a placeholder and the type name wasn't fully-qualified.
688
  bool is_unqualified_placeholder_ : 1;
689
  // Well known type.  Stored like this to conserve space.
690
  uint8_t well_known_type_ : 5;
691
692
  // This points to the last field _number_ that is part of the sequence
693
  // starting at 1, where
694
  //     `desc->field(i)->number() == i + 1`
695
  // A value of `0` means no field matches. That is, there are no fields or the
696
  // first field is not field `1`.
697
  // Uses 16-bit to avoid extra padding. Unlikely to have more than 2^16
698
  // sequentially numbered fields in a message.
699
  uint16_t sequential_field_limit_;
700
701
  int field_count_;
702
703
  // all_names_ = [name, full_name]
704
  const std::string* all_names_;
705
  const FileDescriptor* file_;
706
  const Descriptor* containing_type_;
707
  const MessageOptions* options_;
708
  const FeatureSet* proto_features_;
709
  const FeatureSet* merged_features_;
710
711
  // These arrays are separated from their sizes to minimize padding on 64-bit.
712
  FieldDescriptor* fields_;
713
  OneofDescriptor* oneof_decls_;
714
  Descriptor* nested_types_;
715
  EnumDescriptor* enum_types_;
716
  ExtensionRange* extension_ranges_;
717
  FieldDescriptor* extensions_;
718
  ReservedRange* reserved_ranges_;
719
  const std::string** reserved_names_;
720
721
  int oneof_decl_count_;
722
  int real_oneof_decl_count_;
723
  int nested_type_count_;
724
  int enum_type_count_;
725
  int extension_range_count_;
726
  int extension_count_;
727
  int reserved_range_count_;
728
  int reserved_name_count_;
729
730
  // IMPORTANT:  If you add a new field, make sure to search for all instances
731
  // of Allocate<Descriptor>() and AllocateArray<Descriptor>() in descriptor.cc
732
  // and update them to initialize the field.
733
734
  // Must be constructed using DescriptorPool.
735
  Descriptor();
736
  friend class DescriptorBuilder;
737
  friend class DescriptorPool;
738
  friend class EnumDescriptor;
739
  friend class FieldDescriptor;
740
  friend class FileDescriptorTables;
741
  friend class OneofDescriptor;
742
  friend class MethodDescriptor;
743
  friend class FileDescriptor;
744
};
745
746
PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(Descriptor, 152);
747
748
// Describes a single field of a message.  To get the descriptor for a given
749
// field, first get the Descriptor for the message in which it is defined,
750
// then call Descriptor::FindFieldByName().  To get a FieldDescriptor for
751
// an extension, do one of the following:
752
// - Get the Descriptor or FileDescriptor for its containing scope, then
753
//   call Descriptor::FindExtensionByName() or
754
//   FileDescriptor::FindExtensionByName().
755
// - Given a DescriptorPool, call DescriptorPool::FindExtensionByNumber() or
756
//   DescriptorPool::FindExtensionByPrintableName().
757
// Use DescriptorPool to construct your own descriptors.
758
class PROTOBUF_EXPORT FieldDescriptor : private internal::SymbolBase,
759
                                        public internal::FieldDescriptorLite {
760
 public:
761
  typedef FieldDescriptorProto Proto;
762
763
#ifndef SWIG
764
  FieldDescriptor(const FieldDescriptor&) = delete;
765
  FieldDescriptor& operator=(const FieldDescriptor&) = delete;
766
#endif
767
768
  // Identifies a field type.  0 is reserved for errors.  The order is weird
769
  // for historical reasons.  Types 12 and up are new in proto2.
770
  // Inherited from FieldDescriptorLite:
771
  // enum Type {
772
  //   TYPE_DOUBLE = 1,    // double, exactly eight bytes on the wire.
773
  //   TYPE_FLOAT = 2,     // float, exactly four bytes on the wire.
774
  //   TYPE_INT64 = 3,     // int64, varint on the wire.  Negative numbers
775
  //                       // take 10 bytes.  Use TYPE_SINT64 if negative
776
  //                       // values are likely.
777
  //   TYPE_UINT64 = 4,    // uint64, varint on the wire.
778
  //   TYPE_INT32 = 5,     // int32, varint on the wire.  Negative numbers
779
  //                       // take 10 bytes.  Use TYPE_SINT32 if negative
780
  //                       // values are likely.
781
  //   TYPE_FIXED64 = 6,   // uint64, exactly eight bytes on the wire.
782
  //   TYPE_FIXED32 = 7,   // uint32, exactly four bytes on the wire.
783
  //   TYPE_BOOL = 8,      // bool, varint on the wire.
784
  //   TYPE_STRING = 9,    // UTF-8 text.
785
  //   TYPE_GROUP = 10,    // Tag-delimited message.  Deprecated.
786
  //   TYPE_MESSAGE = 11,  // Length-delimited message.
787
788
  //   TYPE_BYTES = 12,     // Arbitrary byte array.
789
  //   TYPE_UINT32 = 13,    // uint32, varint on the wire
790
  //   TYPE_ENUM = 14,      // Enum, varint on the wire
791
  //   TYPE_SFIXED32 = 15,  // int32, exactly four bytes on the wire
792
  //   TYPE_SFIXED64 = 16,  // int64, exactly eight bytes on the wire
793
  //   TYPE_SINT32 = 17,    // int32, ZigZag-encoded varint on the wire
794
  //   TYPE_SINT64 = 18,    // int64, ZigZag-encoded varint on the wire
795
796
  //   MAX_TYPE = 18,  // Constant useful for defining lookup tables
797
  //                   // indexed by Type.
798
  // };
799
800
  // Specifies the C++ data type used to represent the field.  There is a
801
  // fixed mapping from Type to CppType where each Type maps to exactly one
802
  // CppType.  0 is reserved for errors.
803
  // Inherited from FieldDescriptorLite:
804
  // enum CppType {
805
  //   CPPTYPE_INT32 = 1,     // TYPE_INT32, TYPE_SINT32, TYPE_SFIXED32
806
  //   CPPTYPE_INT64 = 2,     // TYPE_INT64, TYPE_SINT64, TYPE_SFIXED64
807
  //   CPPTYPE_UINT32 = 3,    // TYPE_UINT32, TYPE_FIXED32
808
  //   CPPTYPE_UINT64 = 4,    // TYPE_UINT64, TYPE_FIXED64
809
  //   CPPTYPE_DOUBLE = 5,    // TYPE_DOUBLE
810
  //   CPPTYPE_FLOAT = 6,     // TYPE_FLOAT
811
  //   CPPTYPE_BOOL = 7,      // TYPE_BOOL
812
  //   CPPTYPE_ENUM = 8,      // TYPE_ENUM
813
  //   CPPTYPE_STRING = 9,    // TYPE_STRING, TYPE_BYTES
814
  //   CPPTYPE_MESSAGE = 10,  // TYPE_MESSAGE, TYPE_GROUP
815
816
  //   MAX_CPPTYPE = 10,  // Constant useful for defining lookup tables
817
  //                      // indexed by CppType.
818
  // };
819
820
  // Identifies whether the field is optional, required, or repeated.  0 is
821
  // reserved for errors.
822
  // Inherited from FieldDescriptorLite:
823
  // enum Label {
824
  //   LABEL_OPTIONAL = 1,  // optional
825
  //   LABEL_REQUIRED = 2,  // required
826
  //   LABEL_REPEATED = 3,  // repeated
827
828
  //   MAX_LABEL = 3,  // Constant useful for defining lookup tables
829
  //                   // indexed by Label.
830
  // };
831
832
  // Valid field numbers are positive integers up to kMaxNumber.
833
  static const int kMaxNumber = (1 << 29) - 1;
834
835
  // First field number reserved for the protocol buffer library implementation.
836
  // Users may not declare fields that use reserved numbers.
837
  static const int kFirstReservedNumber = 19000;
838
  // Last field number reserved for the protocol buffer library implementation.
839
  // Users may not declare fields that use reserved numbers.
840
  static const int kLastReservedNumber = 19999;
841
842
  // Name of this field within the message.
843
  internal::DescriptorStringView name() const;
844
  // Fully-qualified name of the field.
845
  internal::DescriptorStringView full_name() const;
846
  // JSON name of this field.
847
  internal::DescriptorStringView json_name() const;
848
849
  const FileDescriptor* file() const;  // File in which this field was defined.
850
  bool is_extension() const;           // Is this an extension field?
851
  int number() const;                  // Declared tag number.
852
853
  // Same as name() except converted to lower-case.  This (and especially the
854
  // FindFieldByLowercaseName() method) can be useful when parsing formats
855
  // which prefer to use lowercase naming style.  (Although, technically
856
  // field names should be lowercased anyway according to the protobuf style
857
  // guide, so this only makes a difference when dealing with old .proto files
858
  // which do not follow the guide.)
859
  internal::DescriptorStringView lowercase_name() const;
860
861
  // Same as name() except converted to camel-case.  In this conversion, any
862
  // time an underscore appears in the name, it is removed and the next
863
  // letter is capitalized.  Furthermore, the first letter of the name is
864
  // lower-cased.  Examples:
865
  //   FooBar -> fooBar
866
  //   foo_bar -> fooBar
867
  //   fooBar -> fooBar
868
  // This (and especially the FindFieldByCamelcaseName() method) can be useful
869
  // when parsing formats which prefer to use camel-case naming style.
870
  internal::DescriptorStringView camelcase_name() const;
871
872
  Type type() const;                  // Declared type of this field.
873
  const char* type_name() const;      // Name of the declared type.
874
  CppType cpp_type() const;           // C++ type of this field.
875
  const char* cpp_type_name() const;  // Name of the C++ type.
876
  Label label() const;                // optional/required/repeated
877
878
#ifndef SWIG
879
  CppStringType cpp_string_type() const;  // The C++ string type of this field.
880
#endif
881
882
  bool is_required() const;  // shorthand for label() == LABEL_REQUIRED
883
  bool is_optional() const;  // shorthand for label() == LABEL_OPTIONAL
884
  bool is_repeated() const;  // shorthand for label() == LABEL_REPEATED
885
  bool is_packable() const;  // shorthand for is_repeated() &&
886
                             //               IsTypePackable(type())
887
  bool is_map() const;       // shorthand for type() == TYPE_MESSAGE &&
888
                             // message_type()->options().map_entry()
889
890
  // Whether or not this field is packable and packed.  In proto2, packable
891
  // fields must have `packed = true` specified.  In proto3, all packable fields
892
  // are packed by default unless `packed = false` is specified.
893
  bool is_packed() const;
894
895
  // Returns true if this field tracks presence, ie. does the field
896
  // distinguish between "unset" and "present with default value."
897
  // This includes required, optional, and oneof fields. It excludes maps,
898
  // repeated fields, and singular proto3 fields without "optional".
899
  //
900
  // For fields where has_presence() == true, the return value of
901
  // Reflection::HasField() is semantically meaningful.
902
  bool has_presence() const;
903
904
  // Returns true if this TYPE_STRING-typed field requires UTF-8 validation on
905
  // parse.
906
  bool requires_utf8_validation() const;
907
908
  // Determines if the given enum field is treated as closed based on legacy
909
  // non-conformant behavior.
910
  //
911
  // Conformant behavior determines closedness based on the enum and
912
  // can be queried using EnumDescriptor::is_closed().
913
  //
914
  // Some runtimes currently have a quirk where non-closed enums are
915
  // treated as closed when used as the type of fields defined in a
916
  // `syntax = proto2;` file. This quirk is not present in all runtimes; as of
917
  // writing, we know that:
918
  //
919
  // - C++, Java, and C++-based Python share this quirk.
920
  // - UPB and UPB-based Python do not.
921
  // - PHP and Ruby treat all enums as open regardless of declaration.
922
  //
923
  // Care should be taken when using this function to respect the target
924
  // runtime's enum handling quirks.
925
  bool legacy_enum_field_treated_as_closed() const;
926
927
  // Index of this field within the message's field array, or the file or
928
  // extension scope's extensions array.
929
  int index() const;
930
931
  // Does this field have an explicitly-declared default value?
932
  bool has_default_value() const;
933
934
  // Whether the user has specified the json_name field option in the .proto
935
  // file.
936
  bool has_json_name() const;
937
938
  // Get the field default value if cpp_type() == CPPTYPE_INT32.  If no
939
  // explicit default was defined, the default is 0.
940
  int32_t default_value_int32_t() const;
941
0
  int32_t default_value_int32() const { return default_value_int32_t(); }
942
  // Get the field default value if cpp_type() == CPPTYPE_INT64.  If no
943
  // explicit default was defined, the default is 0.
944
  int64_t default_value_int64_t() const;
945
0
  int64_t default_value_int64() const { return default_value_int64_t(); }
946
  // Get the field default value if cpp_type() == CPPTYPE_UINT32.  If no
947
  // explicit default was defined, the default is 0.
948
  uint32_t default_value_uint32_t() const;
949
0
  uint32_t default_value_uint32() const { return default_value_uint32_t(); }
950
  // Get the field default value if cpp_type() == CPPTYPE_UINT64.  If no
951
  // explicit default was defined, the default is 0.
952
  uint64_t default_value_uint64_t() const;
953
0
  uint64_t default_value_uint64() const { return default_value_uint64_t(); }
954
  // Get the field default value if cpp_type() == CPPTYPE_FLOAT.  If no
955
  // explicit default was defined, the default is 0.0.
956
  float default_value_float() const;
957
  // Get the field default value if cpp_type() == CPPTYPE_DOUBLE.  If no
958
  // explicit default was defined, the default is 0.0.
959
  double default_value_double() const;
960
  // Get the field default value if cpp_type() == CPPTYPE_BOOL.  If no
961
  // explicit default was defined, the default is false.
962
  bool default_value_bool() const;
963
  // Get the field default value if cpp_type() == CPPTYPE_ENUM.  If no
964
  // explicit default was defined, the default is the first value defined
965
  // in the enum type (all enum types are required to have at least one value).
966
  // This never returns nullptr.
967
  const EnumValueDescriptor* default_value_enum() const;
968
  // Get the field default value if cpp_type() == CPPTYPE_STRING.  If no
969
  // explicit default was defined, the default is the empty string.
970
  internal::DescriptorStringView default_value_string() const;
971
972
  // The Descriptor for the message of which this is a field.  For extensions,
973
  // this is the extended type.  Never nullptr.
974
  const Descriptor* containing_type() const;
975
976
  // If the field is a member of a oneof, this is the one, otherwise this is
977
  // nullptr.
978
  const OneofDescriptor* containing_oneof() const;
979
980
  // If the field is a member of a non-synthetic oneof, returns the descriptor
981
  // for the oneof, otherwise returns nullptr.
982
  const OneofDescriptor* real_containing_oneof() const;
983
984
  // If the field is a member of a oneof, returns the index in that oneof.
985
  int index_in_oneof() const;
986
987
  // An extension may be declared within the scope of another message.  If this
988
  // field is an extension (is_extension() is true), then extension_scope()
989
  // returns that message, or nullptr if the extension was declared at global
990
  // scope.  If this is not an extension, extension_scope() is undefined (may
991
  // assert-fail).
992
  const Descriptor* extension_scope() const;
993
994
  // If type is TYPE_MESSAGE or TYPE_GROUP, returns a descriptor for the
995
  // message or the group type.  Otherwise, returns null.
996
  const Descriptor* message_type() const;
997
  // If type is TYPE_ENUM, returns a descriptor for the enum.  Otherwise,
998
  // returns null.
999
  const EnumDescriptor* enum_type() const;
1000
1001
  // Get the FieldOptions for this field.  This includes things listed in
1002
  // square brackets after the field definition.  E.g., the field:
1003
  //   optional string text = 1 [ctype=CORD];
1004
  // has the "ctype" option set.  Allowed options are defined by FieldOptions in
1005
  // descriptor.proto, and any available extensions of that message.
1006
  const FieldOptions& options() const;
1007
1008
  // See Descriptor::CopyTo().
1009
  void CopyTo(FieldDescriptorProto* proto) const;
1010
1011
  // See Descriptor::DebugString().
1012
  std::string DebugString() const;
1013
1014
  // See Descriptor::DebugStringWithOptions().
1015
  std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1016
1017
  // Allows formatting with absl and gtest.
1018
  template <typename Sink>
1019
  friend void AbslStringify(Sink& sink, const FieldDescriptor& d) {
1020
    absl::Format(&sink, "%s", d.DebugString());
1021
  }
1022
1023
  // Helper method to get the CppType for a particular Type.
1024
  static CppType TypeToCppType(Type type);
1025
1026
  // Helper method to get the name of a Type.
1027
  static const char* TypeName(Type type);
1028
1029
  // Helper method to get the name of a CppType.
1030
  static const char* CppTypeName(CppType cpp_type);
1031
1032
  // Return true iff [packed = true] is valid for fields of this type.
1033
  static inline bool IsTypePackable(Type field_type);
1034
1035
  // Returns full_name() except if the field is a MessageSet extension,
1036
  // in which case it returns the full_name() of the containing message type
1037
  // for backwards compatibility with proto1.
1038
  //
1039
  // A MessageSet extension is defined as an optional message extension
1040
  // whose containing type has the message_set_wire_format option set.
1041
  // This should be true of extensions of google.protobuf.bridge.MessageSet;
1042
  // by convention, such extensions are named "message_set_extension".
1043
  //
1044
  // The opposite operation (looking up an extension's FieldDescriptor given
1045
  // its printable name) can be accomplished with
1046
  //     message->file()->pool()->FindExtensionByPrintableName(message, name)
1047
  // where the extension extends "message".
1048
  internal::DescriptorStringView PrintableNameForExtension() const;
1049
1050
  // Source Location ---------------------------------------------------
1051
1052
  // Updates |*out_location| to the source location of the complete
1053
  // extent of this field declaration.  Returns false and leaves
1054
  // |*out_location| unchanged iff location information was not available.
1055
  bool GetSourceLocation(SourceLocation* out_location) const;
1056
1057
 private:
1058
  friend class Symbol;
1059
  typedef FieldOptions OptionsType;
1060
1061
  // Allows access to GetLocationPath for annotations.
1062
  friend class io::Printer;
1063
  friend class compiler::cpp::Formatter;
1064
  friend class Reflection;
1065
  friend class FieldDescriptorLegacy;
1066
  friend const std::string& internal::DefaultValueStringAsString(
1067
      const FieldDescriptor* field);
1068
1069
  // Returns true if this field was syntactically written with "optional" in the
1070
  // .proto file. Excludes singular proto3 fields that do not have a label.
1071
  bool has_optional_keyword() const;
1072
1073
  // Get the merged features that apply to this field.  These are specified in
1074
  // the .proto file through the feature options in the message definition.
1075
  // Allowed features are defined by Features in descriptor.proto, along with
1076
  // any backend-specific extensions to it.
1077
0
  const FeatureSet& features() const { return *merged_features_; }
1078
  friend class internal::InternalFeatureHelper;
1079
1080
  // Fill the json_name field of FieldDescriptorProto.
1081
  void CopyJsonNameTo(FieldDescriptorProto* proto) const;
1082
1083
  // See Descriptor::DebugString().
1084
  void DebugString(int depth, std::string* contents,
1085
                   const DebugStringOptions& options) const;
1086
1087
  // formats the default value appropriately and returns it as a string.
1088
  // Must have a default value to call this. If quote_string_type is true, then
1089
  // types of CPPTYPE_STRING will be surrounded by quotes and CEscaped.
1090
  std::string DefaultValueAsString(bool quote_string_type) const;
1091
1092
  // Helper function that returns the field type name for DebugString.
1093
  std::string FieldTypeNameDebugString() const;
1094
1095
  // Walks up the descriptor tree to generate the source location path
1096
  // to this descriptor from the file root.
1097
  void GetLocationPath(std::vector<int>* output) const;
1098
1099
  // Returns true if this is a map message type.
1100
  bool is_map_message_type() const;
1101
1102
  bool has_default_value_ : 1;
1103
  bool proto3_optional_ : 1;
1104
  // Whether the user has specified the json_name field option in the .proto
1105
  // file.
1106
  bool has_json_name_ : 1;
1107
  bool is_extension_ : 1;
1108
  bool is_oneof_ : 1;
1109
  bool is_repeated_ : 1;  // Redundant with label_, but it is queried a lot.
1110
1111
  // Actually a `Label` but stored as uint8_t to save space.
1112
  uint8_t label_ : 2;
1113
1114
  // Actually a `Type`, but stored as uint8_t to save space.
1115
  uint8_t type_;
1116
1117
  // Logically:
1118
  //   all_names_ = [name, full_name, lower, camel, json]
1119
  // However:
1120
  //   duplicates will be omitted, so lower/camel/json might be in the same
1121
  //   position.
1122
  // We store the true offset for each name here, and the bit width must be
1123
  // large enough to account for the worst case where all names are present.
1124
  uint8_t lowercase_name_index_ : 2;
1125
  uint8_t camelcase_name_index_ : 2;
1126
  uint8_t json_name_index_ : 3;
1127
1128
  // Can be calculated from containing_oneof(), but we cache it for performance.
1129
  // Located here for bitpacking.
1130
  bool in_real_oneof_ : 1;
1131
1132
  // Sadly, `number_` located here to reduce padding. Unrelated to all_names_
1133
  // and its indices above.
1134
  int number_;
1135
  const std::string* all_names_;
1136
  const FileDescriptor* file_;
1137
1138
  // The once_flag is followed by a NUL terminated string for the type name and
1139
  // enum default value (or empty string if no default enum).
1140
  absl::once_flag* type_once_;
1141
  static void TypeOnceInit(const FieldDescriptor* to_init);
1142
  void InternalTypeOnceInit() const;
1143
  const Descriptor* containing_type_;
1144
  union {
1145
    const OneofDescriptor* containing_oneof;
1146
    const Descriptor* extension_scope;
1147
  } scope_;
1148
  union {
1149
    mutable const Descriptor* message_type;
1150
    mutable const EnumDescriptor* enum_type;
1151
  } type_descriptor_;
1152
  const FieldOptions* options_;
1153
  const FeatureSet* proto_features_;
1154
  const FeatureSet* merged_features_;
1155
  // IMPORTANT:  If you add a new field, make sure to search for all instances
1156
  // of Allocate<FieldDescriptor>() and AllocateArray<FieldDescriptor>() in
1157
  // descriptor.cc and update them to initialize the field.
1158
1159
  union {
1160
    int32_t default_value_int32_t_;
1161
    int64_t default_value_int64_t_;
1162
    uint32_t default_value_uint32_t_;
1163
    uint64_t default_value_uint64_t_;
1164
    float default_value_float_;
1165
    double default_value_double_;
1166
    bool default_value_bool_;
1167
1168
    mutable const EnumValueDescriptor* default_value_enum_;
1169
    const std::string* default_value_string_;
1170
    mutable std::atomic<const Message*> default_generated_instance_;
1171
  };
1172
1173
  static const CppType kTypeToCppTypeMap[MAX_TYPE + 1];
1174
1175
  static const char* const kTypeToName[MAX_TYPE + 1];
1176
1177
  static const char* const kCppTypeToName[MAX_CPPTYPE + 1];
1178
1179
  static const char* const kLabelToName[MAX_LABEL + 1];
1180
1181
  // Must be constructed using DescriptorPool.
1182
  FieldDescriptor();
1183
  friend class DescriptorBuilder;
1184
  friend class FileDescriptor;
1185
  friend class Descriptor;
1186
  friend class OneofDescriptor;
1187
};
1188
1189
PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(FieldDescriptor, 88);
1190
1191
// Describes a oneof defined in a message type.
1192
class PROTOBUF_EXPORT OneofDescriptor : private internal::SymbolBase {
1193
 public:
1194
  typedef OneofDescriptorProto Proto;
1195
1196
#ifndef SWIG
1197
  OneofDescriptor(const OneofDescriptor&) = delete;
1198
  OneofDescriptor& operator=(const OneofDescriptor&) = delete;
1199
#endif
1200
1201
  // Name of this oneof.
1202
  internal::DescriptorStringView name() const;
1203
  // Fully-qualified name of the oneof.
1204
  internal::DescriptorStringView full_name() const;
1205
1206
  // Index of this oneof within the message's oneof array.
1207
  int index() const;
1208
1209
  // The .proto file in which this oneof was defined.  Never nullptr.
1210
  const FileDescriptor* file() const;
1211
  // The Descriptor for the message containing this oneof.
1212
  const Descriptor* containing_type() const;
1213
1214
  // The number of (non-extension) fields which are members of this oneof.
1215
  int field_count() const;
1216
  // Get a member of this oneof, in the order in which they were declared in the
1217
  // .proto file.  Does not include extensions.
1218
  const FieldDescriptor* field(int index) const;
1219
1220
  const OneofOptions& options() const;
1221
1222
  // See Descriptor::CopyTo().
1223
  void CopyTo(OneofDescriptorProto* proto) const;
1224
1225
  // See Descriptor::DebugString().
1226
  std::string DebugString() const;
1227
1228
  // See Descriptor::DebugStringWithOptions().
1229
  std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1230
1231
  // Allows formatting with absl and gtest.
1232
  template <typename Sink>
1233
  friend void AbslStringify(Sink& sink, const OneofDescriptor& d) {
1234
    absl::Format(&sink, "%s", d.DebugString());
1235
  }
1236
1237
  // Source Location ---------------------------------------------------
1238
1239
  // Updates |*out_location| to the source location of the complete
1240
  // extent of this oneof declaration.  Returns false and leaves
1241
  // |*out_location| unchanged iff location information was not available.
1242
  bool GetSourceLocation(SourceLocation* out_location) const;
1243
1244
 private:
1245
  friend class Symbol;
1246
  typedef OneofOptions OptionsType;
1247
1248
  // Allows access to GetLocationPath for annotations.
1249
  friend class io::Printer;
1250
  friend class compiler::cpp::Formatter;
1251
  friend class OneofDescriptorLegacy;
1252
1253
  // Returns whether this oneof was inserted by the compiler to wrap a proto3
1254
  // optional field. If this returns true, code generators should *not* emit it.
1255
  bool is_synthetic() const;
1256
1257
  // Get the merged features that apply to this oneof.  These are specified in
1258
  // the .proto file through the feature options in the oneof definition.
1259
  // Allowed features are defined by Features in descriptor.proto, along with
1260
  // any backend-specific extensions to it.
1261
0
  const FeatureSet& features() const { return *merged_features_; }
1262
  friend class internal::InternalFeatureHelper;
1263
1264
  // See Descriptor::DebugString().
1265
  void DebugString(int depth, std::string* contents,
1266
                   const DebugStringOptions& options) const;
1267
1268
  // Walks up the descriptor tree to generate the source location path
1269
  // to this descriptor from the file root.
1270
  void GetLocationPath(std::vector<int>* output) const;
1271
1272
  int field_count_;
1273
1274
  // all_names_ = [name, full_name]
1275
  const std::string* all_names_;
1276
  const Descriptor* containing_type_;
1277
  const OneofOptions* options_;
1278
  const FeatureSet* proto_features_;
1279
  const FeatureSet* merged_features_;
1280
  const FieldDescriptor* fields_;
1281
1282
  // IMPORTANT:  If you add a new field, make sure to search for all instances
1283
  // of Allocate<OneofDescriptor>() and AllocateArray<OneofDescriptor>()
1284
  // in descriptor.cc and update them to initialize the field.
1285
1286
  // Must be constructed using DescriptorPool.
1287
  OneofDescriptor();
1288
  friend class DescriptorBuilder;
1289
  friend class Descriptor;
1290
  friend class FieldDescriptor;
1291
  friend class Reflection;
1292
};
1293
1294
PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(OneofDescriptor, 56);
1295
1296
// Describes an enum type defined in a .proto file.  To get the EnumDescriptor
1297
// for a generated enum type, call TypeName_descriptor().  Use DescriptorPool
1298
// to construct your own descriptors.
1299
class PROTOBUF_EXPORT EnumDescriptor : private internal::SymbolBase {
1300
 public:
1301
  typedef EnumDescriptorProto Proto;
1302
1303
#ifndef SWIG
1304
  EnumDescriptor(const EnumDescriptor&) = delete;
1305
  EnumDescriptor& operator=(const EnumDescriptor&) = delete;
1306
#endif
1307
1308
  // The name of this enum type in the containing scope.
1309
  internal::DescriptorStringView name() const;
1310
1311
  // The fully-qualified name of the enum type, scope delimited by periods.
1312
  internal::DescriptorStringView full_name() const;
1313
1314
  // Index of this enum within the file or containing message's enum array.
1315
  int index() const;
1316
1317
  // The .proto file in which this enum type was defined.  Never nullptr.
1318
  const FileDescriptor* file() const;
1319
1320
  // The number of values for this EnumDescriptor.  Guaranteed to be greater
1321
  // than zero.
1322
  int value_count() const;
1323
  // Gets a value by index, where 0 <= index < value_count().
1324
  // These are returned in the order they were defined in the .proto file.
1325
  const EnumValueDescriptor* value(int index) const;
1326
1327
  // Looks up a value by name.  Returns nullptr if no such value exists.
1328
  const EnumValueDescriptor* FindValueByName(absl::string_view name) const;
1329
  // Looks up a value by number.  Returns nullptr if no such value exists.  If
1330
  // multiple values have this number, the first one defined is returned.
1331
  const EnumValueDescriptor* FindValueByNumber(int number) const;
1332
1333
  // If this enum type is nested in a message type, this is that message type.
1334
  // Otherwise, nullptr.
1335
  const Descriptor* containing_type() const;
1336
1337
  // Get options for this enum type.  These are specified in the .proto file by
1338
  // placing lines like "option foo = 1234;" in the enum definition.  Allowed
1339
  // options are defined by EnumOptions in descriptor.proto, and any available
1340
  // extensions of that message.
1341
  const EnumOptions& options() const;
1342
1343
  // See Descriptor::CopyTo().
1344
  void CopyTo(EnumDescriptorProto* proto) const;
1345
1346
  // See Descriptor::DebugString().
1347
  std::string DebugString() const;
1348
1349
  // See Descriptor::DebugStringWithOptions().
1350
  std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1351
1352
  // Allows formatting with absl and gtest.
1353
  template <typename Sink>
1354
  friend void AbslStringify(Sink& sink, const EnumDescriptor& d) {
1355
    absl::Format(&sink, "%s", d.DebugString());
1356
  }
1357
1358
  // Returns true if this is a placeholder for an unknown enum. This will
1359
  // only be the case if this descriptor comes from a DescriptorPool
1360
  // with AllowUnknownDependencies() set.
1361
  bool is_placeholder() const;
1362
1363
  // Returns true whether this is a "closed" enum, meaning that it:
1364
  // - Has a fixed set of values, rather than being equivalent to an int32.
1365
  // - Encountering values not in this set causes them to be treated as unknown
1366
  //   fields.
1367
  // - The first value (i.e., the default) may be nonzero.
1368
  //
1369
  // WARNING: Some runtimes currently have a quirk where non-closed enums are
1370
  // treated as closed when used as the type of fields defined in a
1371
  // `syntax = proto2;` file. This quirk is not present in all runtimes; as of
1372
  // writing, we know that:
1373
  //
1374
  // - C++, Java, and C++-based Python share this quirk.
1375
  // - UPB and UPB-based Python do not.
1376
  // - PHP and Ruby treat all enums as open regardless of declaration.
1377
  //
1378
  // Care should be taken when using this function to respect the target
1379
  // runtime's enum handling quirks.
1380
  bool is_closed() const;
1381
1382
  // Reserved fields -------------------------------------------------
1383
1384
  // A range of reserved field numbers.
1385
  struct ReservedRange {
1386
    int start;  // inclusive
1387
    int end;    // inclusive
1388
  };
1389
1390
  // The number of reserved ranges in this message type.
1391
  int reserved_range_count() const;
1392
  // Gets an reserved range by index, where 0 <= index <
1393
  // reserved_range_count(). These are returned in the order they were defined
1394
  // in the .proto file.
1395
  const EnumDescriptor::ReservedRange* reserved_range(int index) const;
1396
1397
  // Returns true if the number is in one of the reserved ranges.
1398
  bool IsReservedNumber(int number) const;
1399
1400
  // Returns nullptr if no reserved range contains the given number.
1401
  const EnumDescriptor::ReservedRange* FindReservedRangeContainingNumber(
1402
      int number) const;
1403
1404
  // The number of reserved field names in this message type.
1405
  int reserved_name_count() const;
1406
1407
  // Gets a reserved name by index, where 0 <= index < reserved_name_count().
1408
  internal::DescriptorStringView reserved_name(int index) const;
1409
1410
  // Returns true if the field name is reserved.
1411
  bool IsReservedName(absl::string_view name) const;
1412
1413
  // Source Location ---------------------------------------------------
1414
1415
  // Updates |*out_location| to the source location of the complete
1416
  // extent of this enum declaration.  Returns false and leaves
1417
  // |*out_location| unchanged iff location information was not available.
1418
  bool GetSourceLocation(SourceLocation* out_location) const;
1419
1420
 private:
1421
  friend class Symbol;
1422
  friend bool internal::IsEnumFullySequential(const EnumDescriptor* enum_desc);
1423
  typedef EnumOptions OptionsType;
1424
1425
  // Allows access to GetLocationPath for annotations.
1426
  friend class io::Printer;
1427
  friend class compiler::cpp::Formatter;
1428
1429
  // Allow access to FindValueByNumberCreatingIfUnknown.
1430
  friend class descriptor_unittest::DescriptorTest;
1431
1432
  // Get the merged features that apply to this enum type.  These are specified
1433
  // in the .proto file through the feature options in the message definition.
1434
  // Allowed features are defined by Features in descriptor.proto, along with
1435
  // any backend-specific extensions to it.
1436
0
  const FeatureSet& features() const { return *merged_features_; }
1437
  friend class internal::InternalFeatureHelper;
1438
1439
  // Looks up a value by number.  If the value does not exist, dynamically
1440
  // creates a new EnumValueDescriptor for that value, assuming that it was
1441
  // unknown. If a new descriptor is created, this is done in a thread-safe way,
1442
  // and future calls will return the same value descriptor pointer.
1443
  //
1444
  // This is private but is used by Reflection (which is friended below) to
1445
  // return a valid EnumValueDescriptor from GetEnum() when this feature is
1446
  // enabled.
1447
  const EnumValueDescriptor* FindValueByNumberCreatingIfUnknown(
1448
      int number) const;
1449
1450
  // See Descriptor::DebugString().
1451
  void DebugString(int depth, std::string* contents,
1452
                   const DebugStringOptions& options) const;
1453
1454
  // Walks up the descriptor tree to generate the source location path
1455
  // to this descriptor from the file root.
1456
  void GetLocationPath(std::vector<int>* output) const;
1457
1458
  // True if this is a placeholder for an unknown type.
1459
  bool is_placeholder_ : 1;
1460
  // True if this is a placeholder and the type name wasn't fully-qualified.
1461
  bool is_unqualified_placeholder_ : 1;
1462
1463
  // This points to the last value _index_ that is part of the sequence starting
1464
  // with the first label, where
1465
  //   `enum->value(i)->number() == enum->value(0)->number() + i`
1466
  // We measure relative to the first label to adapt to enum labels starting at
1467
  // 0 or 1.
1468
  // Uses 16-bit to avoid extra padding. Unlikely to have more than 2^15
1469
  // sequentially numbered labels in an enum.
1470
  int16_t sequential_value_limit_;
1471
1472
  int value_count_;
1473
1474
  // all_names_ = [name, full_name]
1475
  const std::string* all_names_;
1476
  const FileDescriptor* file_;
1477
  const Descriptor* containing_type_;
1478
  const EnumOptions* options_;
1479
  const FeatureSet* proto_features_;
1480
  const FeatureSet* merged_features_;
1481
  EnumValueDescriptor* values_;
1482
1483
  int reserved_range_count_;
1484
  int reserved_name_count_;
1485
  EnumDescriptor::ReservedRange* reserved_ranges_;
1486
  const std::string** reserved_names_;
1487
1488
  // IMPORTANT:  If you add a new field, make sure to search for all instances
1489
  // of Allocate<EnumDescriptor>() and AllocateArray<EnumDescriptor>() in
1490
  // descriptor.cc and update them to initialize the field.
1491
1492
  // Must be constructed using DescriptorPool.
1493
  EnumDescriptor();
1494
  friend class DescriptorBuilder;
1495
  friend class Descriptor;
1496
  friend class FieldDescriptor;
1497
  friend class FileDescriptorTables;
1498
  friend class EnumValueDescriptor;
1499
  friend class FileDescriptor;
1500
  friend class DescriptorPool;
1501
  friend class Reflection;
1502
};
1503
1504
PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(EnumDescriptor, 88);
1505
1506
// Describes an individual enum constant of a particular type.  To get the
1507
// EnumValueDescriptor for a given enum value, first get the EnumDescriptor
1508
// for its type, then use EnumDescriptor::FindValueByName() or
1509
// EnumDescriptor::FindValueByNumber().  Use DescriptorPool to construct
1510
// your own descriptors.
1511
class PROTOBUF_EXPORT EnumValueDescriptor : private internal::SymbolBaseN<0>,
1512
                                            private internal::SymbolBaseN<1> {
1513
 public:
1514
  typedef EnumValueDescriptorProto Proto;
1515
1516
#ifndef SWIG
1517
  EnumValueDescriptor(const EnumValueDescriptor&) = delete;
1518
  EnumValueDescriptor& operator=(const EnumValueDescriptor&) = delete;
1519
#endif
1520
1521
  internal::DescriptorStringView name() const;  // Name of this enum constant.
1522
  int index() const;                // Index within the enums's Descriptor.
1523
  int number() const;               // Numeric value of this enum constant.
1524
1525
  // The full_name of an enum value is a sibling symbol of the enum type.
1526
  // e.g. the full name of FieldDescriptorProto::TYPE_INT32 is actually
1527
  // "google.protobuf.FieldDescriptorProto.TYPE_INT32", NOT
1528
  // "google.protobuf.FieldDescriptorProto.Type.TYPE_INT32".  This is to conform
1529
  // with C++ scoping rules for enums.
1530
  internal::DescriptorStringView full_name() const;
1531
1532
  // The .proto file in which this value was defined.  Never nullptr.
1533
  const FileDescriptor* file() const;
1534
  // The type of this value.  Never nullptr.
1535
  const EnumDescriptor* type() const;
1536
1537
  // Get options for this enum value.  These are specified in the .proto file by
1538
  // adding text like "[foo = 1234]" after an enum value definition.  Allowed
1539
  // options are defined by EnumValueOptions in descriptor.proto, and any
1540
  // available extensions of that message.
1541
  const EnumValueOptions& options() const;
1542
1543
  // See Descriptor::CopyTo().
1544
  void CopyTo(EnumValueDescriptorProto* proto) const;
1545
1546
  // See Descriptor::DebugString().
1547
  std::string DebugString() const;
1548
1549
  // See Descriptor::DebugStringWithOptions().
1550
  std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1551
1552
  // Allows formatting with absl and gtest.
1553
  template <typename Sink>
1554
  friend void AbslStringify(Sink& sink, const EnumValueDescriptor& d) {
1555
    absl::Format(&sink, "%s", d.DebugString());
1556
  }
1557
1558
  // Source Location ---------------------------------------------------
1559
1560
  // Updates |*out_location| to the source location of the complete
1561
  // extent of this enum value declaration.  Returns false and leaves
1562
  // |*out_location| unchanged iff location information was not available.
1563
  bool GetSourceLocation(SourceLocation* out_location) const;
1564
1565
 private:
1566
  friend class Symbol;
1567
  typedef EnumValueOptions OptionsType;
1568
1569
  // Allows access to GetLocationPath for annotations.
1570
  friend class io::Printer;
1571
  friend class compiler::cpp::Formatter;
1572
  friend const std::string& internal::NameOfEnumAsString(
1573
      const EnumValueDescriptor* descriptor);
1574
1575
  // Get the merged features that apply to this enum value.  These are specified
1576
  // in the .proto file through the feature options in the message definition.
1577
  // Allowed features are defined by Features in descriptor.proto, along with
1578
  // any backend-specific extensions to it.
1579
0
  const FeatureSet& features() const { return *merged_features_; }
1580
  friend class internal::InternalFeatureHelper;
1581
1582
  // See Descriptor::DebugString().
1583
  void DebugString(int depth, std::string* contents,
1584
                   const DebugStringOptions& options) const;
1585
1586
  // Walks up the descriptor tree to generate the source location path
1587
  // to this descriptor from the file root.
1588
  void GetLocationPath(std::vector<int>* output) const;
1589
1590
  int number_;
1591
  // all_names_ = [name, full_name]
1592
  const std::string* all_names_;
1593
  const EnumDescriptor* type_;
1594
  const EnumValueOptions* options_;
1595
  const FeatureSet* proto_features_;
1596
  const FeatureSet* merged_features_;
1597
  // IMPORTANT:  If you add a new field, make sure to search for all instances
1598
  // of Allocate<EnumValueDescriptor>() and AllocateArray<EnumValueDescriptor>()
1599
  // in descriptor.cc and update them to initialize the field.
1600
1601
  // Must be constructed using DescriptorPool.
1602
  EnumValueDescriptor();
1603
  friend class DescriptorBuilder;
1604
  friend class EnumDescriptor;
1605
  friend class DescriptorPool;
1606
  friend class FileDescriptorTables;
1607
  friend class Reflection;
1608
};
1609
1610
PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(EnumValueDescriptor, 48);
1611
1612
// Describes an RPC service. Use DescriptorPool to construct your own
1613
// descriptors.
1614
class PROTOBUF_EXPORT ServiceDescriptor : private internal::SymbolBase {
1615
 public:
1616
  typedef ServiceDescriptorProto Proto;
1617
1618
#ifndef SWIG
1619
  ServiceDescriptor(const ServiceDescriptor&) = delete;
1620
  ServiceDescriptor& operator=(const ServiceDescriptor&) = delete;
1621
#endif
1622
1623
  // The name of the service, not including its containing scope.
1624
  internal::DescriptorStringView name() const;
1625
  // The fully-qualified name of the service, scope delimited by periods.
1626
  internal::DescriptorStringView full_name() const;
1627
  // Index of this service within the file's services array.
1628
  int index() const;
1629
1630
  // The .proto file in which this service was defined.  Never nullptr.
1631
  const FileDescriptor* file() const;
1632
1633
  // Get options for this service type.  These are specified in the .proto file
1634
  // by placing lines like "option foo = 1234;" in the service definition.
1635
  // Allowed options are defined by ServiceOptions in descriptor.proto, and any
1636
  // available extensions of that message.
1637
  const ServiceOptions& options() const;
1638
1639
  // The number of methods this service defines.
1640
  int method_count() const;
1641
  // Gets a MethodDescriptor by index, where 0 <= index < method_count().
1642
  // These are returned in the order they were defined in the .proto file.
1643
  const MethodDescriptor* method(int index) const;
1644
1645
  // Look up a MethodDescriptor by name.
1646
  const MethodDescriptor* FindMethodByName(absl::string_view name) const;
1647
1648
  // See Descriptor::CopyTo().
1649
  void CopyTo(ServiceDescriptorProto* proto) const;
1650
1651
  // See Descriptor::DebugString().
1652
  std::string DebugString() const;
1653
1654
  // See Descriptor::DebugStringWithOptions().
1655
  std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1656
1657
  // Allows formatting with absl and gtest.
1658
  template <typename Sink>
1659
  friend void AbslStringify(Sink& sink, const ServiceDescriptor& d) {
1660
    absl::Format(&sink, "%s", d.DebugString());
1661
  }
1662
1663
  // Source Location ---------------------------------------------------
1664
1665
  // Updates |*out_location| to the source location of the complete
1666
  // extent of this service declaration.  Returns false and leaves
1667
  // |*out_location| unchanged iff location information was not available.
1668
  bool GetSourceLocation(SourceLocation* out_location) const;
1669
1670
 private:
1671
  friend class Symbol;
1672
  typedef ServiceOptions OptionsType;
1673
1674
  // Allows access to GetLocationPath for annotations.
1675
  friend class io::Printer;
1676
  friend class compiler::cpp::Formatter;
1677
1678
  // Get the merged features that apply to this service type.  These are
1679
  // specified in the .proto file through the feature options in the service
1680
  // definition. Allowed features are defined by Features in descriptor.proto,
1681
  // along with any backend-specific extensions to it.
1682
0
  const FeatureSet& features() const { return *merged_features_; }
1683
  friend class internal::InternalFeatureHelper;
1684
1685
  // See Descriptor::DebugString().
1686
  void DebugString(std::string* contents,
1687
                   const DebugStringOptions& options) const;
1688
1689
  // Walks up the descriptor tree to generate the source location path
1690
  // to this descriptor from the file root.
1691
  void GetLocationPath(std::vector<int>* output) const;
1692
1693
  // all_names_ = [name, full_name]
1694
  const std::string* all_names_;
1695
  const FileDescriptor* file_;
1696
  const ServiceOptions* options_;
1697
  const FeatureSet* proto_features_;
1698
  const FeatureSet* merged_features_;
1699
  MethodDescriptor* methods_;
1700
  int method_count_;
1701
  // IMPORTANT:  If you add a new field, make sure to search for all instances
1702
  // of Allocate<ServiceDescriptor>() and AllocateArray<ServiceDescriptor>() in
1703
  // descriptor.cc and update them to initialize the field.
1704
1705
  // Must be constructed using DescriptorPool.
1706
  ServiceDescriptor();
1707
  friend class DescriptorBuilder;
1708
  friend class FileDescriptor;
1709
  friend class MethodDescriptor;
1710
};
1711
1712
PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(ServiceDescriptor, 64);
1713
1714
// Describes an individual service method.  To obtain a MethodDescriptor given
1715
// a service, first get its ServiceDescriptor, then call
1716
// ServiceDescriptor::FindMethodByName().  Use DescriptorPool to construct your
1717
// own descriptors.
1718
class PROTOBUF_EXPORT MethodDescriptor : private internal::SymbolBase {
1719
 public:
1720
  typedef MethodDescriptorProto Proto;
1721
1722
#ifndef SWIG
1723
  MethodDescriptor(const MethodDescriptor&) = delete;
1724
  MethodDescriptor& operator=(const MethodDescriptor&) = delete;
1725
#endif
1726
1727
  // Name of this method, not including containing scope.
1728
  internal::DescriptorStringView name() const;
1729
  // The fully-qualified name of the method, scope delimited by periods.
1730
  internal::DescriptorStringView full_name() const;
1731
  // Index within the service's Descriptor.
1732
  int index() const;
1733
1734
  // The .proto file in which this method was defined.  Never nullptr.
1735
  const FileDescriptor* file() const;
1736
  // Gets the service to which this method belongs.  Never nullptr.
1737
  const ServiceDescriptor* service() const;
1738
1739
  // Gets the type of protocol message which this method accepts as input.
1740
  const Descriptor* input_type() const;
1741
  // Gets the type of protocol message which this message produces as output.
1742
  const Descriptor* output_type() const;
1743
1744
  // Gets whether the client streams multiple requests.
1745
  bool client_streaming() const;
1746
  // Gets whether the server streams multiple responses.
1747
  bool server_streaming() const;
1748
1749
  // Get options for this method.  These are specified in the .proto file by
1750
  // placing lines like "option foo = 1234;" in curly-braces after a method
1751
  // declaration.  Allowed options are defined by MethodOptions in
1752
  // descriptor.proto, and any available extensions of that message.
1753
  const MethodOptions& options() const;
1754
1755
  // See Descriptor::CopyTo().
1756
  void CopyTo(MethodDescriptorProto* proto) const;
1757
1758
  // See Descriptor::DebugString().
1759
  std::string DebugString() const;
1760
1761
  // See Descriptor::DebugStringWithOptions().
1762
  std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1763
1764
  // Allows formatting with absl and gtest.
1765
  template <typename Sink>
1766
  friend void AbslStringify(Sink& sink, const MethodDescriptor& d) {
1767
    absl::Format(&sink, "%s", d.DebugString());
1768
  }
1769
1770
  // Source Location ---------------------------------------------------
1771
1772
  // Updates |*out_location| to the source location of the complete
1773
  // extent of this method declaration.  Returns false and leaves
1774
  // |*out_location| unchanged iff location information was not available.
1775
  bool GetSourceLocation(SourceLocation* out_location) const;
1776
1777
 private:
1778
  friend class Symbol;
1779
  typedef MethodOptions OptionsType;
1780
1781
  // Allows access to GetLocationPath for annotations.
1782
  friend class io::Printer;
1783
  friend class compiler::cpp::Formatter;
1784
1785
  // Get the merged features that apply to this method.  These are specified in
1786
  // the .proto file through the feature options in the method definition.
1787
  // Allowed features are defined by Features in descriptor.proto, along with
1788
  // any backend-specific extensions to it.
1789
0
  const FeatureSet& features() const { return *merged_features_; }
1790
  friend class internal::InternalFeatureHelper;
1791
1792
  // See Descriptor::DebugString().
1793
  void DebugString(int depth, std::string* contents,
1794
                   const DebugStringOptions& options) const;
1795
1796
  // Walks up the descriptor tree to generate the source location path
1797
  // to this descriptor from the file root.
1798
  void GetLocationPath(std::vector<int>* output) const;
1799
1800
  bool client_streaming_;
1801
  bool server_streaming_;
1802
  // all_names_ = [name, full_name]
1803
  const std::string* all_names_;
1804
  const ServiceDescriptor* service_;
1805
  mutable internal::LazyDescriptor input_type_;
1806
  mutable internal::LazyDescriptor output_type_;
1807
  const MethodOptions* options_;
1808
  const FeatureSet* proto_features_;
1809
  const FeatureSet* merged_features_;
1810
  // IMPORTANT:  If you add a new field, make sure to search for all instances
1811
  // of Allocate<MethodDescriptor>() and AllocateArray<MethodDescriptor>() in
1812
  // descriptor.cc and update them to initialize the field.
1813
1814
  // Must be constructed using DescriptorPool.
1815
  MethodDescriptor();
1816
  friend class DescriptorBuilder;
1817
  friend class ServiceDescriptor;
1818
};
1819
1820
PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(MethodDescriptor, 80);
1821
1822
// Describes a whole .proto file.  To get the FileDescriptor for a compiled-in
1823
// file, get the descriptor for something defined in that file and call
1824
// descriptor->file().  Use DescriptorPool to construct your own descriptors.
1825
class PROTOBUF_EXPORT FileDescriptor : private internal::SymbolBase {
1826
 public:
1827
  typedef FileDescriptorProto Proto;
1828
1829
#ifndef SWIG
1830
  FileDescriptor(const FileDescriptor&) = delete;
1831
  FileDescriptor& operator=(const FileDescriptor&) = delete;
1832
#endif
1833
1834
  // The filename, relative to the source tree.
1835
  // e.g. "foo/bar/baz.proto"
1836
  internal::DescriptorStringView name() const;
1837
1838
  // The package, e.g. "google.protobuf.compiler".
1839
  internal::DescriptorStringView package() const;
1840
1841
  // The DescriptorPool in which this FileDescriptor and all its contents were
1842
  // allocated.  Never nullptr.
1843
  const DescriptorPool* pool() const;
1844
1845
  // The number of files imported by this one.
1846
  int dependency_count() const;
1847
  // Gets an imported file by index, where 0 <= index < dependency_count().
1848
  // These are returned in the order they were defined in the .proto file.
1849
  const FileDescriptor* dependency(int index) const;
1850
1851
  // The number of files public imported by this one.
1852
  // The public dependency list is a subset of the dependency list.
1853
  int public_dependency_count() const;
1854
  // Gets a public imported file by index, where 0 <= index <
1855
  // public_dependency_count().
1856
  // These are returned in the order they were defined in the .proto file.
1857
  const FileDescriptor* public_dependency(int index) const;
1858
1859
  // The number of files that are imported for weak fields.
1860
  // The weak dependency list is a subset of the dependency list.
1861
  int weak_dependency_count() const;
1862
  // Gets a weak imported file by index, where 0 <= index <
1863
  // weak_dependency_count().
1864
  // These are returned in the order they were defined in the .proto file.
1865
  const FileDescriptor* weak_dependency(int index) const;
1866
1867
  // Number of top-level message types defined in this file.  (This does not
1868
  // include nested types.)
1869
  int message_type_count() const;
1870
  // Gets a top-level message type, where 0 <= index < message_type_count().
1871
  // These are returned in the order they were defined in the .proto file.
1872
  const Descriptor* message_type(int index) const;
1873
1874
  // Number of top-level enum types defined in this file.  (This does not
1875
  // include nested types.)
1876
  int enum_type_count() const;
1877
  // Gets a top-level enum type, where 0 <= index < enum_type_count().
1878
  // These are returned in the order they were defined in the .proto file.
1879
  const EnumDescriptor* enum_type(int index) const;
1880
1881
  // Number of services defined in this file.
1882
  int service_count() const;
1883
  // Gets a service, where 0 <= index < service_count().
1884
  // These are returned in the order they were defined in the .proto file.
1885
  const ServiceDescriptor* service(int index) const;
1886
1887
  // Number of extensions defined at file scope.  (This does not include
1888
  // extensions nested within message types.)
1889
  int extension_count() const;
1890
  // Gets an extension's descriptor, where 0 <= index < extension_count().
1891
  // These are returned in the order they were defined in the .proto file.
1892
  const FieldDescriptor* extension(int index) const;
1893
1894
  // Get options for this file.  These are specified in the .proto file by
1895
  // placing lines like "option foo = 1234;" at the top level, outside of any
1896
  // other definitions.  Allowed options are defined by FileOptions in
1897
  // descriptor.proto, and any available extensions of that message.
1898
  const FileOptions& options() const;
1899
1900
  // Find a top-level message type by name (not full_name).  Returns nullptr if
1901
  // not found.
1902
  const Descriptor* FindMessageTypeByName(absl::string_view name) const;
1903
  // Find a top-level enum type by name.  Returns nullptr if not found.
1904
  const EnumDescriptor* FindEnumTypeByName(absl::string_view name) const;
1905
  // Find an enum value defined in any top-level enum by name.  Returns nullptr
1906
  // if not found.
1907
  const EnumValueDescriptor* FindEnumValueByName(absl::string_view name) const;
1908
  // Find a service definition by name.  Returns nullptr if not found.
1909
  const ServiceDescriptor* FindServiceByName(absl::string_view name) const;
1910
  // Find a top-level extension definition by name.  Returns nullptr if not
1911
  // found.
1912
  const FieldDescriptor* FindExtensionByName(absl::string_view name) const;
1913
  // Similar to FindExtensionByName(), but searches by lowercased-name.  See
1914
  // Descriptor::FindFieldByLowercaseName().
1915
  const FieldDescriptor* FindExtensionByLowercaseName(
1916
      absl::string_view name) const;
1917
  // Similar to FindExtensionByName(), but searches by camelcased-name.  See
1918
  // Descriptor::FindFieldByCamelcaseName().
1919
  const FieldDescriptor* FindExtensionByCamelcaseName(
1920
      absl::string_view name) const;
1921
1922
  // See Descriptor::CopyTo().
1923
  // Notes:
1924
  // - This method does NOT copy source code information since it is relatively
1925
  //   large and rarely needed.  See CopySourceCodeInfoTo() below.
1926
  void CopyTo(FileDescriptorProto* proto) const;
1927
  // Write the source code information of this FileDescriptor into the given
1928
  // FileDescriptorProto.  See CopyTo() above.
1929
  void CopySourceCodeInfoTo(FileDescriptorProto* proto) const;
1930
  // Fill the json_name field of FieldDescriptorProto for all fields. Can only
1931
  // be called after CopyTo().
1932
  void CopyJsonNameTo(FileDescriptorProto* proto) const;
1933
  // Fills in the file-level settings of this file (e.g. edition, package,
1934
  // file options) to `proto`.
1935
  void CopyHeadingTo(FileDescriptorProto* proto) const;
1936
1937
  // See Descriptor::DebugString().
1938
  std::string DebugString() const;
1939
1940
  // See Descriptor::DebugStringWithOptions().
1941
  std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1942
1943
  // Allows formatting with absl and gtest.
1944
  template <typename Sink>
1945
  friend void AbslStringify(Sink& sink, const FileDescriptor& d) {
1946
    absl::Format(&sink, "%s", d.DebugString());
1947
  }
1948
1949
  // Returns true if this is a placeholder for an unknown file. This will
1950
  // only be the case if this descriptor comes from a DescriptorPool
1951
  // with AllowUnknownDependencies() set.
1952
  bool is_placeholder() const;
1953
1954
  // Updates |*out_location| to the source location of the complete extent of
1955
  // this file declaration (namely, the empty path).
1956
  bool GetSourceLocation(SourceLocation* out_location) const;
1957
1958
  // Updates |*out_location| to the source location of the complete
1959
  // extent of the declaration or declaration-part denoted by |path|.
1960
  // Returns false and leaves |*out_location| unchanged iff location
1961
  // information was not available.  (See SourceCodeInfo for
1962
  // description of path encoding.)
1963
  bool GetSourceLocation(const std::vector<int>& path,
1964
                         SourceLocation* out_location) const;
1965
1966
 private:
1967
  friend class Symbol;
1968
  friend class FileDescriptorLegacy;
1969
  typedef FileOptions OptionsType;
1970
1971
  bool is_placeholder_;
1972
  // Indicates the FileDescriptor is completed building. Used to verify
1973
  // that type accessor functions that can possibly build a dependent file
1974
  // aren't called during the process of building the file.
1975
  bool finished_building_;
1976
  // This one is here to fill the padding.
1977
  int extension_count_;
1978
1979
  const std::string* name_;
1980
  const std::string* package_;
1981
  const DescriptorPool* pool_;
1982
  Edition edition_;
1983
1984
  // Returns edition of this file.  For legacy proto2/proto3 files, special
1985
  // EDITION_PROTO2 and EDITION_PROTO3 values are used.
1986
  Edition edition() const;
1987
1988
  // Get the merged features that apply to this file.  These are specified in
1989
  // the .proto file through the feature options in the message definition.
1990
  // Allowed features are defined by FeatureSet in descriptor.proto, along with
1991
  // any backend-specific extensions to it.
1992
0
  const FeatureSet& features() const { return *merged_features_; }
1993
  friend class internal::InternalFeatureHelper;
1994
1995
  // dependencies_once_ contain a once_flag followed by N NUL terminated
1996
  // strings. Dependencies that do not need to be loaded will be empty. ie just
1997
  // {'\0'}
1998
  absl::once_flag* dependencies_once_;
1999
  static void DependenciesOnceInit(const FileDescriptor* to_init);
2000
  void InternalDependenciesOnceInit() const;
2001
2002
  // These are arranged to minimize padding on 64-bit.
2003
  int dependency_count_;
2004
  int public_dependency_count_;
2005
  int weak_dependency_count_;
2006
  int message_type_count_;
2007
  int enum_type_count_;
2008
  int service_count_;
2009
2010
  mutable const FileDescriptor** dependencies_;
2011
  int* public_dependencies_;
2012
  int* weak_dependencies_;
2013
  Descriptor* message_types_;
2014
  EnumDescriptor* enum_types_;
2015
  ServiceDescriptor* services_;
2016
  FieldDescriptor* extensions_;
2017
  const FileOptions* options_;
2018
  const FeatureSet* proto_features_;
2019
  const FeatureSet* merged_features_;
2020
2021
  const FileDescriptorTables* tables_;
2022
  const SourceCodeInfo* source_code_info_;
2023
2024
  // IMPORTANT:  If you add a new field, make sure to search for all instances
2025
  // of Allocate<FileDescriptor>() and AllocateArray<FileDescriptor>() in
2026
  // descriptor.cc and update them to initialize the field.
2027
2028
  FileDescriptor();
2029
  friend class DescriptorBuilder;
2030
  friend class DescriptorPool;
2031
  friend class Descriptor;
2032
  friend class FieldDescriptor;
2033
  friend class internal::LazyDescriptor;
2034
  friend class OneofDescriptor;
2035
  friend class EnumDescriptor;
2036
  friend class EnumValueDescriptor;
2037
  friend class MethodDescriptor;
2038
  friend class ServiceDescriptor;
2039
};
2040
2041
PROTOBUF_INTERNAL_CHECK_CLASS_SIZE(FileDescriptor, 168);
2042
2043
// ===================================================================
2044
2045
// Used to construct descriptors.
2046
//
2047
// Normally you won't want to build your own descriptors.  Message classes
2048
// constructed by the protocol compiler will provide them for you.  However,
2049
// if you are implementing Message on your own, or if you are writing a
2050
// program which can operate on totally arbitrary types and needs to load
2051
// them from some sort of database, you might need to.
2052
//
2053
// Since Descriptors are composed of a whole lot of cross-linked bits of
2054
// data that would be a pain to put together manually, the
2055
// DescriptorPool class is provided to make the process easier.  It can
2056
// take a FileDescriptorProto (defined in descriptor.proto), validate it,
2057
// and convert it to a set of nicely cross-linked Descriptors.
2058
//
2059
// DescriptorPool also helps with memory management.  Descriptors are
2060
// composed of many objects containing static data and pointers to each
2061
// other.  In all likelihood, when it comes time to delete this data,
2062
// you'll want to delete it all at once.  In fact, it is not uncommon to
2063
// have a whole pool of descriptors all cross-linked with each other which
2064
// you wish to delete all at once.  This class represents such a pool, and
2065
// handles the memory management for you.
2066
//
2067
// You can also search for descriptors within a DescriptorPool by name, and
2068
// extensions by number.
2069
class PROTOBUF_EXPORT DescriptorPool {
2070
 public:
2071
  // Create a normal, empty DescriptorPool.
2072
  DescriptorPool();
2073
2074
  // Constructs a DescriptorPool that, when it can't find something among the
2075
  // descriptors already in the pool, looks for it in the given
2076
  // DescriptorDatabase.
2077
  // Notes:
2078
  // - If a DescriptorPool is constructed this way, its BuildFile*() methods
2079
  //   must not be called (they will assert-fail).  The only way to populate
2080
  //   the pool with descriptors is to call the Find*By*() methods.
2081
  // - The Find*By*() methods may block the calling thread if the
2082
  //   DescriptorDatabase blocks.  This in turn means that parsing messages
2083
  //   may block if they need to look up extensions.
2084
  // - The Find*By*() methods will use mutexes for thread-safety, thus making
2085
  //   them slower even when they don't have to fall back to the database.
2086
  //   In fact, even the Find*By*() methods of descriptor objects owned by
2087
  //   this pool will be slower, since they will have to obtain locks too.
2088
  // - An ErrorCollector may optionally be given to collect validation errors
2089
  //   in files loaded from the database.  If not given, errors will be printed
2090
  //   to ABSL_LOG(ERROR).  Remember that files are built on-demand, so this
2091
  //   ErrorCollector may be called from any thread that calls one of the
2092
  //   Find*By*() methods.
2093
  // - The DescriptorDatabase must not be mutated during the lifetime of
2094
  //   the DescriptorPool. Even if the client takes care to avoid data races,
2095
  //   changes to the content of the DescriptorDatabase may not be reflected
2096
  //   in subsequent lookups in the DescriptorPool.
2097
  class ErrorCollector;
2098
  explicit DescriptorPool(DescriptorDatabase* fallback_database,
2099
                          ErrorCollector* error_collector = nullptr);
2100
2101
#ifndef SWIG
2102
  DescriptorPool(const DescriptorPool&) = delete;
2103
  DescriptorPool& operator=(const DescriptorPool&) = delete;
2104
#endif
2105
  ~DescriptorPool();
2106
2107
  // Get a pointer to the generated pool.  Generated protocol message classes
2108
  // which are compiled into the binary will allocate their descriptors in
2109
  // this pool.  Do not add your own descriptors to this pool.
2110
  static const DescriptorPool* generated_pool();
2111
2112
2113
  // Find a FileDescriptor in the pool by file name.  Returns nullptr if not
2114
  // found.
2115
  const FileDescriptor* FindFileByName(absl::string_view name) const;
2116
2117
  // Find the FileDescriptor in the pool which defines the given symbol.
2118
  // If any of the Find*ByName() methods below would succeed, then this is
2119
  // equivalent to calling that method and calling the result's file() method.
2120
  // Otherwise this returns nullptr.
2121
  const FileDescriptor* FindFileContainingSymbol(
2122
      absl::string_view symbol_name) const;
2123
2124
  // Looking up descriptors ------------------------------------------
2125
  // These find descriptors by fully-qualified name.  These will find both
2126
  // top-level descriptors and nested descriptors.  They return nullptr if not
2127
  // found.
2128
2129
  const Descriptor* FindMessageTypeByName(absl::string_view name) const;
2130
  const FieldDescriptor* FindFieldByName(absl::string_view name) const;
2131
  const FieldDescriptor* FindExtensionByName(absl::string_view name) const;
2132
  const OneofDescriptor* FindOneofByName(absl::string_view name) const;
2133
  const EnumDescriptor* FindEnumTypeByName(absl::string_view name) const;
2134
  const EnumValueDescriptor* FindEnumValueByName(absl::string_view name) const;
2135
  const ServiceDescriptor* FindServiceByName(absl::string_view name) const;
2136
  const MethodDescriptor* FindMethodByName(absl::string_view name) const;
2137
2138
  // Finds an extension of the given type by number.  The extendee must be
2139
  // a member of this DescriptorPool or one of its underlays.
2140
  const FieldDescriptor* FindExtensionByNumber(const Descriptor* extendee,
2141
                                               int number) const;
2142
2143
  // Finds an extension of the given type by its printable name.
2144
  // See comments above PrintableNameForExtension() for the definition of
2145
  // "printable name".  The extendee must be a member of this DescriptorPool
2146
  // or one of its underlays.  Returns nullptr if there is no known message
2147
  // extension with the given printable name.
2148
  const FieldDescriptor* FindExtensionByPrintableName(
2149
      const Descriptor* extendee, absl::string_view printable_name) const;
2150
2151
  // Finds extensions of extendee. The extensions will be appended to
2152
  // out in an undefined order. Only extensions defined directly in
2153
  // this DescriptorPool or one of its underlays are guaranteed to be
2154
  // found: extensions defined in the fallback database might not be found
2155
  // depending on the database implementation.
2156
  void FindAllExtensions(const Descriptor* extendee,
2157
                         std::vector<const FieldDescriptor*>* out) const;
2158
2159
  // Building descriptors --------------------------------------------
2160
2161
  // When converting a FileDescriptorProto to a FileDescriptor, various
2162
  // errors might be detected in the input.  The caller may handle these
2163
  // programmatically by implementing an ErrorCollector.
2164
  class PROTOBUF_EXPORT ErrorCollector {
2165
   public:
2166
0
    inline ErrorCollector() {}
2167
#ifndef SWIG
2168
    ErrorCollector(const ErrorCollector&) = delete;
2169
    ErrorCollector& operator=(const ErrorCollector&) = delete;
2170
#endif
2171
    virtual ~ErrorCollector();
2172
2173
    // These constants specify what exact part of the construct is broken.
2174
    // This is useful e.g. for mapping the error back to an exact location
2175
    // in a .proto file.
2176
    enum ErrorLocation {
2177
      NAME,           // the symbol name, or the package name for files
2178
      NUMBER,         // field, extension range or extension decl number
2179
      TYPE,           // field type
2180
      EXTENDEE,       // field extendee
2181
      DEFAULT_VALUE,  // field default value
2182
      INPUT_TYPE,     // method input type
2183
      OUTPUT_TYPE,    // method output type
2184
      OPTION_NAME,    // name in assignment
2185
      OPTION_VALUE,   // value in option assignment
2186
      IMPORT,         // import error
2187
      EDITIONS,       // editions-related error
2188
      OTHER           // some other problem
2189
    };
2190
    static absl::string_view ErrorLocationName(ErrorLocation location);
2191
2192
    // Reports an error in the FileDescriptorProto. Use this function if the
2193
    // problem occurred should interrupt building the FileDescriptorProto.
2194
    // Provided the following arguments:
2195
    // filename - File name in which the error occurred.
2196
    // element_name - Full name of the erroneous element.
2197
    // descriptor - Descriptor of the erroneous element.
2198
    // location - One of the location constants, above.
2199
    // message - Human-readable error message.
2200
    virtual void RecordError(absl::string_view filename,
2201
                             absl::string_view element_name,
2202
                             const Message* descriptor, ErrorLocation location,
2203
                             absl::string_view message)
2204
        = 0;
2205
2206
    // Reports a warning in the FileDescriptorProto. Use this function if the
2207
    // problem occurred should NOT interrupt building the FileDescriptorProto.
2208
    // Provided the following arguments:
2209
    // filename - File name in which the error occurred.
2210
    // element_name - Full name of the erroneous element.
2211
    // descriptor - Descriptor of the erroneous element.
2212
    // location - One of the location constants, above.
2213
    // message - Human-readable error message.
2214
    virtual void RecordWarning(absl::string_view filename,
2215
                               absl::string_view element_name,
2216
                               const Message* descriptor,
2217
                               ErrorLocation location,
2218
0
                               absl::string_view message) {
2219
0
    }
2220
2221
  };
2222
2223
  // Convert the FileDescriptorProto to real descriptors and place them in
2224
  // this DescriptorPool.  All dependencies of the file must already be in
2225
  // the pool.  Returns the resulting FileDescriptor, or nullptr if there were
2226
  // problems with the input (e.g. the message was invalid, or dependencies
2227
  // were missing).  Details about the errors are written to ABSL_LOG(ERROR).
2228
  const FileDescriptor* BuildFile(const FileDescriptorProto& proto);
2229
2230
  // Same as BuildFile() except errors are sent to the given ErrorCollector.
2231
  const FileDescriptor* BuildFileCollectingErrors(
2232
      const FileDescriptorProto& proto, ErrorCollector* error_collector);
2233
2234
  // By default, it is an error if a FileDescriptorProto contains references
2235
  // to types or other files that are not found in the DescriptorPool (or its
2236
  // backing DescriptorDatabase, if any).  If you call
2237
  // AllowUnknownDependencies(), however, then unknown types and files
2238
  // will be replaced by placeholder descriptors (which can be identified by
2239
  // the is_placeholder() method).  This can allow you to
2240
  // perform some useful operations with a .proto file even if you do not
2241
  // have access to other .proto files on which it depends.  However, some
2242
  // heuristics must be used to fill in the gaps in information, and these
2243
  // can lead to descriptors which are inaccurate.  For example, the
2244
  // DescriptorPool may be forced to guess whether an unknown type is a message
2245
  // or an enum, as well as what package it resides in.  Furthermore,
2246
  // placeholder types will not be discoverable via FindMessageTypeByName()
2247
  // and similar methods, which could confuse some descriptor-based algorithms.
2248
  // Generally, the results of this option should be handled with extreme care.
2249
0
  void AllowUnknownDependencies() { allow_unknown_ = true; }
2250
2251
  // By default, weak imports are allowed to be missing, in which case we will
2252
  // use a placeholder for the dependency and convert the field to be an Empty
2253
  // message field. If you call EnforceWeakDependencies(true), however, the
2254
  // DescriptorPool will report a import not found error.
2255
0
  void EnforceWeakDependencies(bool enforce) { enforce_weak_ = enforce; }
2256
2257
  // Sets the default feature mappings used during the build. If this function
2258
  // isn't called, the C++ feature set defaults are used.  If this function is
2259
  // called, these defaults will be used instead.
2260
  // FeatureSetDefaults includes a minimum/maximum supported edition, which will
2261
  // be enforced while building proto files.
2262
  absl::Status SetFeatureSetDefaults(FeatureSetDefaults spec);
2263
2264
  // Toggles enforcement of extension declarations.
2265
  // This enforcement is disabled by default because it requires full
2266
  // descriptors with source-retention options, which are generally not
2267
  // available at runtime.
2268
0
  void EnforceExtensionDeclarations(bool enforce) {
2269
0
    enforce_extension_declarations_ = enforce;
2270
0
  }
2271
2272
#ifndef SWIG
2273
  // Dispatch recursive builds to a callback that may stick them onto a separate
2274
  // thread.  This is primarily to avoid stack overflows on untrusted inputs.
2275
  // The dispatcher must always synchronously execute the provided callback.
2276
  // Asynchronous execution is undefined behavior.
2277
  void SetRecursiveBuildDispatcher(
2278
0
      absl::AnyInvocable<void(absl::FunctionRef<void()>) const> dispatcher) {
2279
0
    if (dispatcher != nullptr) {
2280
0
      dispatcher_ = std::make_unique<
2281
0
          absl::AnyInvocable<void(absl::FunctionRef<void()>) const>>(
2282
0
          std::move(dispatcher));
2283
0
    } else {
2284
0
      dispatcher_.reset(nullptr);
2285
0
    }
2286
0
  }
2287
#endif  // SWIG
2288
2289
  // Internal stuff --------------------------------------------------
2290
  // These methods MUST NOT be called from outside the proto2 library.
2291
  // These methods may contain hidden pitfalls and may be removed in a
2292
  // future library version.
2293
2294
  // Create a DescriptorPool which is overlaid on top of some other pool.
2295
  // If you search for a descriptor in the overlay and it is not found, the
2296
  // underlay will be searched as a backup.  If the underlay has its own
2297
  // underlay, that will be searched next, and so on.  This also means that
2298
  // files built in the overlay will be cross-linked with the underlay's
2299
  // descriptors if necessary.  The underlay remains property of the caller;
2300
  // it must remain valid for the lifetime of the newly-constructed pool.
2301
  //
2302
  // Example:  Say you want to parse a .proto file at runtime in order to use
2303
  // its type with a DynamicMessage.  Say this .proto file has dependencies,
2304
  // but you know that all the dependencies will be things that are already
2305
  // compiled into the binary.  For ease of use, you'd like to load the types
2306
  // right out of generated_pool() rather than have to parse redundant copies
2307
  // of all these .protos and runtime.  But, you don't want to add the parsed
2308
  // types directly into generated_pool(): this is not allowed, and would be
2309
  // bad design anyway.  So, instead, you could use generated_pool() as an
2310
  // underlay for a new DescriptorPool in which you add only the new file.
2311
  //
2312
  // WARNING:  Use of underlays can lead to many subtle gotchas.  Instead,
2313
  //   try to formulate what you want to do in terms of DescriptorDatabases.
2314
  explicit DescriptorPool(const DescriptorPool* underlay);
2315
2316
  // Called by generated classes at init time to add their descriptors to
2317
  // generated_pool.  Do NOT call this in your own code!  filename must be a
2318
  // permanent string (e.g. a string literal).
2319
  static void InternalAddGeneratedFile(const void* encoded_file_descriptor,
2320
                                       int size);
2321
2322
  // Disallow [enforce_utf8 = false] in .proto files.
2323
0
  void DisallowEnforceUtf8() { disallow_enforce_utf8_ = true; }
2324
2325
  // Use the deprecated legacy behavior for handling JSON field name conflicts.
2326
  ABSL_DEPRECATED("Deprecated treatment of field name conflicts is enabled.")
2327
0
  void UseDeprecatedLegacyJsonFieldConflicts() {
2328
0
    deprecated_legacy_json_field_conflicts_ = true;
2329
0
  }
2330
2331
2332
  // For internal use only:  Gets a non-const pointer to the generated pool.
2333
  // This is called at static-initialization time only, so thread-safety is
2334
  // not a concern.  If both an underlay and a fallback database are present,
2335
  // the underlay takes precedence.
2336
  static DescriptorPool* internal_generated_pool();
2337
2338
  // For internal use only:  Gets a non-const pointer to the generated
2339
  // descriptor database.
2340
  // Only used for testing.
2341
  static DescriptorDatabase* internal_generated_database();
2342
2343
  // For internal use only:  Changes the behavior of BuildFile() such that it
2344
  // allows the file to make reference to message types declared in other files
2345
  // which it did not officially declare as dependencies.
2346
  void InternalDontEnforceDependencies();
2347
2348
  // For internal use only: Enables lazy building of dependencies of a file.
2349
  // Delay the building of dependencies of a file descriptor until absolutely
2350
  // necessary, like when message_type() is called on a field that is defined
2351
  // in that dependency's file. This will cause functional issues if a proto
2352
  // or one of its dependencies has errors. Should only be enabled for the
2353
  // generated_pool_ (because no descriptor build errors are guaranteed by
2354
  // the compilation generation process), testing, or if a lack of descriptor
2355
  // build errors can be guaranteed for a pool.
2356
0
  void InternalSetLazilyBuildDependencies() {
2357
0
    lazily_build_dependencies_ = true;
2358
0
    // This needs to be set when lazily building dependencies, as it breaks
2359
0
    // dependency checking.
2360
0
    InternalDontEnforceDependencies();
2361
0
  }
2362
2363
  // For internal use only.
2364
0
  void internal_set_underlay(const DescriptorPool* underlay) {
2365
0
    underlay_ = underlay;
2366
0
  }
2367
2368
  // For internal (unit test) use only:  Returns true if a FileDescriptor has
2369
  // been constructed for the given file, false otherwise.  Useful for testing
2370
  // lazy descriptor initialization behavior.
2371
  bool InternalIsFileLoaded(absl::string_view filename) const;
2372
2373
  // Add a file to to apply more strict checks to.
2374
  // - unused imports will log either warnings or errors.
2375
  // - deprecated features will log warnings.
2376
  void AddDirectInputFile(absl::string_view file_name,
2377
                          bool unused_import_is_error = false);
2378
  void ClearDirectInputFiles();
2379
2380
#if !defined(PROTOBUF_FUTURE_RENAME_ADD_UNUSED_IMPORT) && !defined(SWIG)
2381
  ABSL_DEPRECATED("Use AddDirectInputFile")
2382
  void AddUnusedImportTrackFile(absl::string_view file_name,
2383
0
                                bool is_error = false) {
2384
0
    AddDirectInputFile(file_name, is_error);
2385
0
  }
2386
  ABSL_DEPRECATED("Use AddDirectInputFile")
2387
0
  void ClearUnusedImportTrackFiles() { ClearDirectInputFiles(); }
2388
#endif  // !PROTOBUF_FUTURE_RENAME_ADD_UNUSED_IMPORT && !SWIG
2389
2390
2391
 private:
2392
  friend class Descriptor;
2393
  friend class internal::LazyDescriptor;
2394
  friend class FieldDescriptor;
2395
  friend class EnumDescriptor;
2396
  friend class ServiceDescriptor;
2397
  friend class MethodDescriptor;
2398
  friend class FileDescriptor;
2399
  friend class DescriptorBuilder;
2400
  friend class FileDescriptorTables;
2401
  friend class google::protobuf::descriptor_unittest::ValidationErrorTest;
2402
  friend class ::google::protobuf::compiler::CommandLineInterface;
2403
2404
  // Return true if the given name is a sub-symbol of any non-package
2405
  // descriptor that already exists in the descriptor pool.  (The full
2406
  // definition of such types is already known.)
2407
  bool IsSubSymbolOfBuiltType(absl::string_view name) const;
2408
2409
  // Tries to find something in the fallback database and link in the
2410
  // corresponding proto file.  Returns true if successful, in which case
2411
  // the caller should search for the thing again.  These are declared
2412
  // const because they are called by (semantically) const methods.
2413
  // DeferredValidation stores temporary information necessary to run validation
2414
  // checks that can't be done inside the database lock.  This is generally
2415
  // reflective operations that also require the lock to do safely.
2416
  class DeferredValidation;
2417
  bool TryFindFileInFallbackDatabase(
2418
      absl::string_view name, DeferredValidation& deferred_validation) const;
2419
  bool TryFindSymbolInFallbackDatabase(
2420
      absl::string_view name, DeferredValidation& deferred_validation) const;
2421
  bool TryFindExtensionInFallbackDatabase(
2422
      const Descriptor* containing_type, int field_number,
2423
      DeferredValidation& deferred_validation) const;
2424
2425
  // This internal find extension method only check with its table and underlay
2426
  // descriptor_pool's table. It does not check with fallback DB and no
2427
  // additional proto file will be build in this method.
2428
  const FieldDescriptor* InternalFindExtensionByNumberNoLock(
2429
      const Descriptor* extendee, int number) const;
2430
2431
  // Like BuildFile() but called internally when the file has been loaded from
2432
  // fallback_database_.  Declared const because it is called by (semantically)
2433
  // const methods.
2434
  const FileDescriptor* BuildFileFromDatabase(
2435
      const FileDescriptorProto& proto,
2436
      DeferredValidation& deferred_validation) const;
2437
2438
  // Helper for when lazily_build_dependencies_ is set, can look up a symbol
2439
  // after the file's descriptor is built, and can build the file where that
2440
  // symbol is defined if necessary. Will create a placeholder if the type
2441
  // doesn't exist in the fallback database, or the file doesn't build
2442
  // successfully.
2443
  Symbol CrossLinkOnDemandHelper(absl::string_view name,
2444
                                 bool expecting_enum) const;
2445
2446
  // Create a placeholder FileDescriptor of the specified name
2447
  FileDescriptor* NewPlaceholderFile(absl::string_view name) const;
2448
  FileDescriptor* NewPlaceholderFileWithMutexHeld(
2449
      absl::string_view name, internal::FlatAllocator& alloc) const;
2450
2451
  enum PlaceholderType {
2452
    PLACEHOLDER_MESSAGE,
2453
    PLACEHOLDER_ENUM,
2454
    PLACEHOLDER_EXTENDABLE_MESSAGE
2455
  };
2456
  // Create a placeholder Descriptor of the specified name
2457
  Symbol NewPlaceholder(absl::string_view name,
2458
                        PlaceholderType placeholder_type) const;
2459
  Symbol NewPlaceholderWithMutexHeld(absl::string_view name,
2460
                                     PlaceholderType placeholder_type) const;
2461
2462
  // If fallback_database_ is nullptr, this is nullptr.  Otherwise, this is a
2463
  // mutex which must be locked while accessing tables_.
2464
  absl::Mutex* mutex_;
2465
2466
  // See constructor.
2467
  DescriptorDatabase* fallback_database_;
2468
  ErrorCollector* default_error_collector_;
2469
  const DescriptorPool* underlay_;
2470
2471
#ifndef SWIG
2472
  // Dispatcher for recursive calls during builds.
2473
  std::unique_ptr<absl::AnyInvocable<void(absl::FunctionRef<void()>) const>>
2474
      dispatcher_;
2475
#endif  // SWIG
2476
2477
  // This class contains a lot of hash maps with complicated types that
2478
  // we'd like to keep out of the header.
2479
  class Tables;
2480
  std::unique_ptr<Tables> tables_;
2481
2482
  bool enforce_dependencies_;
2483
  bool lazily_build_dependencies_;
2484
  bool allow_unknown_;
2485
  bool enforce_weak_;
2486
  bool enforce_extension_declarations_;
2487
  bool disallow_enforce_utf8_;
2488
  bool deprecated_legacy_json_field_conflicts_;
2489
  mutable bool build_started_ = false;
2490
2491
  // Set of files to track for additional validation. The bool value when true
2492
  // means unused imports are treated as errors (and as warnings when false).
2493
  absl::flat_hash_map<std::string, bool> direct_input_files_;
2494
2495
  // Specification of defaults to use for feature resolution.  This defaults to
2496
  // just the global and C++ features, but can be overridden for other runtimes.
2497
  std::unique_ptr<FeatureSetDefaults> feature_set_defaults_spec_;
2498
2499
  // Returns true if the field extends an option message of descriptor.proto.
2500
  bool IsReadyForCheckingDescriptorExtDecl(
2501
      absl::string_view message_name) const;
2502
2503
};
2504
2505
2506
// inline methods ====================================================
2507
2508
// These macros makes this repetitive code more readable.
2509
#define PROTOBUF_DEFINE_ACCESSOR(CLASS, FIELD, TYPE) \
2510
0
  inline TYPE CLASS::FIELD() const { return FIELD##_; }
Unexecuted instantiation: google::protobuf::Descriptor::file() const
Unexecuted instantiation: google::protobuf::Descriptor::containing_type() const
Unexecuted instantiation: google::protobuf::Descriptor::field_count() const
Unexecuted instantiation: google::protobuf::Descriptor::oneof_decl_count() const
Unexecuted instantiation: google::protobuf::Descriptor::real_oneof_decl_count() const
Unexecuted instantiation: google::protobuf::Descriptor::nested_type_count() const
Unexecuted instantiation: google::protobuf::Descriptor::enum_type_count() const
Unexecuted instantiation: google::protobuf::Descriptor::extension_range_count() const
Unexecuted instantiation: google::protobuf::Descriptor::extension_count() const
Unexecuted instantiation: google::protobuf::Descriptor::reserved_range_count() const
Unexecuted instantiation: google::protobuf::Descriptor::reserved_name_count() const
Unexecuted instantiation: google::protobuf::Descriptor::is_placeholder() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::file() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::number() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::is_extension() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::containing_type() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::has_default_value() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::has_json_name() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::default_value_int32_t() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::default_value_int64_t() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::default_value_uint32_t() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::default_value_uint64_t() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::default_value_float() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::default_value_double() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::default_value_bool() const
Unexecuted instantiation: google::protobuf::OneofDescriptor::containing_type() const
Unexecuted instantiation: google::protobuf::OneofDescriptor::field_count() const
Unexecuted instantiation: google::protobuf::EnumDescriptor::file() const
Unexecuted instantiation: google::protobuf::EnumDescriptor::containing_type() const
Unexecuted instantiation: google::protobuf::EnumDescriptor::value_count() const
Unexecuted instantiation: google::protobuf::EnumDescriptor::is_placeholder() const
Unexecuted instantiation: google::protobuf::EnumDescriptor::reserved_range_count() const
Unexecuted instantiation: google::protobuf::EnumDescriptor::reserved_name_count() const
Unexecuted instantiation: google::protobuf::EnumValueDescriptor::number() const
Unexecuted instantiation: google::protobuf::EnumValueDescriptor::type() const
Unexecuted instantiation: google::protobuf::ServiceDescriptor::file() const
Unexecuted instantiation: google::protobuf::ServiceDescriptor::method_count() const
Unexecuted instantiation: google::protobuf::MethodDescriptor::service() const
Unexecuted instantiation: google::protobuf::MethodDescriptor::client_streaming() const
Unexecuted instantiation: google::protobuf::MethodDescriptor::server_streaming() const
Unexecuted instantiation: google::protobuf::FileDescriptor::pool() const
Unexecuted instantiation: google::protobuf::FileDescriptor::dependency_count() const
Unexecuted instantiation: google::protobuf::FileDescriptor::public_dependency_count() const
Unexecuted instantiation: google::protobuf::FileDescriptor::weak_dependency_count() const
Unexecuted instantiation: google::protobuf::FileDescriptor::message_type_count() const
Unexecuted instantiation: google::protobuf::FileDescriptor::enum_type_count() const
Unexecuted instantiation: google::protobuf::FileDescriptor::service_count() const
Unexecuted instantiation: google::protobuf::FileDescriptor::extension_count() const
Unexecuted instantiation: google::protobuf::FileDescriptor::is_placeholder() const
2511
2512
// Strings fields are stored as pointers but returned as const references.
2513
#define PROTOBUF_DEFINE_STRING_ACCESSOR(CLASS, FIELD)          \
2514
0
  inline internal::DescriptorStringView CLASS::FIELD() const { \
2515
0
    return *FIELD##_;                                          \
2516
0
  }
Unexecuted instantiation: google::protobuf::FieldDescriptor::default_value_string() const
Unexecuted instantiation: google::protobuf::FileDescriptor::name() const
Unexecuted instantiation: google::protobuf::FileDescriptor::package() const
2517
2518
// Name and full name are stored in a single array to save space.
2519
#define PROTOBUF_DEFINE_NAME_ACCESSOR(CLASS)                       \
2520
0
  inline internal::DescriptorStringView CLASS::name() const {      \
2521
0
    return all_names_[0];                                          \
2522
0
  }                                                                \
Unexecuted instantiation: google::protobuf::Descriptor::name() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::name() const
Unexecuted instantiation: google::protobuf::OneofDescriptor::name() const
Unexecuted instantiation: google::protobuf::EnumDescriptor::name() const
Unexecuted instantiation: google::protobuf::EnumValueDescriptor::name() const
Unexecuted instantiation: google::protobuf::ServiceDescriptor::name() const
Unexecuted instantiation: google::protobuf::MethodDescriptor::name() const
2523
0
  inline internal::DescriptorStringView CLASS::full_name() const { \
2524
0
    return all_names_[1];                                          \
2525
0
  }
Unexecuted instantiation: google::protobuf::Descriptor::full_name() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::full_name() const
Unexecuted instantiation: google::protobuf::OneofDescriptor::full_name() const
Unexecuted instantiation: google::protobuf::EnumDescriptor::full_name() const
Unexecuted instantiation: google::protobuf::EnumValueDescriptor::full_name() const
Unexecuted instantiation: google::protobuf::ServiceDescriptor::full_name() const
Unexecuted instantiation: google::protobuf::MethodDescriptor::full_name() const
2526
2527
// Arrays take an index parameter, obviously.
2528
#define PROTOBUF_DEFINE_ARRAY_ACCESSOR(CLASS, FIELD, TYPE) \
2529
0
  inline TYPE CLASS::FIELD(int index) const {              \
2530
0
    ABSL_DCHECK_LE(0, index);                              \
2531
0
    ABSL_DCHECK_LT(index, FIELD##_count());                \
2532
0
    return FIELD##s_ + index;                              \
2533
0
  }
Unexecuted instantiation: google::protobuf::Descriptor::field(int) const
Unexecuted instantiation: google::protobuf::Descriptor::oneof_decl(int) const
Unexecuted instantiation: google::protobuf::Descriptor::nested_type(int) const
Unexecuted instantiation: google::protobuf::Descriptor::enum_type(int) const
Unexecuted instantiation: google::protobuf::Descriptor::extension_range(int) const
Unexecuted instantiation: google::protobuf::Descriptor::extension(int) const
Unexecuted instantiation: google::protobuf::Descriptor::reserved_range(int) const
Unexecuted instantiation: google::protobuf::OneofDescriptor::field(int) const
Unexecuted instantiation: google::protobuf::EnumDescriptor::value(int) const
Unexecuted instantiation: google::protobuf::EnumDescriptor::reserved_range(int) const
Unexecuted instantiation: google::protobuf::ServiceDescriptor::method(int) const
Unexecuted instantiation: google::protobuf::FileDescriptor::message_type(int) const
Unexecuted instantiation: google::protobuf::FileDescriptor::enum_type(int) const
Unexecuted instantiation: google::protobuf::FileDescriptor::service(int) const
Unexecuted instantiation: google::protobuf::FileDescriptor::extension(int) const
2534
2535
#define PROTOBUF_DEFINE_OPTIONS_ACCESSOR(CLASS, TYPE) \
2536
0
  inline const TYPE& CLASS::options() const { return *options_; }
Unexecuted instantiation: google::protobuf::Descriptor::options() const
Unexecuted instantiation: google::protobuf::FieldDescriptor::options() const
Unexecuted instantiation: google::protobuf::OneofDescriptor::options() const
Unexecuted instantiation: google::protobuf::EnumDescriptor::options() const
Unexecuted instantiation: google::protobuf::EnumValueDescriptor::options() const
Unexecuted instantiation: google::protobuf::ServiceDescriptor::options() const
Unexecuted instantiation: google::protobuf::MethodDescriptor::options() const
Unexecuted instantiation: google::protobuf::FileDescriptor::options() const
2537
2538
PROTOBUF_DEFINE_NAME_ACCESSOR(Descriptor)
2539
PROTOBUF_DEFINE_ACCESSOR(Descriptor, file, const FileDescriptor*)
2540
PROTOBUF_DEFINE_ACCESSOR(Descriptor, containing_type, const Descriptor*)
2541
2542
PROTOBUF_DEFINE_ACCESSOR(Descriptor, field_count, int)
2543
PROTOBUF_DEFINE_ACCESSOR(Descriptor, oneof_decl_count, int)
2544
PROTOBUF_DEFINE_ACCESSOR(Descriptor, real_oneof_decl_count, int)
2545
PROTOBUF_DEFINE_ACCESSOR(Descriptor, nested_type_count, int)
2546
PROTOBUF_DEFINE_ACCESSOR(Descriptor, enum_type_count, int)
2547
2548
PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, field, const FieldDescriptor*)
2549
PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, oneof_decl, const OneofDescriptor*)
2550
PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, nested_type, const Descriptor*)
2551
PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, enum_type, const EnumDescriptor*)
2552
0
inline const OneofDescriptor* Descriptor::real_oneof_decl(int index) const {
2553
0
  ABSL_DCHECK(index < real_oneof_decl_count());
2554
0
  return oneof_decl(index);
2555
0
}
2556
2557
PROTOBUF_DEFINE_ACCESSOR(Descriptor, extension_range_count, int)
2558
PROTOBUF_DEFINE_ACCESSOR(Descriptor, extension_count, int)
2559
PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension_range,
2560
                               const Descriptor::ExtensionRange*)
2561
PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension, const FieldDescriptor*)
2562
2563
PROTOBUF_DEFINE_ACCESSOR(Descriptor, reserved_range_count, int)
2564
PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, reserved_range,
2565
                               const Descriptor::ReservedRange*)
2566
PROTOBUF_DEFINE_ACCESSOR(Descriptor, reserved_name_count, int)
2567
2568
PROTOBUF_DEFINE_OPTIONS_ACCESSOR(Descriptor, MessageOptions)
2569
PROTOBUF_DEFINE_ACCESSOR(Descriptor, is_placeholder, bool)
2570
2571
PROTOBUF_DEFINE_NAME_ACCESSOR(FieldDescriptor)
2572
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, file, const FileDescriptor*)
2573
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, number, int)
2574
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, is_extension, bool)
2575
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, containing_type, const Descriptor*)
2576
PROTOBUF_DEFINE_OPTIONS_ACCESSOR(FieldDescriptor, FieldOptions)
2577
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_default_value, bool)
2578
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_json_name, bool)
2579
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int32_t, int32_t)
2580
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int64_t, int64_t)
2581
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint32_t, uint32_t)
2582
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint64_t, uint64_t)
2583
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_float, float)
2584
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_double, double)
2585
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_bool, bool)
2586
PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, default_value_string)
2587
2588
PROTOBUF_DEFINE_NAME_ACCESSOR(OneofDescriptor)
2589
PROTOBUF_DEFINE_ACCESSOR(OneofDescriptor, containing_type, const Descriptor*)
2590
PROTOBUF_DEFINE_ACCESSOR(OneofDescriptor, field_count, int)
2591
PROTOBUF_DEFINE_ARRAY_ACCESSOR(OneofDescriptor, field, const FieldDescriptor*)
2592
PROTOBUF_DEFINE_OPTIONS_ACCESSOR(OneofDescriptor, OneofOptions)
2593
2594
PROTOBUF_DEFINE_NAME_ACCESSOR(EnumDescriptor)
2595
PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, file, const FileDescriptor*)
2596
PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, containing_type, const Descriptor*)
2597
PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, value_count, int)
2598
PROTOBUF_DEFINE_ARRAY_ACCESSOR(EnumDescriptor, value,
2599
                               const EnumValueDescriptor*)
2600
PROTOBUF_DEFINE_OPTIONS_ACCESSOR(EnumDescriptor, EnumOptions)
2601
PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, is_placeholder, bool)
2602
PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, reserved_range_count, int)
2603
PROTOBUF_DEFINE_ARRAY_ACCESSOR(EnumDescriptor, reserved_range,
2604
                               const EnumDescriptor::ReservedRange*)
2605
PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, reserved_name_count, int)
2606
2607
PROTOBUF_DEFINE_NAME_ACCESSOR(EnumValueDescriptor)
2608
PROTOBUF_DEFINE_ACCESSOR(EnumValueDescriptor, number, int)
2609
PROTOBUF_DEFINE_ACCESSOR(EnumValueDescriptor, type, const EnumDescriptor*)
2610
PROTOBUF_DEFINE_OPTIONS_ACCESSOR(EnumValueDescriptor, EnumValueOptions)
2611
2612
PROTOBUF_DEFINE_NAME_ACCESSOR(ServiceDescriptor)
2613
PROTOBUF_DEFINE_ACCESSOR(ServiceDescriptor, file, const FileDescriptor*)
2614
PROTOBUF_DEFINE_ACCESSOR(ServiceDescriptor, method_count, int)
2615
PROTOBUF_DEFINE_ARRAY_ACCESSOR(ServiceDescriptor, method,
2616
                               const MethodDescriptor*)
2617
PROTOBUF_DEFINE_OPTIONS_ACCESSOR(ServiceDescriptor, ServiceOptions)
2618
2619
PROTOBUF_DEFINE_NAME_ACCESSOR(MethodDescriptor)
2620
PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, service, const ServiceDescriptor*)
2621
PROTOBUF_DEFINE_OPTIONS_ACCESSOR(MethodDescriptor, MethodOptions)
2622
PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, client_streaming, bool)
2623
PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, server_streaming, bool)
2624
2625
PROTOBUF_DEFINE_STRING_ACCESSOR(FileDescriptor, name)
2626
PROTOBUF_DEFINE_STRING_ACCESSOR(FileDescriptor, package)
2627
PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, pool, const DescriptorPool*)
2628
PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, dependency_count, int)
2629
PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, public_dependency_count, int)
2630
PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, weak_dependency_count, int)
2631
PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, message_type_count, int)
2632
PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, enum_type_count, int)
2633
PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, service_count, int)
2634
PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, extension_count, int)
2635
PROTOBUF_DEFINE_OPTIONS_ACCESSOR(FileDescriptor, FileOptions)
2636
PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, is_placeholder, bool)
2637
2638
PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, message_type, const Descriptor*)
2639
PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, enum_type, const EnumDescriptor*)
2640
PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, service,
2641
                               const ServiceDescriptor*)
2642
PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, extension,
2643
                               const FieldDescriptor*)
2644
2645
#undef PROTOBUF_DEFINE_ACCESSOR
2646
#undef PROTOBUF_DEFINE_STRING_ACCESSOR
2647
#undef PROTOBUF_DEFINE_ARRAY_ACCESSOR
2648
2649
// A few accessors differ from the macros...
2650
2651
0
inline Descriptor::WellKnownType Descriptor::well_known_type() const {
2652
0
  return static_cast<Descriptor::WellKnownType>(well_known_type_);
2653
0
}
2654
2655
0
inline bool Descriptor::IsExtensionNumber(int number) const {
2656
0
  return FindExtensionRangeContainingNumber(number) != nullptr;
2657
0
}
2658
2659
0
inline bool Descriptor::IsReservedNumber(int number) const {
2660
0
  return FindReservedRangeContainingNumber(number) != nullptr;
2661
0
}
2662
2663
0
inline bool Descriptor::IsReservedName(absl::string_view name) const {
2664
0
  for (int i = 0; i < reserved_name_count(); i++) {
2665
0
    if (name == static_cast<absl::string_view>(reserved_name(i))) {
2666
0
      return true;
2667
0
    }
2668
0
  }
2669
0
  return false;
2670
0
}
2671
2672
// Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually
2673
// an array of pointers rather than the usual array of objects.
2674
inline internal::DescriptorStringView Descriptor::reserved_name(
2675
0
    int index) const {
2676
0
  return *reserved_names_[index];
2677
0
}
2678
2679
0
inline bool EnumDescriptor::IsReservedNumber(int number) const {
2680
0
  return FindReservedRangeContainingNumber(number) != nullptr;
2681
0
}
2682
2683
0
inline bool EnumDescriptor::IsReservedName(absl::string_view name) const {
2684
0
  for (int i = 0; i < reserved_name_count(); i++) {
2685
0
    if (name == static_cast<absl::string_view>(reserved_name(i))) {
2686
0
      return true;
2687
0
    }
2688
0
  }
2689
0
  return false;
2690
0
}
2691
2692
// Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually
2693
// an array of pointers rather than the usual array of objects.
2694
inline internal::DescriptorStringView EnumDescriptor::reserved_name(
2695
0
    int index) const {
2696
0
  return *reserved_names_[index];
2697
0
}
2698
2699
0
inline internal::DescriptorStringView FieldDescriptor::lowercase_name() const {
2700
0
  return all_names_[lowercase_name_index_];
2701
0
}
2702
2703
0
inline internal::DescriptorStringView FieldDescriptor::camelcase_name() const {
2704
0
  return all_names_[camelcase_name_index_];
2705
0
}
2706
2707
0
inline internal::DescriptorStringView FieldDescriptor::json_name() const {
2708
0
  return all_names_[json_name_index_];
2709
0
}
2710
2711
0
inline const OneofDescriptor* FieldDescriptor::containing_oneof() const {
2712
0
  if (is_oneof_) {
2713
0
    auto* res = scope_.containing_oneof;
2714
0
    PROTOBUF_ASSUME(res != nullptr);
2715
0
    return res;
2716
0
  }
2717
0
  return nullptr;
2718
0
}
2719
2720
0
inline int FieldDescriptor::index_in_oneof() const {
2721
0
  ABSL_DCHECK(is_oneof_);
2722
0
  return static_cast<int>(this - scope_.containing_oneof->field(0));
2723
0
}
2724
2725
0
inline const Descriptor* FieldDescriptor::extension_scope() const {
2726
0
  ABSL_CHECK(is_extension_);
2727
0
  return scope_.extension_scope;
2728
0
}
2729
2730
0
inline FieldDescriptor::Label FieldDescriptor::label() const {
2731
0
  return static_cast<Label>(label_);
2732
0
}
2733
2734
0
inline FieldDescriptor::Type FieldDescriptor::type() const {
2735
0
  return static_cast<Type>(type_);
2736
0
}
2737
2738
0
inline bool FieldDescriptor::is_optional() const {
2739
0
  return label() == LABEL_OPTIONAL;
2740
0
}
2741
2742
0
inline bool FieldDescriptor::is_repeated() const {
2743
0
  ABSL_DCHECK_EQ(is_repeated_, label() == LABEL_REPEATED);
2744
0
  return is_repeated_;
2745
0
}
2746
2747
0
inline bool FieldDescriptor::is_packable() const {
2748
0
  return is_repeated() && IsTypePackable(type());
2749
0
}
2750
2751
0
inline bool FieldDescriptor::is_map() const {
2752
0
  return type() == TYPE_MESSAGE && is_map_message_type();
2753
0
}
2754
2755
0
inline const OneofDescriptor* FieldDescriptor::real_containing_oneof() const {
2756
0
  if (in_real_oneof_) {
2757
0
    auto* res = containing_oneof();
2758
0
    PROTOBUF_ASSUME(res != nullptr);
2759
0
    ABSL_DCHECK(!res->is_synthetic());
2760
0
    return res;
2761
0
  }
2762
0
  return nullptr;
2763
0
}
2764
2765
// To save space, index() is computed by looking at the descriptor's position
2766
// in the parent's array of children.
2767
0
inline int FieldDescriptor::index() const {
2768
0
  if (!is_extension_) {
2769
0
    return static_cast<int>(this - containing_type()->fields_);
2770
0
  } else if (extension_scope() != nullptr) {
2771
0
    return static_cast<int>(this - extension_scope()->extensions_);
2772
0
  } else {
2773
0
    return static_cast<int>(this - file_->extensions_);
2774
0
  }
2775
0
}
2776
2777
0
inline int Descriptor::index() const {
2778
0
  if (containing_type_ == nullptr) {
2779
0
    return static_cast<int>(this - file_->message_types_);
2780
0
  } else {
2781
0
    return static_cast<int>(this - containing_type_->nested_types_);
2782
0
  }
2783
0
}
2784
2785
0
inline int Descriptor::ExtensionRange::index() const {
2786
0
  return static_cast<int>(this - containing_type_->extension_ranges_);
2787
0
}
2788
2789
0
inline const FileDescriptor* OneofDescriptor::file() const {
2790
0
  return containing_type()->file();
2791
0
}
2792
2793
0
inline int OneofDescriptor::index() const {
2794
0
  return static_cast<int>(this - containing_type_->oneof_decls_);
2795
0
}
2796
2797
0
inline bool OneofDescriptor::is_synthetic() const {
2798
0
  return field_count() == 1 && field(0)->proto3_optional_;
2799
0
}
2800
2801
0
inline int EnumDescriptor::index() const {
2802
0
  if (containing_type_ == nullptr) {
2803
0
    return static_cast<int>(this - file_->enum_types_);
2804
0
  } else {
2805
0
    return static_cast<int>(this - containing_type_->enum_types_);
2806
0
  }
2807
0
}
2808
2809
0
inline const FileDescriptor* EnumValueDescriptor::file() const {
2810
0
  return type()->file();
2811
0
}
2812
2813
0
inline int EnumValueDescriptor::index() const {
2814
0
  return static_cast<int>(this - type_->values_);
2815
0
}
2816
2817
0
inline int ServiceDescriptor::index() const {
2818
0
  return static_cast<int>(this - file_->services_);
2819
0
}
2820
2821
0
inline const FileDescriptor* MethodDescriptor::file() const {
2822
0
  return service()->file();
2823
0
}
2824
2825
0
inline int MethodDescriptor::index() const {
2826
0
  return static_cast<int>(this - service_->methods_);
2827
0
}
2828
2829
0
inline const char* FieldDescriptor::type_name() const {
2830
0
  return kTypeToName[type()];
2831
0
}
2832
2833
0
inline FieldDescriptor::CppType FieldDescriptor::cpp_type() const {
2834
0
  return kTypeToCppTypeMap[type()];
2835
0
}
2836
2837
0
inline const char* FieldDescriptor::cpp_type_name() const {
2838
0
  return kCppTypeToName[kTypeToCppTypeMap[type()]];
2839
0
}
2840
2841
0
inline FieldDescriptor::CppType FieldDescriptor::TypeToCppType(Type type) {
2842
0
  return kTypeToCppTypeMap[type];
2843
0
}
2844
2845
0
inline const char* FieldDescriptor::TypeName(Type type) {
2846
0
  return kTypeToName[type];
2847
0
}
2848
2849
0
inline const char* FieldDescriptor::CppTypeName(CppType cpp_type) {
2850
0
  return kCppTypeToName[cpp_type];
2851
0
}
2852
2853
0
inline bool FieldDescriptor::IsTypePackable(Type field_type) {
2854
0
  return (field_type != FieldDescriptor::TYPE_STRING &&
2855
0
          field_type != FieldDescriptor::TYPE_GROUP &&
2856
0
          field_type != FieldDescriptor::TYPE_MESSAGE &&
2857
0
          field_type != FieldDescriptor::TYPE_BYTES);
2858
0
}
2859
2860
inline const FileDescriptor* FileDescriptor::public_dependency(
2861
0
    int index) const {
2862
0
  return dependency(public_dependencies_[index]);
2863
0
}
2864
2865
0
inline const FileDescriptor* FileDescriptor::weak_dependency(int index) const {
2866
0
  return dependency(weak_dependencies_[index]);
2867
0
}
2868
2869
namespace internal {
2870
2871
inline const std::string& DefaultValueStringAsString(
2872
0
    const FieldDescriptor* field) {
2873
0
  return *field->default_value_string_;
2874
0
}
2875
2876
inline const std::string& NameOfEnumAsString(
2877
0
    const EnumValueDescriptor* descriptor) {
2878
0
  return descriptor->all_names_[0];
2879
0
}
2880
2881
0
inline bool IsEnumFullySequential(const EnumDescriptor* enum_desc) {
2882
0
  return enum_desc->sequential_value_limit_ == enum_desc->value_count() - 1;
2883
0
}
2884
2885
// FieldRange(desc) provides an iterable range for the fields of a
2886
// descriptor type, appropriate for range-for loops.
2887
2888
template <typename T>
2889
struct FieldRangeImpl;
2890
2891
template <typename T>
2892
FieldRangeImpl<T> FieldRange(const T* desc) {
2893
  return {desc};
2894
}
2895
2896
template <typename T>
2897
struct FieldRangeImpl {
2898
  struct Iterator {
2899
    using iterator_category = std::forward_iterator_tag;
2900
    using value_type = const FieldDescriptor*;
2901
    using difference_type = int;
2902
2903
    value_type operator*() { return descriptor->field(idx); }
2904
2905
    friend bool operator==(const Iterator& a, const Iterator& b) {
2906
      ABSL_DCHECK(a.descriptor == b.descriptor);
2907
      return a.idx == b.idx;
2908
    }
2909
    friend bool operator!=(const Iterator& a, const Iterator& b) {
2910
      return !(a == b);
2911
    }
2912
2913
    Iterator& operator++() {
2914
      idx++;
2915
      return *this;
2916
    }
2917
2918
    int idx;
2919
    const T* descriptor;
2920
  };
2921
2922
  Iterator begin() const { return {0, descriptor}; }
2923
  Iterator end() const { return {descriptor->field_count(), descriptor}; }
2924
2925
  const T* descriptor;
2926
};
2927
2928
// While building descriptors, we need to avoid using MergeFrom()/CopyFrom() to
2929
// be -fno-rtti friendly. Without RTTI, MergeFrom() and CopyFrom() will fallback
2930
// to the reflection based method, which requires the Descriptor. However, while
2931
// building the descriptors, this causes deadlock. We also must disable lazy
2932
// parsing because that uses reflection to verify consistency.
2933
bool ParseNoReflection(absl::string_view from, google::protobuf::MessageLite& to);
2934
2935
// The context for these functions under `cpp` is "for the C++ implementation".
2936
// In particular, questions like "does this field have a has bit?" have a
2937
// different answer depending on the language.
2938
namespace cpp {
2939
2940
// The maximum allowed nesting for message declarations.
2941
// Going over this limit will make the proto definition invalid.
2942
0
constexpr int MaxMessageDeclarationNestingDepth() { return 32; }
2943
2944
// Returns true if 'enum' semantics are such that unknown values are preserved
2945
// in the enum field itself, rather than going to the UnknownFieldSet.
2946
PROTOBUF_EXPORT bool HasPreservingUnknownEnumSemantics(
2947
    const FieldDescriptor* field);
2948
2949
PROTOBUF_EXPORT bool HasHasbit(const FieldDescriptor* field);
2950
2951
#ifndef SWIG
2952
// For a string field, returns the effective ctype.  If the actual ctype is
2953
// not supported, returns the default of STRING.
2954
template <typename FieldDesc = FieldDescriptor,
2955
          typename FieldOpts = FieldOptions>
2956
typename FieldOpts::CType EffectiveStringCType(const FieldDesc* field) {
2957
  // TODO Replace this function with
2958
  // FieldDescriptor::cpp_string_type;
2959
  switch (field->cpp_string_type()) {
2960
    case FieldDescriptor::CppStringType::kCord:
2961
      return FieldOpts::CORD;
2962
    default:
2963
      return FieldOpts::STRING;
2964
  }
2965
}
2966
2967
enum class Utf8CheckMode : uint8_t {
2968
  kStrict = 0,  // Parsing will fail if non UTF-8 data is in string fields.
2969
  kVerify = 1,  // Only log an error but parsing will succeed.
2970
  kNone = 2,    // No UTF-8 check.
2971
};
2972
PROTOBUF_EXPORT Utf8CheckMode GetUtf8CheckMode(const FieldDescriptor* field,
2973
                                               bool is_lite);
2974
2975
// Returns true if the field is a "group-like field" consistent with a proto2
2976
// group:
2977
//  - Message encoding is DELIMITED (synonymous with type TYPE_GROUP)
2978
//  - Field name is exactly the message name lowercased
2979
//  - Message is defined within the same scope as the field
2980
PROTOBUF_EXPORT bool IsGroupLike(const FieldDescriptor& field);
2981
2982
// Returns whether or not this file is lazily initialized rather than
2983
// pre-main via static initialization.  This has to be done for our bootstrapped
2984
// protos to avoid linker bloat in lite runtimes.
2985
PROTOBUF_EXPORT bool IsLazilyInitializedFile(absl::string_view filename);
2986
2987
// Returns true during internal calls that should avoid calling trackers.  These
2988
// calls can be particularly dangerous during build steps like feature
2989
// resolution, where a MergeFrom call can wind up in a deadlock.
2990
PROTOBUF_EXPORT bool IsTrackingEnabled();
2991
2992
template <typename F>
2993
auto VisitDescriptorsInFileOrder(const Descriptor* desc,
2994
                                 F& f) -> decltype(f(desc)) {
2995
  for (int i = 0; i < desc->nested_type_count(); i++) {
2996
    if (auto res = VisitDescriptorsInFileOrder(desc->nested_type(i), f)) {
2997
      return res;
2998
    }
2999
  }
3000
  if (auto res = f(desc)) return res;
3001
  return {};
3002
}
3003
3004
// Visit the messages in post-order traversal.
3005
// We need several pieces of code to follow the same order because we use the
3006
// index of types during array lookups.
3007
// If any call returns a "truthy" value, it stops visitation and returns that
3008
// value right away. Otherwise returns `{}` after visiting all types.
3009
template <typename F>
3010
auto VisitDescriptorsInFileOrder(const FileDescriptor* file,
3011
                                 F f) -> decltype(f(file->message_type(0))) {
3012
  for (int i = 0; i < file->message_type_count(); i++) {
3013
    if (auto res = VisitDescriptorsInFileOrder(file->message_type(i), f)) {
3014
      return res;
3015
    }
3016
  }
3017
  return {};
3018
}
3019
#endif  // !SWIG
3020
3021
}  // namespace cpp
3022
}  // namespace internal
3023
3024
}  // namespace protobuf
3025
}  // namespace google
3026
3027
#undef PROTOBUF_INTERNAL_CHECK_CLASS_SIZE
3028
#include "google/protobuf/port_undef.inc"
3029
3030
#endif  // GOOGLE_PROTOBUF_DESCRIPTOR_H__