1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 // * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 // * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 // * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 // Author: kenton@google.com (Kenton Varda)
32 // Based on original Protocol Buffers design by
33 // Sanjay Ghemawat, Jeff Dean, and others.
34 //
35 // This file contains classes which describe a type of protocol message.
36 // You can use a message's descriptor to learn at runtime what fields
37 // it contains and what the types of those fields are. The Message
38 // interface also allows you to dynamically access and modify individual
39 // fields by passing the FieldDescriptor of the field you are interested
40 // in.
41 //
42 // Most users will not care about descriptors, because they will write
43 // code specific to certain protocol types and will simply use the classes
44 // generated by the protocol compiler directly. Advanced users who want
45 // to operate on arbitrary types (not known at compile time) may want to
46 // read descriptors in order to learn about the contents of a message.
47 // A very small number of users will want to construct their own
48 // Descriptors, either because they are implementing Message manually or
49 // because they are writing something like the protocol compiler.
50 //
51 // For an example of how you might use descriptors, see the code example
52 // at the top of message.h.
53
54 #ifndef GOOGLE_PROTOBUF_DESCRIPTOR_H__
55 #define GOOGLE_PROTOBUF_DESCRIPTOR_H__
56
57 #include <atomic>
58 #include <map>
59 #include <memory>
60 #include <set>
61 #include <string>
62 #include <vector>
63
64 #include <google/protobuf/stubs/common.h>
65 #include <google/protobuf/stubs/logging.h>
66 #include <google/protobuf/stubs/mutex.h>
67 #include <google/protobuf/stubs/once.h>
68 #include <google/protobuf/port.h>
69 #include <google/protobuf/port_def.inc>
70
71 // TYPE_BOOL is defined in the MacOS's ConditionalMacros.h.
72 #ifdef TYPE_BOOL
73 #undef TYPE_BOOL
74 #endif // TYPE_BOOL
75
76 #ifdef SWIG
77 #define PROTOBUF_EXPORT
78 #endif
79
80
81 namespace google {
82 namespace protobuf {
83
84 // Defined in this file.
85 class Descriptor;
86 class FieldDescriptor;
87 class OneofDescriptor;
88 class EnumDescriptor;
89 class EnumValueDescriptor;
90 class ServiceDescriptor;
91 class MethodDescriptor;
92 class FileDescriptor;
93 class DescriptorDatabase;
94 class DescriptorPool;
95
96 // Defined in descriptor.proto
97 class DescriptorProto;
98 class DescriptorProto_ExtensionRange;
99 class FieldDescriptorProto;
100 class OneofDescriptorProto;
101 class EnumDescriptorProto;
102 class EnumValueDescriptorProto;
103 class ServiceDescriptorProto;
104 class MethodDescriptorProto;
105 class FileDescriptorProto;
106 class MessageOptions;
107 class FieldOptions;
108 class OneofOptions;
109 class EnumOptions;
110 class EnumValueOptions;
111 class ExtensionRangeOptions;
112 class ServiceOptions;
113 class MethodOptions;
114 class FileOptions;
115 class UninterpretedOption;
116 class SourceCodeInfo;
117
118 // Defined in message.h
119 class Message;
120 class Reflection;
121
122 // Defined in descriptor.cc
123 class DescriptorBuilder;
124 class FileDescriptorTables;
125 class Symbol;
126
127 // Defined in unknown_field_set.h.
128 class UnknownField;
129
130 // Defined in command_line_interface.cc
131 namespace compiler {
132 class CommandLineInterface;
133 namespace cpp {
134 // Defined in helpers.h
135 class Formatter;
136 } // namespace cpp
137 } // namespace compiler
138
139 namespace descriptor_unittest {
140 class DescriptorTest;
141 } // namespace descriptor_unittest
142
143 // Defined in printer.h
144 namespace io {
145 class Printer;
146 } // namespace io
147
148 // NB, all indices are zero-based.
149 struct SourceLocation {
150 int start_line;
151 int end_line;
152 int start_column;
153 int end_column;
154
155 // Doc comments found at the source location.
156 // See the comments in SourceCodeInfo.Location (descriptor.proto) for details.
157 std::string leading_comments;
158 std::string trailing_comments;
159 std::vector<std::string> leading_detached_comments;
160 };
161
162 // Options when generating machine-parsable output from a descriptor with
163 // DebugString().
164 struct DebugStringOptions {
165 // include original user comments as recorded in SourceLocation entries. N.B.
166 // that this must be |false| by default: several other pieces of code (for
167 // example, the C++ code generation for fields in the proto compiler) rely on
168 // DebugString() output being unobstructed by user comments.
169 bool include_comments;
170 // If true, elide the braced body in the debug string.
171 bool elide_group_body;
172 bool elide_oneof_body;
173
DebugStringOptionsDebugStringOptions174 DebugStringOptions()
175 : include_comments(false),
176 elide_group_body(false),
177 elide_oneof_body(false) {
178 }
179 };
180
181 // A class to handle the simplest cases of a lazily linked descriptor
182 // for a message type that isn't built at the time of cross linking,
183 // which is needed when a pool has lazily_build_dependencies_ set.
184 // Must be instantiated as mutable in a descriptor.
185 namespace internal {
186
187 // Data required to do lazy initialization.
188 struct PROTOBUF_EXPORT LazyInitData {
189 #ifndef SWIG
190 internal::once_flag once;
191 #endif
192 struct Field {
193 const std::string* type_name;
194 const std::string* default_value_enum_name;
195 };
196 struct Descriptor {
197 const std::string* name;
198 const FileDescriptor* file;
199 };
200 struct File {
201 const std::string** dependencies_names;
202 };
203 union {
204 Field field;
205 Descriptor descriptor;
206 File file;
207 };
208 };
209
210 class PROTOBUF_EXPORT LazyDescriptor {
211 public:
212 // Init function to be called at init time of a descriptor containing
213 // a LazyDescriptor.
Init()214 void Init() {
215 descriptor_ = nullptr;
216 once_ = nullptr;
217 }
218
219 // Sets the value of the descriptor if it is known during the descriptor
220 // building process. Not thread safe, should only be called during the
221 // descriptor build process. Should not be called after SetLazy has been
222 // called.
223 void Set(const Descriptor* descriptor);
224
225 // Sets the information needed to lazily cross link the descriptor at a later
226 // time, SetLazy is not thread safe, should be called only once at descriptor
227 // build time if the symbol wasn't found and building of the file containing
228 // that type is delayed because lazily_build_dependencies_ is set on the pool.
229 // Should not be called after Set() has been called.
230 void SetLazy(StringPiece name, const FileDescriptor* file);
231
232 // Returns the current value of the descriptor, thread-safe. If SetLazy(...)
233 // has been called, will do a one-time cross link of the type specified,
234 // building the descriptor file that contains the type if necessary.
Get()235 inline const Descriptor* Get() {
236 Once();
237 return descriptor_;
238 }
239
240 private:
241 static void OnceStatic(LazyDescriptor* lazy);
242 void OnceInternal();
243 void Once();
244
245 const Descriptor* descriptor_;
246 LazyInitData* once_;
247 };
248
249 class PROTOBUF_EXPORT SymbolBase {
250 private:
251 friend class google::protobuf::Symbol;
252 uint8_t symbol_type_;
253 };
254
255 // Some types have more than one SymbolBase because they have multiple
256 // identities in the table. We can't have duplicate direct bases, so we use this
257 // intermediate base to do so.
258 // See BuildEnumValue for details.
259 template <int N>
260 class PROTOBUF_EXPORT SymbolBaseN : public SymbolBase {};
261
262 } // namespace internal
263
264 // Describes a type of protocol message, or a particular group within a
265 // message. To obtain the Descriptor for a given message object, call
266 // Message::GetDescriptor(). Generated message classes also have a
267 // static method called descriptor() which returns the type's descriptor.
268 // Use DescriptorPool to construct your own descriptors.
269 class PROTOBUF_EXPORT Descriptor : private internal::SymbolBase {
270 public:
271 typedef DescriptorProto Proto;
272
273 // The name of the message type, not including its scope.
274 const std::string& name() const;
275
276 // The fully-qualified name of the message type, scope delimited by
277 // periods. For example, message type "Foo" which is declared in package
278 // "bar" has full name "bar.Foo". If a type "Baz" is nested within
279 // Foo, Baz's full_name is "bar.Foo.Baz". To get only the part that
280 // comes after the last '.', use name().
281 const std::string& full_name() const;
282
283 // Index of this descriptor within the file or containing type's message
284 // type array.
285 int index() const;
286
287 // The .proto file in which this message type was defined. Never nullptr.
288 const FileDescriptor* file() const;
289
290 // If this Descriptor describes a nested type, this returns the type
291 // in which it is nested. Otherwise, returns nullptr.
292 const Descriptor* containing_type() const;
293
294 // Get options for this message type. These are specified in the .proto file
295 // by placing lines like "option foo = 1234;" in the message definition.
296 // Allowed options are defined by MessageOptions in descriptor.proto, and any
297 // available extensions of that message.
298 const MessageOptions& options() const;
299
300 // Write the contents of this Descriptor into the given DescriptorProto.
301 // The target DescriptorProto must be clear before calling this; if it
302 // isn't, the result may be garbage.
303 void CopyTo(DescriptorProto* proto) const;
304
305 // Write the contents of this descriptor in a human-readable form. Output
306 // will be suitable for re-parsing.
307 std::string DebugString() const;
308
309 // Similar to DebugString(), but additionally takes options (e.g.,
310 // include original user comments in output).
311 std::string DebugStringWithOptions(const DebugStringOptions& options) const;
312
313 // Returns true if this is a placeholder for an unknown type. This will
314 // only be the case if this descriptor comes from a DescriptorPool
315 // with AllowUnknownDependencies() set.
316 bool is_placeholder() const;
317
318 enum WellKnownType {
319 WELLKNOWNTYPE_UNSPECIFIED, // Not a well-known type.
320
321 // Wrapper types.
322 WELLKNOWNTYPE_DOUBLEVALUE, // google.protobuf.DoubleValue
323 WELLKNOWNTYPE_FLOATVALUE, // google.protobuf.FloatValue
324 WELLKNOWNTYPE_INT64VALUE, // google.protobuf.Int64Value
325 WELLKNOWNTYPE_UINT64VALUE, // google.protobuf.UInt64Value
326 WELLKNOWNTYPE_INT32VALUE, // google.protobuf.Int32Value
327 WELLKNOWNTYPE_UINT32VALUE, // google.protobuf.UInt32Value
328 WELLKNOWNTYPE_STRINGVALUE, // google.protobuf.StringValue
329 WELLKNOWNTYPE_BYTESVALUE, // google.protobuf.BytesValue
330 WELLKNOWNTYPE_BOOLVALUE, // google.protobuf.BoolValue
331
332 // Other well known types.
333 WELLKNOWNTYPE_ANY, // google.protobuf.Any
334 WELLKNOWNTYPE_FIELDMASK, // google.protobuf.FieldMask
335 WELLKNOWNTYPE_DURATION, // google.protobuf.Duration
336 WELLKNOWNTYPE_TIMESTAMP, // google.protobuf.Timestamp
337 WELLKNOWNTYPE_VALUE, // google.protobuf.Value
338 WELLKNOWNTYPE_LISTVALUE, // google.protobuf.ListValue
339 WELLKNOWNTYPE_STRUCT, // google.protobuf.Struct
340
341 // New well-known types may be added in the future.
342 // Please make sure any switch() statements have a 'default' case.
343 __WELLKNOWNTYPE__DO_NOT_USE__ADD_DEFAULT_INSTEAD__,
344 };
345
346 WellKnownType well_known_type() const;
347
348 // Field stuff -----------------------------------------------------
349
350 // The number of fields in this message type.
351 int field_count() const;
352 // Gets a field by index, where 0 <= index < field_count().
353 // These are returned in the order they were defined in the .proto file.
354 const FieldDescriptor* field(int index) const;
355
356 // Looks up a field by declared tag number. Returns nullptr if no such field
357 // exists.
358 const FieldDescriptor* FindFieldByNumber(int number) const;
359 // Looks up a field by name. Returns nullptr if no such field exists.
360 const FieldDescriptor* FindFieldByName(ConstStringParam name) const;
361
362 // Looks up a field by lowercased name (as returned by lowercase_name()).
363 // This lookup may be ambiguous if multiple field names differ only by case,
364 // in which case the field returned is chosen arbitrarily from the matches.
365 const FieldDescriptor* FindFieldByLowercaseName(
366 ConstStringParam lowercase_name) const;
367
368 // Looks up a field by camel-case name (as returned by camelcase_name()).
369 // This lookup may be ambiguous if multiple field names differ in a way that
370 // leads them to have identical camel-case names, in which case the field
371 // returned is chosen arbitrarily from the matches.
372 const FieldDescriptor* FindFieldByCamelcaseName(
373 ConstStringParam camelcase_name) const;
374
375 // The number of oneofs in this message type.
376 int oneof_decl_count() const;
377 // The number of oneofs in this message type, excluding synthetic oneofs.
378 // Real oneofs always come first, so iterating up to real_oneof_decl_cout()
379 // will yield all real oneofs.
380 int real_oneof_decl_count() const;
381 // Get a oneof by index, where 0 <= index < oneof_decl_count().
382 // These are returned in the order they were defined in the .proto file.
383 const OneofDescriptor* oneof_decl(int index) const;
384
385 // Looks up a oneof by name. Returns nullptr if no such oneof exists.
386 const OneofDescriptor* FindOneofByName(ConstStringParam name) const;
387
388 // Nested type stuff -----------------------------------------------
389
390 // The number of nested types in this message type.
391 int nested_type_count() const;
392 // Gets a nested type by index, where 0 <= index < nested_type_count().
393 // These are returned in the order they were defined in the .proto file.
394 const Descriptor* nested_type(int index) const;
395
396 // Looks up a nested type by name. Returns nullptr if no such nested type
397 // exists.
398 const Descriptor* FindNestedTypeByName(ConstStringParam name) const;
399
400 // Enum stuff ------------------------------------------------------
401
402 // The number of enum types in this message type.
403 int enum_type_count() const;
404 // Gets an enum type by index, where 0 <= index < enum_type_count().
405 // These are returned in the order they were defined in the .proto file.
406 const EnumDescriptor* enum_type(int index) const;
407
408 // Looks up an enum type by name. Returns nullptr if no such enum type
409 // exists.
410 const EnumDescriptor* FindEnumTypeByName(ConstStringParam name) const;
411
412 // Looks up an enum value by name, among all enum types in this message.
413 // Returns nullptr if no such value exists.
414 const EnumValueDescriptor* FindEnumValueByName(ConstStringParam name) const;
415
416 // Extensions ------------------------------------------------------
417
418 // A range of field numbers which are designated for third-party
419 // extensions.
420 struct ExtensionRange {
421 typedef DescriptorProto_ExtensionRange Proto;
422
423 typedef ExtensionRangeOptions OptionsType;
424
425 // See Descriptor::CopyTo().
426 void CopyTo(DescriptorProto_ExtensionRange* proto) const;
427
428 int start; // inclusive
429 int end; // exclusive
430
431 const ExtensionRangeOptions* options_;
432 };
433
434 // The number of extension ranges in this message type.
435 int extension_range_count() const;
436 // Gets an extension range by index, where 0 <= index <
437 // extension_range_count(). These are returned in the order they were defined
438 // in the .proto file.
439 const ExtensionRange* extension_range(int index) const;
440
441 // Returns true if the number is in one of the extension ranges.
442 bool IsExtensionNumber(int number) const;
443
444 // Returns nullptr if no extension range contains the given number.
445 const ExtensionRange* FindExtensionRangeContainingNumber(int number) const;
446
447 // The number of extensions defined nested within this message type's scope.
448 // See doc:
449 // https://developers.google.com/protocol-buffers/docs/proto#nested-extensions
450 //
451 // Note that the extensions may be extending *other* messages.
452 //
453 // For example:
454 // message M1 {
455 // extensions 1 to max;
456 // }
457 //
458 // message M2 {
459 // extend M1 {
460 // optional int32 foo = 1;
461 // }
462 // }
463 //
464 // In this case,
465 // DescriptorPool::generated_pool()
466 // ->FindMessageTypeByName("M2")
467 // ->extension(0)
468 // will return "foo", even though "foo" is an extension of M1.
469 // To find all known extensions of a given message, instead use
470 // DescriptorPool::FindAllExtensions.
471 int extension_count() const;
472 // Get an extension by index, where 0 <= index < extension_count().
473 // These are returned in the order they were defined in the .proto file.
474 const FieldDescriptor* extension(int index) const;
475
476 // Looks up a named extension (which extends some *other* message type)
477 // defined within this message type's scope.
478 const FieldDescriptor* FindExtensionByName(ConstStringParam name) const;
479
480 // Similar to FindFieldByLowercaseName(), but finds extensions defined within
481 // this message type's scope.
482 const FieldDescriptor* FindExtensionByLowercaseName(
483 ConstStringParam name) const;
484
485 // Similar to FindFieldByCamelcaseName(), but finds extensions defined within
486 // this message type's scope.
487 const FieldDescriptor* FindExtensionByCamelcaseName(
488 ConstStringParam name) const;
489
490 // Reserved fields -------------------------------------------------
491
492 // A range of reserved field numbers.
493 struct ReservedRange {
494 int start; // inclusive
495 int end; // exclusive
496 };
497
498 // The number of reserved ranges in this message type.
499 int reserved_range_count() const;
500 // Gets an reserved range by index, where 0 <= index <
501 // reserved_range_count(). These are returned in the order they were defined
502 // in the .proto file.
503 const ReservedRange* reserved_range(int index) const;
504
505 // Returns true if the number is in one of the reserved ranges.
506 bool IsReservedNumber(int number) const;
507
508 // Returns nullptr if no reserved range contains the given number.
509 const ReservedRange* FindReservedRangeContainingNumber(int number) const;
510
511 // The number of reserved field names in this message type.
512 int reserved_name_count() const;
513
514 // Gets a reserved name by index, where 0 <= index < reserved_name_count().
515 const std::string& reserved_name(int index) const;
516
517 // Returns true if the field name is reserved.
518 bool IsReservedName(ConstStringParam name) const;
519
520 // Source Location ---------------------------------------------------
521
522 // Updates |*out_location| to the source location of the complete
523 // extent of this message declaration. Returns false and leaves
524 // |*out_location| unchanged iff location information was not available.
525 bool GetSourceLocation(SourceLocation* out_location) const;
526
527 // Maps --------------------------------------------------------------
528
529 // Returns the FieldDescriptor for the "key" field. If this isn't a map entry
530 // field, returns nullptr.
531 const FieldDescriptor* map_key() const;
532
533 // Returns the FieldDescriptor for the "value" field. If this isn't a map
534 // entry field, returns nullptr.
535 const FieldDescriptor* map_value() const;
536
537 private:
538 friend class Symbol;
539 typedef MessageOptions OptionsType;
540
541 // Allows tests to test CopyTo(proto, true).
542 friend class descriptor_unittest::DescriptorTest;
543
544 // Allows access to GetLocationPath for annotations.
545 friend class io::Printer;
546 friend class compiler::cpp::Formatter;
547
548 // Fill the json_name field of FieldDescriptorProto.
549 void CopyJsonNameTo(DescriptorProto* proto) const;
550
551 // Internal version of DebugString; controls the level of indenting for
552 // correct depth. Takes |options| to control debug-string options, and
553 // |include_opening_clause| to indicate whether the "message ... " part of the
554 // clause has already been generated (this varies depending on context).
555 void DebugString(int depth, std::string* contents,
556 const DebugStringOptions& options,
557 bool include_opening_clause) const;
558
559 // Walks up the descriptor tree to generate the source location path
560 // to this descriptor from the file root.
561 void GetLocationPath(std::vector<int>* output) const;
562
563 // True if this is a placeholder for an unknown type.
564 bool is_placeholder_ : 1;
565 // True if this is a placeholder and the type name wasn't fully-qualified.
566 bool is_unqualified_placeholder_ : 1;
567 // Well known type. Stored as char to conserve space.
568 char well_known_type_;
569 int field_count_;
570
571 // all_names_ = [name, full_name]
572 const std::string* all_names_;
573 const FileDescriptor* file_;
574 const Descriptor* containing_type_;
575 const MessageOptions* options_;
576
577 // These arrays are separated from their sizes to minimize padding on 64-bit.
578 FieldDescriptor* fields_;
579 OneofDescriptor* oneof_decls_;
580 Descriptor* nested_types_;
581 EnumDescriptor* enum_types_;
582 ExtensionRange* extension_ranges_;
583 FieldDescriptor* extensions_;
584 ReservedRange* reserved_ranges_;
585 const std::string** reserved_names_;
586
587 int oneof_decl_count_;
588 int real_oneof_decl_count_;
589 int nested_type_count_;
590 int enum_type_count_;
591 int extension_range_count_;
592 int extension_count_;
593 int reserved_range_count_;
594 int reserved_name_count_;
595
596 // IMPORTANT: If you add a new field, make sure to search for all instances
597 // of Allocate<Descriptor>() and AllocateArray<Descriptor>() in descriptor.cc
598 // and update them to initialize the field.
599
600 // Must be constructed using DescriptorPool.
Descriptor()601 Descriptor() {}
602 friend class DescriptorBuilder;
603 friend class DescriptorPool;
604 friend class EnumDescriptor;
605 friend class FieldDescriptor;
606 friend class OneofDescriptor;
607 friend class MethodDescriptor;
608 friend class FileDescriptor;
609 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Descriptor);
610 };
611
612
613 // Describes a single field of a message. To get the descriptor for a given
614 // field, first get the Descriptor for the message in which it is defined,
615 // then call Descriptor::FindFieldByName(). To get a FieldDescriptor for
616 // an extension, do one of the following:
617 // - Get the Descriptor or FileDescriptor for its containing scope, then
618 // call Descriptor::FindExtensionByName() or
619 // FileDescriptor::FindExtensionByName().
620 // - Given a DescriptorPool, call DescriptorPool::FindExtensionByNumber() or
621 // DescriptorPool::FindExtensionByPrintableName().
622 // Use DescriptorPool to construct your own descriptors.
623 class PROTOBUF_EXPORT FieldDescriptor : private internal::SymbolBase {
624 public:
625 typedef FieldDescriptorProto Proto;
626
627 // Identifies a field type. 0 is reserved for errors. The order is weird
628 // for historical reasons. Types 12 and up are new in proto2.
629 enum Type {
630 TYPE_DOUBLE = 1, // double, exactly eight bytes on the wire.
631 TYPE_FLOAT = 2, // float, exactly four bytes on the wire.
632 TYPE_INT64 = 3, // int64, varint on the wire. Negative numbers
633 // take 10 bytes. Use TYPE_SINT64 if negative
634 // values are likely.
635 TYPE_UINT64 = 4, // uint64, varint on the wire.
636 TYPE_INT32 = 5, // int32, varint on the wire. Negative numbers
637 // take 10 bytes. Use TYPE_SINT32 if negative
638 // values are likely.
639 TYPE_FIXED64 = 6, // uint64, exactly eight bytes on the wire.
640 TYPE_FIXED32 = 7, // uint32, exactly four bytes on the wire.
641 TYPE_BOOL = 8, // bool, varint on the wire.
642 TYPE_STRING = 9, // UTF-8 text.
643 TYPE_GROUP = 10, // Tag-delimited message. Deprecated.
644 TYPE_MESSAGE = 11, // Length-delimited message.
645
646 TYPE_BYTES = 12, // Arbitrary byte array.
647 TYPE_UINT32 = 13, // uint32, varint on the wire
648 TYPE_ENUM = 14, // Enum, varint on the wire
649 TYPE_SFIXED32 = 15, // int32, exactly four bytes on the wire
650 TYPE_SFIXED64 = 16, // int64, exactly eight bytes on the wire
651 TYPE_SINT32 = 17, // int32, ZigZag-encoded varint on the wire
652 TYPE_SINT64 = 18, // int64, ZigZag-encoded varint on the wire
653
654 MAX_TYPE = 18, // Constant useful for defining lookup tables
655 // indexed by Type.
656 };
657
658 // Specifies the C++ data type used to represent the field. There is a
659 // fixed mapping from Type to CppType where each Type maps to exactly one
660 // CppType. 0 is reserved for errors.
661 enum CppType {
662 CPPTYPE_INT32 = 1, // TYPE_INT32, TYPE_SINT32, TYPE_SFIXED32
663 CPPTYPE_INT64 = 2, // TYPE_INT64, TYPE_SINT64, TYPE_SFIXED64
664 CPPTYPE_UINT32 = 3, // TYPE_UINT32, TYPE_FIXED32
665 CPPTYPE_UINT64 = 4, // TYPE_UINT64, TYPE_FIXED64
666 CPPTYPE_DOUBLE = 5, // TYPE_DOUBLE
667 CPPTYPE_FLOAT = 6, // TYPE_FLOAT
668 CPPTYPE_BOOL = 7, // TYPE_BOOL
669 CPPTYPE_ENUM = 8, // TYPE_ENUM
670 CPPTYPE_STRING = 9, // TYPE_STRING, TYPE_BYTES
671 CPPTYPE_MESSAGE = 10, // TYPE_MESSAGE, TYPE_GROUP
672
673 MAX_CPPTYPE = 10, // Constant useful for defining lookup tables
674 // indexed by CppType.
675 };
676
677 // Identifies whether the field is optional, required, or repeated. 0 is
678 // reserved for errors.
679 enum Label {
680 LABEL_OPTIONAL = 1, // optional
681 LABEL_REQUIRED = 2, // required
682 LABEL_REPEATED = 3, // repeated
683
684 MAX_LABEL = 3, // Constant useful for defining lookup tables
685 // indexed by Label.
686 };
687
688 // Valid field numbers are positive integers up to kMaxNumber.
689 static const int kMaxNumber = (1 << 29) - 1;
690
691 // First field number reserved for the protocol buffer library implementation.
692 // Users may not declare fields that use reserved numbers.
693 static const int kFirstReservedNumber = 19000;
694 // Last field number reserved for the protocol buffer library implementation.
695 // Users may not declare fields that use reserved numbers.
696 static const int kLastReservedNumber = 19999;
697
698 const std::string& name() const; // Name of this field within the message.
699 const std::string& full_name() const; // Fully-qualified name of the field.
700 const std::string& json_name() const; // JSON name of this field.
701 const FileDescriptor* file() const; // File in which this field was defined.
702 bool is_extension() const; // Is this an extension field?
703 int number() const; // Declared tag number.
704
705 // Same as name() except converted to lower-case. This (and especially the
706 // FindFieldByLowercaseName() method) can be useful when parsing formats
707 // which prefer to use lowercase naming style. (Although, technically
708 // field names should be lowercased anyway according to the protobuf style
709 // guide, so this only makes a difference when dealing with old .proto files
710 // which do not follow the guide.)
711 const std::string& lowercase_name() const;
712
713 // Same as name() except converted to camel-case. In this conversion, any
714 // time an underscore appears in the name, it is removed and the next
715 // letter is capitalized. Furthermore, the first letter of the name is
716 // lower-cased. Examples:
717 // FooBar -> fooBar
718 // foo_bar -> fooBar
719 // fooBar -> fooBar
720 // This (and especially the FindFieldByCamelcaseName() method) can be useful
721 // when parsing formats which prefer to use camel-case naming style.
722 const std::string& camelcase_name() const;
723
724 Type type() const; // Declared type of this field.
725 const char* type_name() const; // Name of the declared type.
726 CppType cpp_type() const; // C++ type of this field.
727 const char* cpp_type_name() const; // Name of the C++ type.
728 Label label() const; // optional/required/repeated
729
730 bool is_required() const; // shorthand for label() == LABEL_REQUIRED
731 bool is_optional() const; // shorthand for label() == LABEL_OPTIONAL
732 bool is_repeated() const; // shorthand for label() == LABEL_REPEATED
733 bool is_packable() const; // shorthand for is_repeated() &&
734 // IsTypePackable(type())
735 bool is_packed() const; // shorthand for is_packable() &&
736 // options().packed()
737 bool is_map() const; // shorthand for type() == TYPE_MESSAGE &&
738 // message_type()->options().map_entry()
739
740 // Returns true if this field was syntactically written with "optional" in the
741 // .proto file. Excludes singular proto3 fields that do not have a label.
742 bool has_optional_keyword() const;
743
744 // Returns true if this field tracks presence, ie. does the field
745 // distinguish between "unset" and "present with default value."
746 // This includes required, optional, and oneof fields. It excludes maps,
747 // repeated fields, and singular proto3 fields without "optional".
748 //
749 // For fields where has_presence() == true, the return value of
750 // Reflection::HasField() is semantically meaningful.
751 bool has_presence() const;
752
753 // Index of this field within the message's field array, or the file or
754 // extension scope's extensions array.
755 int index() const;
756
757 // Does this field have an explicitly-declared default value?
758 bool has_default_value() const;
759
760 // Whether the user has specified the json_name field option in the .proto
761 // file.
762 bool has_json_name() const;
763
764 // Get the field default value if cpp_type() == CPPTYPE_INT32. If no
765 // explicit default was defined, the default is 0.
766 int32_t default_value_int32_t() const;
default_value_int32()767 int32_t default_value_int32() const { return default_value_int32_t(); }
768 // Get the field default value if cpp_type() == CPPTYPE_INT64. If no
769 // explicit default was defined, the default is 0.
770 int64_t default_value_int64_t() const;
default_value_int64()771 int64_t default_value_int64() const { return default_value_int64_t(); }
772 // Get the field default value if cpp_type() == CPPTYPE_UINT32. If no
773 // explicit default was defined, the default is 0.
774 uint32_t default_value_uint32_t() const;
default_value_uint32()775 uint32_t default_value_uint32() const { return default_value_uint32_t(); }
776 // Get the field default value if cpp_type() == CPPTYPE_UINT64. If no
777 // explicit default was defined, the default is 0.
778 uint64_t default_value_uint64_t() const;
default_value_uint64()779 uint64_t default_value_uint64() const { return default_value_uint64_t(); }
780 // Get the field default value if cpp_type() == CPPTYPE_FLOAT. If no
781 // explicit default was defined, the default is 0.0.
782 float default_value_float() const;
783 // Get the field default value if cpp_type() == CPPTYPE_DOUBLE. If no
784 // explicit default was defined, the default is 0.0.
785 double default_value_double() const;
786 // Get the field default value if cpp_type() == CPPTYPE_BOOL. If no
787 // explicit default was defined, the default is false.
788 bool default_value_bool() const;
789 // Get the field default value if cpp_type() == CPPTYPE_ENUM. If no
790 // explicit default was defined, the default is the first value defined
791 // in the enum type (all enum types are required to have at least one value).
792 // This never returns nullptr.
793 const EnumValueDescriptor* default_value_enum() const;
794 // Get the field default value if cpp_type() == CPPTYPE_STRING. If no
795 // explicit default was defined, the default is the empty string.
796 const std::string& default_value_string() const;
797
798 // The Descriptor for the message of which this is a field. For extensions,
799 // this is the extended type. Never nullptr.
800 const Descriptor* containing_type() const;
801
802 // If the field is a member of a oneof, this is the one, otherwise this is
803 // nullptr.
804 const OneofDescriptor* containing_oneof() const;
805
806 // If the field is a member of a non-synthetic oneof, returns the descriptor
807 // for the oneof, otherwise returns nullptr.
808 const OneofDescriptor* real_containing_oneof() const;
809
810 // If the field is a member of a oneof, returns the index in that oneof.
811 int index_in_oneof() const;
812
813 // An extension may be declared within the scope of another message. If this
814 // field is an extension (is_extension() is true), then extension_scope()
815 // returns that message, or nullptr if the extension was declared at global
816 // scope. If this is not an extension, extension_scope() is undefined (may
817 // assert-fail).
818 const Descriptor* extension_scope() const;
819
820 // If type is TYPE_MESSAGE or TYPE_GROUP, returns a descriptor for the
821 // message or the group type. Otherwise, returns null.
822 const Descriptor* message_type() const;
823 // If type is TYPE_ENUM, returns a descriptor for the enum. Otherwise,
824 // returns null.
825 const EnumDescriptor* enum_type() const;
826
827 // Get the FieldOptions for this field. This includes things listed in
828 // square brackets after the field definition. E.g., the field:
829 // optional string text = 1 [ctype=CORD];
830 // has the "ctype" option set. Allowed options are defined by FieldOptions in
831 // descriptor.proto, and any available extensions of that message.
832 const FieldOptions& options() const;
833
834 // See Descriptor::CopyTo().
835 void CopyTo(FieldDescriptorProto* proto) const;
836
837 // See Descriptor::DebugString().
838 std::string DebugString() const;
839
840 // See Descriptor::DebugStringWithOptions().
841 std::string DebugStringWithOptions(const DebugStringOptions& options) const;
842
843 // Helper method to get the CppType for a particular Type.
844 static CppType TypeToCppType(Type type);
845
846 // Helper method to get the name of a Type.
847 static const char* TypeName(Type type);
848
849 // Helper method to get the name of a CppType.
850 static const char* CppTypeName(CppType cpp_type);
851
852 // Return true iff [packed = true] is valid for fields of this type.
853 static inline bool IsTypePackable(Type field_type);
854
855 // Returns full_name() except if the field is a MessageSet extension,
856 // in which case it returns the full_name() of the containing message type
857 // for backwards compatibility with proto1.
858 //
859 // A MessageSet extension is defined as an optional message extension
860 // whose containing type has the message_set_wire_format option set.
861 // This should be true of extensions of google.protobuf.bridge.MessageSet;
862 // by convention, such extensions are named "message_set_extension".
863 //
864 // The opposite operation (looking up an extension's FieldDescriptor given
865 // its printable name) can be accomplished with
866 // message->file()->pool()->FindExtensionByPrintableName(message, name)
867 // where the extension extends "message".
868 const std::string& PrintableNameForExtension() const;
869
870 // Source Location ---------------------------------------------------
871
872 // Updates |*out_location| to the source location of the complete
873 // extent of this field declaration. Returns false and leaves
874 // |*out_location| unchanged iff location information was not available.
875 bool GetSourceLocation(SourceLocation* out_location) const;
876
877 private:
878 friend class Symbol;
879 typedef FieldOptions OptionsType;
880
881 // Allows access to GetLocationPath for annotations.
882 friend class io::Printer;
883 friend class compiler::cpp::Formatter;
884 friend class Reflection;
885
886 // Fill the json_name field of FieldDescriptorProto.
887 void CopyJsonNameTo(FieldDescriptorProto* proto) const;
888
889 // See Descriptor::DebugString().
890 void DebugString(int depth, std::string* contents,
891 const DebugStringOptions& options) const;
892
893 // formats the default value appropriately and returns it as a string.
894 // Must have a default value to call this. If quote_string_type is true, then
895 // types of CPPTYPE_STRING whill be surrounded by quotes and CEscaped.
896 std::string DefaultValueAsString(bool quote_string_type) const;
897
898 // Helper function that returns the field type name for DebugString.
899 std::string FieldTypeNameDebugString() const;
900
901 // Walks up the descriptor tree to generate the source location path
902 // to this descriptor from the file root.
903 void GetLocationPath(std::vector<int>* output) const;
904
905 // Returns true if this is a map message type.
906 bool is_map_message_type() const;
907
908 bool has_default_value_;
909 bool proto3_optional_;
910 // Whether the user has specified the json_name field option in the .proto
911 // file.
912 bool has_json_name_;
913 bool is_extension_;
914
915 // Actually a `Type`, but stored as uint8_t to save space.
916 mutable uint8_t type_;
917 // Actually a `Label` but stored as uint8_t to save space.
918 uint8_t label_;
919
920 bool is_oneof_ : 1;
921
922 // Logically:
923 // all_names_ = [name, full_name, lower, camel, json]
924 // However:
925 // duplicates will be omitted, so lower/camel/json might be in the same
926 // position.
927 // We store the true offset for each name here, and the bit width must be
928 // large enough to account for the worst case where all names are present.
929 uint8_t lowercase_name_index_ : 2;
930 uint8_t camelcase_name_index_ : 2;
931 uint8_t json_name_index_ : 3;
932 const std::string* all_names_;
933 const FileDescriptor* file_;
934
935 internal::LazyInitData* type_once_;
936 static void TypeOnceInit(const FieldDescriptor* to_init);
937 void InternalTypeOnceInit() const;
938 int number_;
939 int index_in_oneof_;
940 const Descriptor* containing_type_;
941 union {
942 const OneofDescriptor* containing_oneof;
943 const Descriptor* extension_scope;
944 } scope_;
945 union {
946 mutable const Descriptor* message_type;
947 mutable const EnumDescriptor* enum_type;
948 } type_descriptor_;
949 const FieldOptions* options_;
950 // IMPORTANT: If you add a new field, make sure to search for all instances
951 // of Allocate<FieldDescriptor>() and AllocateArray<FieldDescriptor>() in
952 // descriptor.cc and update them to initialize the field.
953
954 union {
955 int32_t default_value_int32_t_;
956 int64_t default_value_int64_t_;
957 uint32_t default_value_uint32_t_;
958 uint64_t default_value_uint64_t_;
959 float default_value_float_;
960 double default_value_double_;
961 bool default_value_bool_;
962
963 mutable const EnumValueDescriptor* default_value_enum_;
964 const std::string* default_value_string_;
965 mutable std::atomic<const Message*> default_generated_instance_;
966 };
967
968 static const CppType kTypeToCppTypeMap[MAX_TYPE + 1];
969
970 static const char* const kTypeToName[MAX_TYPE + 1];
971
972 static const char* const kCppTypeToName[MAX_CPPTYPE + 1];
973
974 static const char* const kLabelToName[MAX_LABEL + 1];
975
976 // Must be constructed using DescriptorPool.
FieldDescriptor()977 FieldDescriptor() {}
978 friend class DescriptorBuilder;
979 friend class FileDescriptor;
980 friend class Descriptor;
981 friend class OneofDescriptor;
982 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldDescriptor);
983 };
984
985
986 // Describes a oneof defined in a message type.
987 class PROTOBUF_EXPORT OneofDescriptor : private internal::SymbolBase {
988 public:
989 typedef OneofDescriptorProto Proto;
990
991 const std::string& name() const; // Name of this oneof.
992 const std::string& full_name() const; // Fully-qualified name of the oneof.
993
994 // Index of this oneof within the message's oneof array.
995 int index() const;
996
997 // Returns whether this oneof was inserted by the compiler to wrap a proto3
998 // optional field. If this returns true, code generators should *not* emit it.
999 bool is_synthetic() const;
1000
1001 // The .proto file in which this oneof was defined. Never nullptr.
1002 const FileDescriptor* file() const;
1003 // The Descriptor for the message containing this oneof.
1004 const Descriptor* containing_type() const;
1005
1006 // The number of (non-extension) fields which are members of this oneof.
1007 int field_count() const;
1008 // Get a member of this oneof, in the order in which they were declared in the
1009 // .proto file. Does not include extensions.
1010 const FieldDescriptor* field(int index) const;
1011
1012 const OneofOptions& options() const;
1013
1014 // See Descriptor::CopyTo().
1015 void CopyTo(OneofDescriptorProto* proto) const;
1016
1017 // See Descriptor::DebugString().
1018 std::string DebugString() const;
1019
1020 // See Descriptor::DebugStringWithOptions().
1021 std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1022
1023 // Source Location ---------------------------------------------------
1024
1025 // Updates |*out_location| to the source location of the complete
1026 // extent of this oneof declaration. Returns false and leaves
1027 // |*out_location| unchanged iff location information was not available.
1028 bool GetSourceLocation(SourceLocation* out_location) const;
1029
1030 private:
1031 friend class Symbol;
1032 typedef OneofOptions OptionsType;
1033
1034 // Allows access to GetLocationPath for annotations.
1035 friend class io::Printer;
1036 friend class compiler::cpp::Formatter;
1037
1038 // See Descriptor::DebugString().
1039 void DebugString(int depth, std::string* contents,
1040 const DebugStringOptions& options) const;
1041
1042 // Walks up the descriptor tree to generate the source location path
1043 // to this descriptor from the file root.
1044 void GetLocationPath(std::vector<int>* output) const;
1045
1046 int field_count_;
1047
1048 // all_names_ = [name, full_name]
1049 const std::string* all_names_;
1050 const Descriptor* containing_type_;
1051 const FieldDescriptor** fields_;
1052 const OneofOptions* options_;
1053
1054 // IMPORTANT: If you add a new field, make sure to search for all instances
1055 // of Allocate<OneofDescriptor>() and AllocateArray<OneofDescriptor>()
1056 // in descriptor.cc and update them to initialize the field.
1057
1058 // Must be constructed using DescriptorPool.
OneofDescriptor()1059 OneofDescriptor() {}
1060 friend class DescriptorBuilder;
1061 friend class Descriptor;
1062 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(OneofDescriptor);
1063 };
1064
1065 // Describes an enum type defined in a .proto file. To get the EnumDescriptor
1066 // for a generated enum type, call TypeName_descriptor(). Use DescriptorPool
1067 // to construct your own descriptors.
1068 class PROTOBUF_EXPORT EnumDescriptor : private internal::SymbolBase {
1069 public:
1070 typedef EnumDescriptorProto Proto;
1071
1072 // The name of this enum type in the containing scope.
1073 const std::string& name() const;
1074
1075 // The fully-qualified name of the enum type, scope delimited by periods.
1076 const std::string& full_name() const;
1077
1078 // Index of this enum within the file or containing message's enum array.
1079 int index() const;
1080
1081 // The .proto file in which this enum type was defined. Never nullptr.
1082 const FileDescriptor* file() const;
1083
1084 // The number of values for this EnumDescriptor. Guaranteed to be greater
1085 // than zero.
1086 int value_count() const;
1087 // Gets a value by index, where 0 <= index < value_count().
1088 // These are returned in the order they were defined in the .proto file.
1089 const EnumValueDescriptor* value(int index) const;
1090
1091 // Looks up a value by name. Returns nullptr if no such value exists.
1092 const EnumValueDescriptor* FindValueByName(ConstStringParam name) const;
1093 // Looks up a value by number. Returns nullptr if no such value exists. If
1094 // multiple values have this number, the first one defined is returned.
1095 const EnumValueDescriptor* FindValueByNumber(int number) const;
1096
1097 // If this enum type is nested in a message type, this is that message type.
1098 // Otherwise, nullptr.
1099 const Descriptor* containing_type() const;
1100
1101 // Get options for this enum type. These are specified in the .proto file by
1102 // placing lines like "option foo = 1234;" in the enum definition. Allowed
1103 // options are defined by EnumOptions in descriptor.proto, and any available
1104 // extensions of that message.
1105 const EnumOptions& options() const;
1106
1107 // See Descriptor::CopyTo().
1108 void CopyTo(EnumDescriptorProto* proto) const;
1109
1110 // See Descriptor::DebugString().
1111 std::string DebugString() const;
1112
1113 // See Descriptor::DebugStringWithOptions().
1114 std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1115
1116 // Returns true if this is a placeholder for an unknown enum. This will
1117 // only be the case if this descriptor comes from a DescriptorPool
1118 // with AllowUnknownDependencies() set.
1119 bool is_placeholder() const;
1120
1121 // Reserved fields -------------------------------------------------
1122
1123 // A range of reserved field numbers.
1124 struct ReservedRange {
1125 int start; // inclusive
1126 int end; // inclusive
1127 };
1128
1129 // The number of reserved ranges in this message type.
1130 int reserved_range_count() const;
1131 // Gets an reserved range by index, where 0 <= index <
1132 // reserved_range_count(). These are returned in the order they were defined
1133 // in the .proto file.
1134 const EnumDescriptor::ReservedRange* reserved_range(int index) const;
1135
1136 // Returns true if the number is in one of the reserved ranges.
1137 bool IsReservedNumber(int number) const;
1138
1139 // Returns nullptr if no reserved range contains the given number.
1140 const EnumDescriptor::ReservedRange* FindReservedRangeContainingNumber(
1141 int number) const;
1142
1143 // The number of reserved field names in this message type.
1144 int reserved_name_count() const;
1145
1146 // Gets a reserved name by index, where 0 <= index < reserved_name_count().
1147 const std::string& reserved_name(int index) const;
1148
1149 // Returns true if the field name is reserved.
1150 bool IsReservedName(ConstStringParam name) const;
1151
1152 // Source Location ---------------------------------------------------
1153
1154 // Updates |*out_location| to the source location of the complete
1155 // extent of this enum declaration. Returns false and leaves
1156 // |*out_location| unchanged iff location information was not available.
1157 bool GetSourceLocation(SourceLocation* out_location) const;
1158
1159 private:
1160 friend class Symbol;
1161 typedef EnumOptions OptionsType;
1162
1163 // Allows access to GetLocationPath for annotations.
1164 friend class io::Printer;
1165 friend class compiler::cpp::Formatter;
1166
1167 // Looks up a value by number. If the value does not exist, dynamically
1168 // creates a new EnumValueDescriptor for that value, assuming that it was
1169 // unknown. If a new descriptor is created, this is done in a thread-safe way,
1170 // and future calls will return the same value descriptor pointer.
1171 //
1172 // This is private but is used by Reflection (which is friended below) to
1173 // return a valid EnumValueDescriptor from GetEnum() when this feature is
1174 // enabled.
1175 const EnumValueDescriptor* FindValueByNumberCreatingIfUnknown(
1176 int number) const;
1177
1178 // See Descriptor::DebugString().
1179 void DebugString(int depth, std::string* contents,
1180 const DebugStringOptions& options) const;
1181
1182 // Walks up the descriptor tree to generate the source location path
1183 // to this descriptor from the file root.
1184 void GetLocationPath(std::vector<int>* output) const;
1185
1186 // True if this is a placeholder for an unknown type.
1187 bool is_placeholder_;
1188 // True if this is a placeholder and the type name wasn't fully-qualified.
1189 bool is_unqualified_placeholder_;
1190
1191 int value_count_;
1192
1193 // all_names_ = [name, full_name]
1194 const std::string* all_names_;
1195 const FileDescriptor* file_;
1196 const Descriptor* containing_type_;
1197 const EnumOptions* options_;
1198 EnumValueDescriptor* values_;
1199
1200 int reserved_range_count_;
1201 int reserved_name_count_;
1202 EnumDescriptor::ReservedRange* reserved_ranges_;
1203 const std::string** reserved_names_;
1204
1205 // IMPORTANT: If you add a new field, make sure to search for all instances
1206 // of Allocate<EnumDescriptor>() and AllocateArray<EnumDescriptor>() in
1207 // descriptor.cc and update them to initialize the field.
1208
1209 // Must be constructed using DescriptorPool.
EnumDescriptor()1210 EnumDescriptor() {}
1211 friend class DescriptorBuilder;
1212 friend class Descriptor;
1213 friend class FieldDescriptor;
1214 friend class EnumValueDescriptor;
1215 friend class FileDescriptor;
1216 friend class DescriptorPool;
1217 friend class Reflection;
1218 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumDescriptor);
1219 };
1220
1221 // Describes an individual enum constant of a particular type. To get the
1222 // EnumValueDescriptor for a given enum value, first get the EnumDescriptor
1223 // for its type, then use EnumDescriptor::FindValueByName() or
1224 // EnumDescriptor::FindValueByNumber(). Use DescriptorPool to construct
1225 // your own descriptors.
1226 class PROTOBUF_EXPORT EnumValueDescriptor : private internal::SymbolBaseN<0>,
1227 private internal::SymbolBaseN<1> {
1228 public:
1229 typedef EnumValueDescriptorProto Proto;
1230
1231 const std::string& name() const; // Name of this enum constant.
1232 int index() const; // Index within the enums's Descriptor.
1233 int number() const; // Numeric value of this enum constant.
1234
1235 // The full_name of an enum value is a sibling symbol of the enum type.
1236 // e.g. the full name of FieldDescriptorProto::TYPE_INT32 is actually
1237 // "google.protobuf.FieldDescriptorProto.TYPE_INT32", NOT
1238 // "google.protobuf.FieldDescriptorProto.Type.TYPE_INT32". This is to conform
1239 // with C++ scoping rules for enums.
1240 const std::string& full_name() const;
1241
1242 // The .proto file in which this value was defined. Never nullptr.
1243 const FileDescriptor* file() const;
1244 // The type of this value. Never nullptr.
1245 const EnumDescriptor* type() const;
1246
1247 // Get options for this enum value. These are specified in the .proto file by
1248 // adding text like "[foo = 1234]" after an enum value definition. Allowed
1249 // options are defined by EnumValueOptions in descriptor.proto, and any
1250 // available extensions of that message.
1251 const EnumValueOptions& options() const;
1252
1253 // See Descriptor::CopyTo().
1254 void CopyTo(EnumValueDescriptorProto* proto) const;
1255
1256 // See Descriptor::DebugString().
1257 std::string DebugString() const;
1258
1259 // See Descriptor::DebugStringWithOptions().
1260 std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1261
1262 // Source Location ---------------------------------------------------
1263
1264 // Updates |*out_location| to the source location of the complete
1265 // extent of this enum value declaration. Returns false and leaves
1266 // |*out_location| unchanged iff location information was not available.
1267 bool GetSourceLocation(SourceLocation* out_location) const;
1268
1269 private:
1270 friend class Symbol;
1271 typedef EnumValueOptions OptionsType;
1272
1273 // Allows access to GetLocationPath for annotations.
1274 friend class io::Printer;
1275 friend class compiler::cpp::Formatter;
1276
1277 // See Descriptor::DebugString().
1278 void DebugString(int depth, std::string* contents,
1279 const DebugStringOptions& options) const;
1280
1281 // Walks up the descriptor tree to generate the source location path
1282 // to this descriptor from the file root.
1283 void GetLocationPath(std::vector<int>* output) const;
1284
1285 int number_;
1286 // all_names_ = [name, full_name]
1287 const std::string* all_names_;
1288 const EnumDescriptor* type_;
1289 const EnumValueOptions* options_;
1290 // IMPORTANT: If you add a new field, make sure to search for all instances
1291 // of Allocate<EnumValueDescriptor>() and AllocateArray<EnumValueDescriptor>()
1292 // in descriptor.cc and update them to initialize the field.
1293
1294 // Must be constructed using DescriptorPool.
EnumValueDescriptor()1295 EnumValueDescriptor() {}
1296 friend class DescriptorBuilder;
1297 friend class EnumDescriptor;
1298 friend class DescriptorPool;
1299 friend class FileDescriptorTables;
1300 friend class Reflection;
1301 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumValueDescriptor);
1302 };
1303
1304 // Describes an RPC service. Use DescriptorPool to construct your own
1305 // descriptors.
1306 class PROTOBUF_EXPORT ServiceDescriptor : private internal::SymbolBase {
1307 public:
1308 typedef ServiceDescriptorProto Proto;
1309
1310 // The name of the service, not including its containing scope.
1311 const std::string& name() const;
1312 // The fully-qualified name of the service, scope delimited by periods.
1313 const std::string& full_name() const;
1314 // Index of this service within the file's services array.
1315 int index() const;
1316
1317 // The .proto file in which this service was defined. Never nullptr.
1318 const FileDescriptor* file() const;
1319
1320 // Get options for this service type. These are specified in the .proto file
1321 // by placing lines like "option foo = 1234;" in the service definition.
1322 // Allowed options are defined by ServiceOptions in descriptor.proto, and any
1323 // available extensions of that message.
1324 const ServiceOptions& options() const;
1325
1326 // The number of methods this service defines.
1327 int method_count() const;
1328 // Gets a MethodDescriptor by index, where 0 <= index < method_count().
1329 // These are returned in the order they were defined in the .proto file.
1330 const MethodDescriptor* method(int index) const;
1331
1332 // Look up a MethodDescriptor by name.
1333 const MethodDescriptor* FindMethodByName(ConstStringParam name) const;
1334 // See Descriptor::CopyTo().
1335 void CopyTo(ServiceDescriptorProto* proto) const;
1336
1337 // See Descriptor::DebugString().
1338 std::string DebugString() const;
1339
1340 // See Descriptor::DebugStringWithOptions().
1341 std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1342
1343 // Source Location ---------------------------------------------------
1344
1345 // Updates |*out_location| to the source location of the complete
1346 // extent of this service declaration. Returns false and leaves
1347 // |*out_location| unchanged iff location information was not available.
1348 bool GetSourceLocation(SourceLocation* out_location) const;
1349
1350 private:
1351 friend class Symbol;
1352 typedef ServiceOptions OptionsType;
1353
1354 // Allows access to GetLocationPath for annotations.
1355 friend class io::Printer;
1356 friend class compiler::cpp::Formatter;
1357
1358 // See Descriptor::DebugString().
1359 void DebugString(std::string* contents,
1360 const DebugStringOptions& options) const;
1361
1362 // Walks up the descriptor tree to generate the source location path
1363 // to this descriptor from the file root.
1364 void GetLocationPath(std::vector<int>* output) const;
1365
1366 // all_names_ = [name, full_name]
1367 const std::string* all_names_;
1368 const FileDescriptor* file_;
1369 const ServiceOptions* options_;
1370 MethodDescriptor* methods_;
1371 int method_count_;
1372 // IMPORTANT: If you add a new field, make sure to search for all instances
1373 // of Allocate<ServiceDescriptor>() and AllocateArray<ServiceDescriptor>() in
1374 // descriptor.cc and update them to initialize the field.
1375
1376 // Must be constructed using DescriptorPool.
ServiceDescriptor()1377 ServiceDescriptor() {}
1378 friend class DescriptorBuilder;
1379 friend class FileDescriptor;
1380 friend class MethodDescriptor;
1381 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ServiceDescriptor);
1382 };
1383
1384
1385 // Describes an individual service method. To obtain a MethodDescriptor given
1386 // a service, first get its ServiceDescriptor, then call
1387 // ServiceDescriptor::FindMethodByName(). Use DescriptorPool to construct your
1388 // own descriptors.
1389 class PROTOBUF_EXPORT MethodDescriptor : private internal::SymbolBase {
1390 public:
1391 typedef MethodDescriptorProto Proto;
1392
1393 // Name of this method, not including containing scope.
1394 const std::string& name() const;
1395 // The fully-qualified name of the method, scope delimited by periods.
1396 const std::string& full_name() const;
1397 // Index within the service's Descriptor.
1398 int index() const;
1399
1400 // The .proto file in which this method was defined. Never nullptr.
1401 const FileDescriptor* file() const;
1402 // Gets the service to which this method belongs. Never nullptr.
1403 const ServiceDescriptor* service() const;
1404
1405 // Gets the type of protocol message which this method accepts as input.
1406 const Descriptor* input_type() const;
1407 // Gets the type of protocol message which this message produces as output.
1408 const Descriptor* output_type() const;
1409
1410 // Gets whether the client streams multiple requests.
1411 bool client_streaming() const;
1412 // Gets whether the server streams multiple responses.
1413 bool server_streaming() const;
1414
1415 // Get options for this method. These are specified in the .proto file by
1416 // placing lines like "option foo = 1234;" in curly-braces after a method
1417 // declaration. Allowed options are defined by MethodOptions in
1418 // descriptor.proto, and any available extensions of that message.
1419 const MethodOptions& options() const;
1420
1421 // See Descriptor::CopyTo().
1422 void CopyTo(MethodDescriptorProto* proto) const;
1423
1424 // See Descriptor::DebugString().
1425 std::string DebugString() const;
1426
1427 // See Descriptor::DebugStringWithOptions().
1428 std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1429
1430 // Source Location ---------------------------------------------------
1431
1432 // Updates |*out_location| to the source location of the complete
1433 // extent of this method declaration. Returns false and leaves
1434 // |*out_location| unchanged iff location information was not available.
1435 bool GetSourceLocation(SourceLocation* out_location) const;
1436
1437 private:
1438 friend class Symbol;
1439 typedef MethodOptions OptionsType;
1440
1441 // Allows access to GetLocationPath for annotations.
1442 friend class io::Printer;
1443 friend class compiler::cpp::Formatter;
1444
1445 // See Descriptor::DebugString().
1446 void DebugString(int depth, std::string* contents,
1447 const DebugStringOptions& options) const;
1448
1449 // Walks up the descriptor tree to generate the source location path
1450 // to this descriptor from the file root.
1451 void GetLocationPath(std::vector<int>* output) const;
1452
1453 bool client_streaming_;
1454 bool server_streaming_;
1455 // all_names_ = [name, full_name]
1456 const std::string* all_names_;
1457 const ServiceDescriptor* service_;
1458 mutable internal::LazyDescriptor input_type_;
1459 mutable internal::LazyDescriptor output_type_;
1460 const MethodOptions* options_;
1461 // IMPORTANT: If you add a new field, make sure to search for all instances
1462 // of Allocate<MethodDescriptor>() and AllocateArray<MethodDescriptor>() in
1463 // descriptor.cc and update them to initialize the field.
1464
1465 // Must be constructed using DescriptorPool.
MethodDescriptor()1466 MethodDescriptor() {}
1467 friend class DescriptorBuilder;
1468 friend class ServiceDescriptor;
1469 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MethodDescriptor);
1470 };
1471
1472
1473 // Describes a whole .proto file. To get the FileDescriptor for a compiled-in
1474 // file, get the descriptor for something defined in that file and call
1475 // descriptor->file(). Use DescriptorPool to construct your own descriptors.
1476 class PROTOBUF_EXPORT FileDescriptor {
1477 public:
1478 typedef FileDescriptorProto Proto;
1479
1480 // The filename, relative to the source tree.
1481 // e.g. "foo/bar/baz.proto"
1482 const std::string& name() const;
1483
1484 // The package, e.g. "google.protobuf.compiler".
1485 const std::string& package() const;
1486
1487 // The DescriptorPool in which this FileDescriptor and all its contents were
1488 // allocated. Never nullptr.
1489 const DescriptorPool* pool() const;
1490
1491 // The number of files imported by this one.
1492 int dependency_count() const;
1493 // Gets an imported file by index, where 0 <= index < dependency_count().
1494 // These are returned in the order they were defined in the .proto file.
1495 const FileDescriptor* dependency(int index) const;
1496
1497 // The number of files public imported by this one.
1498 // The public dependency list is a subset of the dependency list.
1499 int public_dependency_count() const;
1500 // Gets a public imported file by index, where 0 <= index <
1501 // public_dependency_count().
1502 // These are returned in the order they were defined in the .proto file.
1503 const FileDescriptor* public_dependency(int index) const;
1504
1505 // The number of files that are imported for weak fields.
1506 // The weak dependency list is a subset of the dependency list.
1507 int weak_dependency_count() const;
1508 // Gets a weak imported file by index, where 0 <= index <
1509 // weak_dependency_count().
1510 // These are returned in the order they were defined in the .proto file.
1511 const FileDescriptor* weak_dependency(int index) const;
1512
1513 // Number of top-level message types defined in this file. (This does not
1514 // include nested types.)
1515 int message_type_count() const;
1516 // Gets a top-level message type, where 0 <= index < message_type_count().
1517 // These are returned in the order they were defined in the .proto file.
1518 const Descriptor* message_type(int index) const;
1519
1520 // Number of top-level enum types defined in this file. (This does not
1521 // include nested types.)
1522 int enum_type_count() const;
1523 // Gets a top-level enum type, where 0 <= index < enum_type_count().
1524 // These are returned in the order they were defined in the .proto file.
1525 const EnumDescriptor* enum_type(int index) const;
1526
1527 // Number of services defined in this file.
1528 int service_count() const;
1529 // Gets a service, where 0 <= index < service_count().
1530 // These are returned in the order they were defined in the .proto file.
1531 const ServiceDescriptor* service(int index) const;
1532
1533 // Number of extensions defined at file scope. (This does not include
1534 // extensions nested within message types.)
1535 int extension_count() const;
1536 // Gets an extension's descriptor, where 0 <= index < extension_count().
1537 // These are returned in the order they were defined in the .proto file.
1538 const FieldDescriptor* extension(int index) const;
1539
1540 // Get options for this file. These are specified in the .proto file by
1541 // placing lines like "option foo = 1234;" at the top level, outside of any
1542 // other definitions. Allowed options are defined by FileOptions in
1543 // descriptor.proto, and any available extensions of that message.
1544 const FileOptions& options() const;
1545
1546 // Syntax of this file.
1547 enum Syntax {
1548 SYNTAX_UNKNOWN = 0,
1549 SYNTAX_PROTO2 = 2,
1550 SYNTAX_PROTO3 = 3,
1551 };
1552 Syntax syntax() const;
1553 static const char* SyntaxName(Syntax syntax);
1554
1555 // Find a top-level message type by name (not full_name). Returns nullptr if
1556 // not found.
1557 const Descriptor* FindMessageTypeByName(ConstStringParam name) const;
1558 // Find a top-level enum type by name. Returns nullptr if not found.
1559 const EnumDescriptor* FindEnumTypeByName(ConstStringParam name) const;
1560 // Find an enum value defined in any top-level enum by name. Returns nullptr
1561 // if not found.
1562 const EnumValueDescriptor* FindEnumValueByName(ConstStringParam name) const;
1563 // Find a service definition by name. Returns nullptr if not found.
1564 const ServiceDescriptor* FindServiceByName(ConstStringParam name) const;
1565 // Find a top-level extension definition by name. Returns nullptr if not
1566 // found.
1567 const FieldDescriptor* FindExtensionByName(ConstStringParam name) const;
1568 // Similar to FindExtensionByName(), but searches by lowercased-name. See
1569 // Descriptor::FindFieldByLowercaseName().
1570 const FieldDescriptor* FindExtensionByLowercaseName(
1571 ConstStringParam name) const;
1572 // Similar to FindExtensionByName(), but searches by camelcased-name. See
1573 // Descriptor::FindFieldByCamelcaseName().
1574 const FieldDescriptor* FindExtensionByCamelcaseName(
1575 ConstStringParam name) const;
1576
1577 // See Descriptor::CopyTo().
1578 // Notes:
1579 // - This method does NOT copy source code information since it is relatively
1580 // large and rarely needed. See CopySourceCodeInfoTo() below.
1581 void CopyTo(FileDescriptorProto* proto) const;
1582 // Write the source code information of this FileDescriptor into the given
1583 // FileDescriptorProto. See CopyTo() above.
1584 void CopySourceCodeInfoTo(FileDescriptorProto* proto) const;
1585 // Fill the json_name field of FieldDescriptorProto for all fields. Can only
1586 // be called after CopyTo().
1587 void CopyJsonNameTo(FileDescriptorProto* proto) const;
1588
1589 // See Descriptor::DebugString().
1590 std::string DebugString() const;
1591
1592 // See Descriptor::DebugStringWithOptions().
1593 std::string DebugStringWithOptions(const DebugStringOptions& options) const;
1594
1595 // Returns true if this is a placeholder for an unknown file. This will
1596 // only be the case if this descriptor comes from a DescriptorPool
1597 // with AllowUnknownDependencies() set.
1598 bool is_placeholder() const;
1599
1600 // Updates |*out_location| to the source location of the complete extent of
1601 // this file declaration (namely, the empty path).
1602 bool GetSourceLocation(SourceLocation* out_location) const;
1603
1604 // Updates |*out_location| to the source location of the complete
1605 // extent of the declaration or declaration-part denoted by |path|.
1606 // Returns false and leaves |*out_location| unchanged iff location
1607 // information was not available. (See SourceCodeInfo for
1608 // description of path encoding.)
1609 bool GetSourceLocation(const std::vector<int>& path,
1610 SourceLocation* out_location) const;
1611
1612 private:
1613 typedef FileOptions OptionsType;
1614
1615 const std::string* name_;
1616 const std::string* package_;
1617 const DescriptorPool* pool_;
1618 internal::LazyInitData* dependencies_once_;
1619 static void DependenciesOnceInit(const FileDescriptor* to_init);
1620 void InternalDependenciesOnceInit() const;
1621
1622 // These are arranged to minimize padding on 64-bit.
1623 int dependency_count_;
1624 int public_dependency_count_;
1625 int weak_dependency_count_;
1626 int message_type_count_;
1627 int enum_type_count_;
1628 int service_count_;
1629
1630 bool is_placeholder_;
1631 // Indicates the FileDescriptor is completed building. Used to verify
1632 // that type accessor functions that can possibly build a dependent file
1633 // aren't called during the process of building the file.
1634 bool finished_building_;
1635 // Actually a `Syntax` but stored as uint8_t to save space.
1636 uint8_t syntax_;
1637 // This one is here to fill the padding.
1638 int extension_count_;
1639
1640 mutable const FileDescriptor** dependencies_;
1641 int* public_dependencies_;
1642 int* weak_dependencies_;
1643 Descriptor* message_types_;
1644 EnumDescriptor* enum_types_;
1645 ServiceDescriptor* services_;
1646 FieldDescriptor* extensions_;
1647 const FileOptions* options_;
1648
1649 const FileDescriptorTables* tables_;
1650 const SourceCodeInfo* source_code_info_;
1651
1652 // IMPORTANT: If you add a new field, make sure to search for all instances
1653 // of Allocate<FileDescriptor>() and AllocateArray<FileDescriptor>() in
1654 // descriptor.cc and update them to initialize the field.
1655
FileDescriptor()1656 FileDescriptor() {}
1657 friend class DescriptorBuilder;
1658 friend class DescriptorPool;
1659 friend class Descriptor;
1660 friend class FieldDescriptor;
1661 friend class internal::LazyDescriptor;
1662 friend class OneofDescriptor;
1663 friend class EnumDescriptor;
1664 friend class EnumValueDescriptor;
1665 friend class MethodDescriptor;
1666 friend class ServiceDescriptor;
1667 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileDescriptor);
1668 };
1669
1670
1671 // ===================================================================
1672
1673 // Used to construct descriptors.
1674 //
1675 // Normally you won't want to build your own descriptors. Message classes
1676 // constructed by the protocol compiler will provide them for you. However,
1677 // if you are implementing Message on your own, or if you are writing a
1678 // program which can operate on totally arbitrary types and needs to load
1679 // them from some sort of database, you might need to.
1680 //
1681 // Since Descriptors are composed of a whole lot of cross-linked bits of
1682 // data that would be a pain to put together manually, the
1683 // DescriptorPool class is provided to make the process easier. It can
1684 // take a FileDescriptorProto (defined in descriptor.proto), validate it,
1685 // and convert it to a set of nicely cross-linked Descriptors.
1686 //
1687 // DescriptorPool also helps with memory management. Descriptors are
1688 // composed of many objects containing static data and pointers to each
1689 // other. In all likelihood, when it comes time to delete this data,
1690 // you'll want to delete it all at once. In fact, it is not uncommon to
1691 // have a whole pool of descriptors all cross-linked with each other which
1692 // you wish to delete all at once. This class represents such a pool, and
1693 // handles the memory management for you.
1694 //
1695 // You can also search for descriptors within a DescriptorPool by name, and
1696 // extensions by number.
1697 class PROTOBUF_EXPORT DescriptorPool {
1698 public:
1699 // Create a normal, empty DescriptorPool.
1700 DescriptorPool();
1701
1702 // Constructs a DescriptorPool that, when it can't find something among the
1703 // descriptors already in the pool, looks for it in the given
1704 // DescriptorDatabase.
1705 // Notes:
1706 // - If a DescriptorPool is constructed this way, its BuildFile*() methods
1707 // must not be called (they will assert-fail). The only way to populate
1708 // the pool with descriptors is to call the Find*By*() methods.
1709 // - The Find*By*() methods may block the calling thread if the
1710 // DescriptorDatabase blocks. This in turn means that parsing messages
1711 // may block if they need to look up extensions.
1712 // - The Find*By*() methods will use mutexes for thread-safety, thus making
1713 // them slower even when they don't have to fall back to the database.
1714 // In fact, even the Find*By*() methods of descriptor objects owned by
1715 // this pool will be slower, since they will have to obtain locks too.
1716 // - An ErrorCollector may optionally be given to collect validation errors
1717 // in files loaded from the database. If not given, errors will be printed
1718 // to GOOGLE_LOG(ERROR). Remember that files are built on-demand, so this
1719 // ErrorCollector may be called from any thread that calls one of the
1720 // Find*By*() methods.
1721 // - The DescriptorDatabase must not be mutated during the lifetime of
1722 // the DescriptorPool. Even if the client takes care to avoid data races,
1723 // changes to the content of the DescriptorDatabase may not be reflected
1724 // in subsequent lookups in the DescriptorPool.
1725 class ErrorCollector;
1726 explicit DescriptorPool(DescriptorDatabase* fallback_database,
1727 ErrorCollector* error_collector = nullptr);
1728
1729 ~DescriptorPool();
1730
1731 // Get a pointer to the generated pool. Generated protocol message classes
1732 // which are compiled into the binary will allocate their descriptors in
1733 // this pool. Do not add your own descriptors to this pool.
1734 static const DescriptorPool* generated_pool();
1735
1736
1737 // Find a FileDescriptor in the pool by file name. Returns nullptr if not
1738 // found.
1739 const FileDescriptor* FindFileByName(ConstStringParam name) const;
1740
1741 // Find the FileDescriptor in the pool which defines the given symbol.
1742 // If any of the Find*ByName() methods below would succeed, then this is
1743 // equivalent to calling that method and calling the result's file() method.
1744 // Otherwise this returns nullptr.
1745 const FileDescriptor* FindFileContainingSymbol(
1746 ConstStringParam symbol_name) const;
1747
1748 // Looking up descriptors ------------------------------------------
1749 // These find descriptors by fully-qualified name. These will find both
1750 // top-level descriptors and nested descriptors. They return nullptr if not
1751 // found.
1752
1753 const Descriptor* FindMessageTypeByName(ConstStringParam name) const;
1754 const FieldDescriptor* FindFieldByName(ConstStringParam name) const;
1755 const FieldDescriptor* FindExtensionByName(ConstStringParam name) const;
1756 const OneofDescriptor* FindOneofByName(ConstStringParam name) const;
1757 const EnumDescriptor* FindEnumTypeByName(ConstStringParam name) const;
1758 const EnumValueDescriptor* FindEnumValueByName(ConstStringParam name) const;
1759 const ServiceDescriptor* FindServiceByName(ConstStringParam name) const;
1760 const MethodDescriptor* FindMethodByName(ConstStringParam name) const;
1761
1762 // Finds an extension of the given type by number. The extendee must be
1763 // a member of this DescriptorPool or one of its underlays.
1764 const FieldDescriptor* FindExtensionByNumber(const Descriptor* extendee,
1765 int number) const;
1766
1767 // Finds an extension of the given type by its printable name.
1768 // See comments above PrintableNameForExtension() for the definition of
1769 // "printable name". The extendee must be a member of this DescriptorPool
1770 // or one of its underlays. Returns nullptr if there is no known message
1771 // extension with the given printable name.
1772 const FieldDescriptor* FindExtensionByPrintableName(
1773 const Descriptor* extendee, ConstStringParam printable_name) const;
1774
1775 // Finds extensions of extendee. The extensions will be appended to
1776 // out in an undefined order. Only extensions defined directly in
1777 // this DescriptorPool or one of its underlays are guaranteed to be
1778 // found: extensions defined in the fallback database might not be found
1779 // depending on the database implementation.
1780 void FindAllExtensions(const Descriptor* extendee,
1781 std::vector<const FieldDescriptor*>* out) const;
1782
1783 // Building descriptors --------------------------------------------
1784
1785 // When converting a FileDescriptorProto to a FileDescriptor, various
1786 // errors might be detected in the input. The caller may handle these
1787 // programmatically by implementing an ErrorCollector.
1788 class PROTOBUF_EXPORT ErrorCollector {
1789 public:
ErrorCollector()1790 inline ErrorCollector() {}
1791 virtual ~ErrorCollector();
1792
1793 // These constants specify what exact part of the construct is broken.
1794 // This is useful e.g. for mapping the error back to an exact location
1795 // in a .proto file.
1796 enum ErrorLocation {
1797 NAME, // the symbol name, or the package name for files
1798 NUMBER, // field or extension range number
1799 TYPE, // field type
1800 EXTENDEE, // field extendee
1801 DEFAULT_VALUE, // field default value
1802 INPUT_TYPE, // method input type
1803 OUTPUT_TYPE, // method output type
1804 OPTION_NAME, // name in assignment
1805 OPTION_VALUE, // value in option assignment
1806 IMPORT, // import error
1807 OTHER // some other problem
1808 };
1809
1810 // Reports an error in the FileDescriptorProto. Use this function if the
1811 // problem occurred should interrupt building the FileDescriptorProto.
1812 virtual void AddError(
1813 const std::string& filename, // File name in which the error occurred.
1814 const std::string& element_name, // Full name of the erroneous element.
1815 const Message* descriptor, // Descriptor of the erroneous element.
1816 ErrorLocation location, // One of the location constants, above.
1817 const std::string& message // Human-readable error message.
1818 ) = 0;
1819
1820 // Reports a warning in the FileDescriptorProto. Use this function if the
1821 // problem occurred should NOT interrupt building the FileDescriptorProto.
AddWarning(const std::string &,const std::string &,const Message *,ErrorLocation,const std::string &)1822 virtual void AddWarning(
1823 const std::string& /*filename*/, // File name in which the error
1824 // occurred.
1825 const std::string& /*element_name*/, // Full name of the erroneous
1826 // element.
1827 const Message* /*descriptor*/, // Descriptor of the erroneous element.
1828 ErrorLocation /*location*/, // One of the location constants, above.
1829 const std::string& /*message*/ // Human-readable error message.
1830 ) {}
1831
1832 private:
1833 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ErrorCollector);
1834 };
1835
1836 // Convert the FileDescriptorProto to real descriptors and place them in
1837 // this DescriptorPool. All dependencies of the file must already be in
1838 // the pool. Returns the resulting FileDescriptor, or nullptr if there were
1839 // problems with the input (e.g. the message was invalid, or dependencies
1840 // were missing). Details about the errors are written to GOOGLE_LOG(ERROR).
1841 const FileDescriptor* BuildFile(const FileDescriptorProto& proto);
1842
1843 // Same as BuildFile() except errors are sent to the given ErrorCollector.
1844 const FileDescriptor* BuildFileCollectingErrors(
1845 const FileDescriptorProto& proto, ErrorCollector* error_collector);
1846
1847 // By default, it is an error if a FileDescriptorProto contains references
1848 // to types or other files that are not found in the DescriptorPool (or its
1849 // backing DescriptorDatabase, if any). If you call
1850 // AllowUnknownDependencies(), however, then unknown types and files
1851 // will be replaced by placeholder descriptors (which can be identified by
1852 // the is_placeholder() method). This can allow you to
1853 // perform some useful operations with a .proto file even if you do not
1854 // have access to other .proto files on which it depends. However, some
1855 // heuristics must be used to fill in the gaps in information, and these
1856 // can lead to descriptors which are inaccurate. For example, the
1857 // DescriptorPool may be forced to guess whether an unknown type is a message
1858 // or an enum, as well as what package it resides in. Furthermore,
1859 // placeholder types will not be discoverable via FindMessageTypeByName()
1860 // and similar methods, which could confuse some descriptor-based algorithms.
1861 // Generally, the results of this option should be handled with extreme care.
AllowUnknownDependencies()1862 void AllowUnknownDependencies() { allow_unknown_ = true; }
1863
1864 // By default, weak imports are allowed to be missing, in which case we will
1865 // use a placeholder for the dependency and convert the field to be an Empty
1866 // message field. If you call EnforceWeakDependencies(true), however, the
1867 // DescriptorPool will report a import not found error.
EnforceWeakDependencies(bool enforce)1868 void EnforceWeakDependencies(bool enforce) { enforce_weak_ = enforce; }
1869
1870 // Internal stuff --------------------------------------------------
1871 // These methods MUST NOT be called from outside the proto2 library.
1872 // These methods may contain hidden pitfalls and may be removed in a
1873 // future library version.
1874
1875 // Create a DescriptorPool which is overlaid on top of some other pool.
1876 // If you search for a descriptor in the overlay and it is not found, the
1877 // underlay will be searched as a backup. If the underlay has its own
1878 // underlay, that will be searched next, and so on. This also means that
1879 // files built in the overlay will be cross-linked with the underlay's
1880 // descriptors if necessary. The underlay remains property of the caller;
1881 // it must remain valid for the lifetime of the newly-constructed pool.
1882 //
1883 // Example: Say you want to parse a .proto file at runtime in order to use
1884 // its type with a DynamicMessage. Say this .proto file has dependencies,
1885 // but you know that all the dependencies will be things that are already
1886 // compiled into the binary. For ease of use, you'd like to load the types
1887 // right out of generated_pool() rather than have to parse redundant copies
1888 // of all these .protos and runtime. But, you don't want to add the parsed
1889 // types directly into generated_pool(): this is not allowed, and would be
1890 // bad design anyway. So, instead, you could use generated_pool() as an
1891 // underlay for a new DescriptorPool in which you add only the new file.
1892 //
1893 // WARNING: Use of underlays can lead to many subtle gotchas. Instead,
1894 // try to formulate what you want to do in terms of DescriptorDatabases.
1895 explicit DescriptorPool(const DescriptorPool* underlay);
1896
1897 // Called by generated classes at init time to add their descriptors to
1898 // generated_pool. Do NOT call this in your own code! filename must be a
1899 // permanent string (e.g. a string literal).
1900 static void InternalAddGeneratedFile(const void* encoded_file_descriptor,
1901 int size);
1902
1903 // Disallow [enforce_utf8 = false] in .proto files.
DisallowEnforceUtf8()1904 void DisallowEnforceUtf8() { disallow_enforce_utf8_ = true; }
1905
1906
1907 // For internal use only: Gets a non-const pointer to the generated pool.
1908 // This is called at static-initialization time only, so thread-safety is
1909 // not a concern. If both an underlay and a fallback database are present,
1910 // the underlay takes precedence.
1911 static DescriptorPool* internal_generated_pool();
1912
1913 // For internal use only: Gets a non-const pointer to the generated
1914 // descriptor database.
1915 // Only used for testing.
1916 static DescriptorDatabase* internal_generated_database();
1917
1918 // For internal use only: Changes the behavior of BuildFile() such that it
1919 // allows the file to make reference to message types declared in other files
1920 // which it did not officially declare as dependencies.
1921 void InternalDontEnforceDependencies();
1922
1923 // For internal use only: Enables lazy building of dependencies of a file.
1924 // Delay the building of dependencies of a file descriptor until absolutely
1925 // necessary, like when message_type() is called on a field that is defined
1926 // in that dependency's file. This will cause functional issues if a proto
1927 // or one of its dependencies has errors. Should only be enabled for the
1928 // generated_pool_ (because no descriptor build errors are guaranteed by
1929 // the compilation generation process), testing, or if a lack of descriptor
1930 // build errors can be guaranteed for a pool.
InternalSetLazilyBuildDependencies()1931 void InternalSetLazilyBuildDependencies() {
1932 lazily_build_dependencies_ = true;
1933 // This needs to be set when lazily building dependencies, as it breaks
1934 // dependency checking.
1935 InternalDontEnforceDependencies();
1936 }
1937
1938 // For internal use only.
internal_set_underlay(const DescriptorPool * underlay)1939 void internal_set_underlay(const DescriptorPool* underlay) {
1940 underlay_ = underlay;
1941 }
1942
1943 // For internal (unit test) use only: Returns true if a FileDescriptor has
1944 // been constructed for the given file, false otherwise. Useful for testing
1945 // lazy descriptor initialization behavior.
1946 bool InternalIsFileLoaded(ConstStringParam filename) const;
1947
1948 // Add a file to unused_import_track_files_. DescriptorBuilder will log
1949 // warnings or errors for those files if there is any unused import.
1950 void AddUnusedImportTrackFile(ConstStringParam file_name,
1951 bool is_error = false);
1952 void ClearUnusedImportTrackFiles();
1953
1954 private:
1955 friend class Descriptor;
1956 friend class internal::LazyDescriptor;
1957 friend class FieldDescriptor;
1958 friend class EnumDescriptor;
1959 friend class ServiceDescriptor;
1960 friend class MethodDescriptor;
1961 friend class FileDescriptor;
1962 friend class StreamDescriptor;
1963 friend class DescriptorBuilder;
1964 friend class FileDescriptorTables;
1965
1966 // Return true if the given name is a sub-symbol of any non-package
1967 // descriptor that already exists in the descriptor pool. (The full
1968 // definition of such types is already known.)
1969 bool IsSubSymbolOfBuiltType(StringPiece name) const;
1970
1971 // Tries to find something in the fallback database and link in the
1972 // corresponding proto file. Returns true if successful, in which case
1973 // the caller should search for the thing again. These are declared
1974 // const because they are called by (semantically) const methods.
1975 bool TryFindFileInFallbackDatabase(StringPiece name) const;
1976 bool TryFindSymbolInFallbackDatabase(StringPiece name) const;
1977 bool TryFindExtensionInFallbackDatabase(const Descriptor* containing_type,
1978 int field_number) const;
1979
1980 // This internal find extension method only check with its table and underlay
1981 // descriptor_pool's table. It does not check with fallback DB and no
1982 // additional proto file will be build in this method.
1983 const FieldDescriptor* InternalFindExtensionByNumberNoLock(
1984 const Descriptor* extendee, int number) const;
1985
1986 // Like BuildFile() but called internally when the file has been loaded from
1987 // fallback_database_. Declared const because it is called by (semantically)
1988 // const methods.
1989 const FileDescriptor* BuildFileFromDatabase(
1990 const FileDescriptorProto& proto) const;
1991
1992 // Helper for when lazily_build_dependencies_ is set, can look up a symbol
1993 // after the file's descriptor is built, and can build the file where that
1994 // symbol is defined if necessary. Will create a placeholder if the type
1995 // doesn't exist in the fallback database, or the file doesn't build
1996 // successfully.
1997 Symbol CrossLinkOnDemandHelper(StringPiece name,
1998 bool expecting_enum) const;
1999
2000 // Create a placeholder FileDescriptor of the specified name
2001 FileDescriptor* NewPlaceholderFile(StringPiece name) const;
2002 FileDescriptor* NewPlaceholderFileWithMutexHeld(StringPiece name) const;
2003
2004 enum PlaceholderType {
2005 PLACEHOLDER_MESSAGE,
2006 PLACEHOLDER_ENUM,
2007 PLACEHOLDER_EXTENDABLE_MESSAGE
2008 };
2009 // Create a placeholder Descriptor of the specified name
2010 Symbol NewPlaceholder(StringPiece name,
2011 PlaceholderType placeholder_type) const;
2012 Symbol NewPlaceholderWithMutexHeld(StringPiece name,
2013 PlaceholderType placeholder_type) const;
2014
2015 // If fallback_database_ is nullptr, this is nullptr. Otherwise, this is a
2016 // mutex which must be locked while accessing tables_.
2017 internal::WrappedMutex* mutex_;
2018
2019 // See constructor.
2020 DescriptorDatabase* fallback_database_;
2021 ErrorCollector* default_error_collector_;
2022 const DescriptorPool* underlay_;
2023
2024 // This class contains a lot of hash maps with complicated types that
2025 // we'd like to keep out of the header.
2026 class Tables;
2027 std::unique_ptr<Tables> tables_;
2028
2029 bool enforce_dependencies_;
2030 bool lazily_build_dependencies_;
2031 bool allow_unknown_;
2032 bool enforce_weak_;
2033 bool disallow_enforce_utf8_;
2034
2035 // Set of files to track for unused imports. The bool value when true means
2036 // unused imports are treated as errors (and as warnings when false).
2037 std::map<std::string, bool> unused_import_track_files_;
2038
2039 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorPool);
2040 };
2041
2042
2043 // inline methods ====================================================
2044
2045 // These macros makes this repetitive code more readable.
2046 #define PROTOBUF_DEFINE_ACCESSOR(CLASS, FIELD, TYPE) \
2047 inline TYPE CLASS::FIELD() const { return FIELD##_; }
2048
2049 // Strings fields are stored as pointers but returned as const references.
2050 #define PROTOBUF_DEFINE_STRING_ACCESSOR(CLASS, FIELD) \
2051 inline const std::string& CLASS::FIELD() const { return *FIELD##_; }
2052
2053 // Name and full name are stored in a single array to save space.
2054 #define PROTOBUF_DEFINE_NAME_ACCESSOR(CLASS) \
2055 inline const std::string& CLASS::name() const { return all_names_[0]; } \
2056 inline const std::string& CLASS::full_name() const { return all_names_[1]; }
2057
2058 // Arrays take an index parameter, obviously.
2059 #define PROTOBUF_DEFINE_ARRAY_ACCESSOR(CLASS, FIELD, TYPE) \
2060 inline TYPE CLASS::FIELD(int index) const { return FIELD##s_ + index; }
2061
2062 #define PROTOBUF_DEFINE_OPTIONS_ACCESSOR(CLASS, TYPE) \
2063 inline const TYPE& CLASS::options() const { return *options_; }
2064
2065 PROTOBUF_DEFINE_NAME_ACCESSOR(Descriptor)
PROTOBUF_DEFINE_ACCESSOR(Descriptor,file,const FileDescriptor *)2066 PROTOBUF_DEFINE_ACCESSOR(Descriptor, file, const FileDescriptor*)
2067 PROTOBUF_DEFINE_ACCESSOR(Descriptor, containing_type, const Descriptor*)
2068
2069 PROTOBUF_DEFINE_ACCESSOR(Descriptor, field_count, int)
2070 PROTOBUF_DEFINE_ACCESSOR(Descriptor, oneof_decl_count, int)
2071 PROTOBUF_DEFINE_ACCESSOR(Descriptor, real_oneof_decl_count, int)
2072 PROTOBUF_DEFINE_ACCESSOR(Descriptor, nested_type_count, int)
2073 PROTOBUF_DEFINE_ACCESSOR(Descriptor, enum_type_count, int)
2074
2075 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, field, const FieldDescriptor*)
2076 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, oneof_decl, const OneofDescriptor*)
2077 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, nested_type, const Descriptor*)
2078 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, enum_type, const EnumDescriptor*)
2079
2080 PROTOBUF_DEFINE_ACCESSOR(Descriptor, extension_range_count, int)
2081 PROTOBUF_DEFINE_ACCESSOR(Descriptor, extension_count, int)
2082 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension_range,
2083 const Descriptor::ExtensionRange*)
2084 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension, const FieldDescriptor*)
2085
2086 PROTOBUF_DEFINE_ACCESSOR(Descriptor, reserved_range_count, int)
2087 PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, reserved_range,
2088 const Descriptor::ReservedRange*)
2089 PROTOBUF_DEFINE_ACCESSOR(Descriptor, reserved_name_count, int)
2090
2091 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(Descriptor, MessageOptions)
2092 PROTOBUF_DEFINE_ACCESSOR(Descriptor, is_placeholder, bool)
2093
2094 PROTOBUF_DEFINE_NAME_ACCESSOR(FieldDescriptor)
2095 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, file, const FileDescriptor*)
2096 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, number, int)
2097 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, is_extension, bool)
2098 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, containing_type, const Descriptor*)
2099 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, index_in_oneof, int)
2100 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(FieldDescriptor, FieldOptions)
2101 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_default_value, bool)
2102 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_json_name, bool)
2103 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int32_t, int32_t)
2104 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int64_t, int64_t)
2105 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint32_t, uint32_t)
2106 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint64_t, uint64_t)
2107 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_float, float)
2108 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_double, double)
2109 PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_bool, bool)
2110 PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, default_value_string)
2111
2112 PROTOBUF_DEFINE_NAME_ACCESSOR(OneofDescriptor)
2113 PROTOBUF_DEFINE_ACCESSOR(OneofDescriptor, containing_type, const Descriptor*)
2114 PROTOBUF_DEFINE_ACCESSOR(OneofDescriptor, field_count, int)
2115 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(OneofDescriptor, OneofOptions)
2116
2117 PROTOBUF_DEFINE_NAME_ACCESSOR(EnumDescriptor)
2118 PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, file, const FileDescriptor*)
2119 PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, containing_type, const Descriptor*)
2120 PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, value_count, int)
2121 PROTOBUF_DEFINE_ARRAY_ACCESSOR(EnumDescriptor, value,
2122 const EnumValueDescriptor*)
2123 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(EnumDescriptor, EnumOptions)
2124 PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, is_placeholder, bool)
2125 PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, reserved_range_count, int)
2126 PROTOBUF_DEFINE_ARRAY_ACCESSOR(EnumDescriptor, reserved_range,
2127 const EnumDescriptor::ReservedRange*)
2128 PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, reserved_name_count, int)
2129
2130 PROTOBUF_DEFINE_NAME_ACCESSOR(EnumValueDescriptor)
2131 PROTOBUF_DEFINE_ACCESSOR(EnumValueDescriptor, number, int)
2132 PROTOBUF_DEFINE_ACCESSOR(EnumValueDescriptor, type, const EnumDescriptor*)
2133 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(EnumValueDescriptor, EnumValueOptions)
2134
2135 PROTOBUF_DEFINE_NAME_ACCESSOR(ServiceDescriptor)
2136 PROTOBUF_DEFINE_ACCESSOR(ServiceDescriptor, file, const FileDescriptor*)
2137 PROTOBUF_DEFINE_ACCESSOR(ServiceDescriptor, method_count, int)
2138 PROTOBUF_DEFINE_ARRAY_ACCESSOR(ServiceDescriptor, method,
2139 const MethodDescriptor*)
2140 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(ServiceDescriptor, ServiceOptions)
2141
2142 PROTOBUF_DEFINE_NAME_ACCESSOR(MethodDescriptor)
2143 PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, service, const ServiceDescriptor*)
2144 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(MethodDescriptor, MethodOptions)
2145 PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, client_streaming, bool)
2146 PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, server_streaming, bool)
2147
2148 PROTOBUF_DEFINE_STRING_ACCESSOR(FileDescriptor, name)
2149 PROTOBUF_DEFINE_STRING_ACCESSOR(FileDescriptor, package)
2150 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, pool, const DescriptorPool*)
2151 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, dependency_count, int)
2152 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, public_dependency_count, int)
2153 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, weak_dependency_count, int)
2154 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, message_type_count, int)
2155 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, enum_type_count, int)
2156 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, service_count, int)
2157 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, extension_count, int)
2158 PROTOBUF_DEFINE_OPTIONS_ACCESSOR(FileDescriptor, FileOptions)
2159 PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, is_placeholder, bool)
2160
2161 PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, message_type, const Descriptor*)
2162 PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, enum_type, const EnumDescriptor*)
2163 PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, service,
2164 const ServiceDescriptor*)
2165 PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, extension,
2166 const FieldDescriptor*)
2167
2168 #undef PROTOBUF_DEFINE_ACCESSOR
2169 #undef PROTOBUF_DEFINE_STRING_ACCESSOR
2170 #undef PROTOBUF_DEFINE_ARRAY_ACCESSOR
2171
2172 // A few accessors differ from the macros...
2173
2174 inline Descriptor::WellKnownType Descriptor::well_known_type() const {
2175 return static_cast<Descriptor::WellKnownType>(well_known_type_);
2176 }
2177
IsExtensionNumber(int number)2178 inline bool Descriptor::IsExtensionNumber(int number) const {
2179 return FindExtensionRangeContainingNumber(number) != nullptr;
2180 }
2181
IsReservedNumber(int number)2182 inline bool Descriptor::IsReservedNumber(int number) const {
2183 return FindReservedRangeContainingNumber(number) != nullptr;
2184 }
2185
IsReservedName(ConstStringParam name)2186 inline bool Descriptor::IsReservedName(ConstStringParam name) const {
2187 for (int i = 0; i < reserved_name_count(); i++) {
2188 if (name == static_cast<ConstStringParam>(reserved_name(i))) {
2189 return true;
2190 }
2191 }
2192 return false;
2193 }
2194
2195 // Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually
2196 // an array of pointers rather than the usual array of objects.
reserved_name(int index)2197 inline const std::string& Descriptor::reserved_name(int index) const {
2198 return *reserved_names_[index];
2199 }
2200
IsReservedNumber(int number)2201 inline bool EnumDescriptor::IsReservedNumber(int number) const {
2202 return FindReservedRangeContainingNumber(number) != nullptr;
2203 }
2204
IsReservedName(ConstStringParam name)2205 inline bool EnumDescriptor::IsReservedName(ConstStringParam name) const {
2206 for (int i = 0; i < reserved_name_count(); i++) {
2207 if (name == static_cast<ConstStringParam>(reserved_name(i))) {
2208 return true;
2209 }
2210 }
2211 return false;
2212 }
2213
2214 // Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually
2215 // an array of pointers rather than the usual array of objects.
reserved_name(int index)2216 inline const std::string& EnumDescriptor::reserved_name(int index) const {
2217 return *reserved_names_[index];
2218 }
2219
lowercase_name()2220 inline const std::string& FieldDescriptor::lowercase_name() const {
2221 return all_names_[lowercase_name_index_];
2222 }
2223
camelcase_name()2224 inline const std::string& FieldDescriptor::camelcase_name() const {
2225 return all_names_[camelcase_name_index_];
2226 }
2227
json_name()2228 inline const std::string& FieldDescriptor::json_name() const {
2229 return all_names_[json_name_index_];
2230 }
2231
containing_oneof()2232 inline const OneofDescriptor* FieldDescriptor::containing_oneof() const {
2233 return is_oneof_ ? scope_.containing_oneof : nullptr;
2234 }
2235
extension_scope()2236 inline const Descriptor* FieldDescriptor::extension_scope() const {
2237 GOOGLE_CHECK(is_extension_);
2238 return scope_.extension_scope;
2239 }
2240
label()2241 inline FieldDescriptor::Label FieldDescriptor::label() const {
2242 return static_cast<Label>(label_);
2243 }
2244
type()2245 inline FieldDescriptor::Type FieldDescriptor::type() const {
2246 if (type_once_) {
2247 internal::call_once(type_once_->once, &FieldDescriptor::TypeOnceInit, this);
2248 }
2249 return static_cast<Type>(type_);
2250 }
2251
is_required()2252 inline bool FieldDescriptor::is_required() const {
2253 return label() == LABEL_REQUIRED;
2254 }
2255
is_optional()2256 inline bool FieldDescriptor::is_optional() const {
2257 return label() == LABEL_OPTIONAL;
2258 }
2259
is_repeated()2260 inline bool FieldDescriptor::is_repeated() const {
2261 return label() == LABEL_REPEATED;
2262 }
2263
is_packable()2264 inline bool FieldDescriptor::is_packable() const {
2265 return is_repeated() && IsTypePackable(type());
2266 }
2267
is_map()2268 inline bool FieldDescriptor::is_map() const {
2269 return type() == TYPE_MESSAGE && is_map_message_type();
2270 }
2271
has_optional_keyword()2272 inline bool FieldDescriptor::has_optional_keyword() const {
2273 return proto3_optional_ ||
2274 (file()->syntax() == FileDescriptor::SYNTAX_PROTO2 && is_optional() &&
2275 !containing_oneof());
2276 }
2277
real_containing_oneof()2278 inline const OneofDescriptor* FieldDescriptor::real_containing_oneof() const {
2279 auto* oneof = containing_oneof();
2280 return oneof && !oneof->is_synthetic() ? oneof : nullptr;
2281 }
2282
has_presence()2283 inline bool FieldDescriptor::has_presence() const {
2284 if (is_repeated()) return false;
2285 return cpp_type() == CPPTYPE_MESSAGE || containing_oneof() ||
2286 file()->syntax() == FileDescriptor::SYNTAX_PROTO2;
2287 }
2288
2289 // To save space, index() is computed by looking at the descriptor's position
2290 // in the parent's array of children.
index()2291 inline int FieldDescriptor::index() const {
2292 if (!is_extension_) {
2293 return static_cast<int>(this - containing_type()->fields_);
2294 } else if (extension_scope() != nullptr) {
2295 return static_cast<int>(this - extension_scope()->extensions_);
2296 } else {
2297 return static_cast<int>(this - file_->extensions_);
2298 }
2299 }
2300
index()2301 inline int Descriptor::index() const {
2302 if (containing_type_ == nullptr) {
2303 return static_cast<int>(this - file_->message_types_);
2304 } else {
2305 return static_cast<int>(this - containing_type_->nested_types_);
2306 }
2307 }
2308
file()2309 inline const FileDescriptor* OneofDescriptor::file() const {
2310 return containing_type()->file();
2311 }
2312
index()2313 inline int OneofDescriptor::index() const {
2314 return static_cast<int>(this - containing_type_->oneof_decls_);
2315 }
2316
is_synthetic()2317 inline bool OneofDescriptor::is_synthetic() const {
2318 return field_count() == 1 && field(0)->proto3_optional_;
2319 }
2320
index()2321 inline int EnumDescriptor::index() const {
2322 if (containing_type_ == nullptr) {
2323 return static_cast<int>(this - file_->enum_types_);
2324 } else {
2325 return static_cast<int>(this - containing_type_->enum_types_);
2326 }
2327 }
2328
file()2329 inline const FileDescriptor* EnumValueDescriptor::file() const {
2330 return type()->file();
2331 }
2332
index()2333 inline int EnumValueDescriptor::index() const {
2334 return static_cast<int>(this - type_->values_);
2335 }
2336
index()2337 inline int ServiceDescriptor::index() const {
2338 return static_cast<int>(this - file_->services_);
2339 }
2340
file()2341 inline const FileDescriptor* MethodDescriptor::file() const {
2342 return service()->file();
2343 }
2344
index()2345 inline int MethodDescriptor::index() const {
2346 return static_cast<int>(this - service_->methods_);
2347 }
2348
type_name()2349 inline const char* FieldDescriptor::type_name() const {
2350 return kTypeToName[type()];
2351 }
2352
cpp_type()2353 inline FieldDescriptor::CppType FieldDescriptor::cpp_type() const {
2354 return kTypeToCppTypeMap[type()];
2355 }
2356
cpp_type_name()2357 inline const char* FieldDescriptor::cpp_type_name() const {
2358 return kCppTypeToName[kTypeToCppTypeMap[type()]];
2359 }
2360
TypeToCppType(Type type)2361 inline FieldDescriptor::CppType FieldDescriptor::TypeToCppType(Type type) {
2362 return kTypeToCppTypeMap[type];
2363 }
2364
TypeName(Type type)2365 inline const char* FieldDescriptor::TypeName(Type type) {
2366 return kTypeToName[type];
2367 }
2368
CppTypeName(CppType cpp_type)2369 inline const char* FieldDescriptor::CppTypeName(CppType cpp_type) {
2370 return kCppTypeToName[cpp_type];
2371 }
2372
IsTypePackable(Type field_type)2373 inline bool FieldDescriptor::IsTypePackable(Type field_type) {
2374 return (field_type != FieldDescriptor::TYPE_STRING &&
2375 field_type != FieldDescriptor::TYPE_GROUP &&
2376 field_type != FieldDescriptor::TYPE_MESSAGE &&
2377 field_type != FieldDescriptor::TYPE_BYTES);
2378 }
2379
public_dependency(int index)2380 inline const FileDescriptor* FileDescriptor::public_dependency(
2381 int index) const {
2382 return dependency(public_dependencies_[index]);
2383 }
2384
weak_dependency(int index)2385 inline const FileDescriptor* FileDescriptor::weak_dependency(int index) const {
2386 return dependency(weak_dependencies_[index]);
2387 }
2388
syntax()2389 inline FileDescriptor::Syntax FileDescriptor::syntax() const {
2390 return static_cast<Syntax>(syntax_);
2391 }
2392
2393 // Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because fields_ is actually an array
2394 // of pointers rather than the usual array of objects.
field(int index)2395 inline const FieldDescriptor* OneofDescriptor::field(int index) const {
2396 return fields_[index];
2397 }
2398
2399 } // namespace protobuf
2400 } // namespace google
2401
2402 #include <google/protobuf/port_undef.inc>
2403
2404 #endif // GOOGLE_PROTOBUF_DESCRIPTOR_H__
2405