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