/thirdparty/breakpad/third_party/protobuf/protobuf/src/google/protobuf/descriptor.cc
C++ | 1943 lines | 1412 code | 279 blank | 252 comment | 292 complexity | 169581e021afaf1ffcb5e8223a3b3ca5 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, GPL-3.0, GPL-2.0
- // Protocol Buffers - Google's data interchange format
- // Copyright 2008 Google Inc. All rights reserved.
- // http://code.google.com/p/protobuf/
- //
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are
- // met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above
- // copyright notice, this list of conditions and the following disclaimer
- // in the documentation and/or other materials provided with the
- // distribution.
- // * Neither the name of Google Inc. nor the names of its
- // contributors may be used to endorse or promote products derived from
- // this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- // Author: kenton@google.com (Kenton Varda)
- // Based on original Protocol Buffers design by
- // Sanjay Ghemawat, Jeff Dean, and others.
- #include <google/protobuf/stubs/hash.h>
- #include <map>
- #include <set>
- #include <vector>
- #include <algorithm>
- #include <limits>
- #include <google/protobuf/descriptor.h>
- #include <google/protobuf/descriptor_database.h>
- #include <google/protobuf/descriptor.pb.h>
- #include <google/protobuf/dynamic_message.h>
- #include <google/protobuf/text_format.h>
- #include <google/protobuf/unknown_field_set.h>
- #include <google/protobuf/wire_format.h>
- #include <google/protobuf/io/coded_stream.h>
- #include <google/protobuf/io/tokenizer.h>
- #include <google/protobuf/io/zero_copy_stream_impl.h>
- #include <google/protobuf/stubs/common.h>
- #include <google/protobuf/stubs/once.h>
- #include <google/protobuf/stubs/strutil.h>
- #include <google/protobuf/stubs/substitute.h>
- #include <google/protobuf/stubs/map-util.h>
- #include <google/protobuf/stubs/stl_util-inl.h>
- #undef PACKAGE // autoheader #defines this. :(
- namespace google {
- namespace protobuf {
- const FieldDescriptor::CppType
- FieldDescriptor::kTypeToCppTypeMap[MAX_TYPE + 1] = {
- static_cast<CppType>(0), // 0 is reserved for errors
- CPPTYPE_DOUBLE, // TYPE_DOUBLE
- CPPTYPE_FLOAT, // TYPE_FLOAT
- CPPTYPE_INT64, // TYPE_INT64
- CPPTYPE_UINT64, // TYPE_UINT64
- CPPTYPE_INT32, // TYPE_INT32
- CPPTYPE_UINT64, // TYPE_FIXED64
- CPPTYPE_UINT32, // TYPE_FIXED32
- CPPTYPE_BOOL, // TYPE_BOOL
- CPPTYPE_STRING, // TYPE_STRING
- CPPTYPE_MESSAGE, // TYPE_GROUP
- CPPTYPE_MESSAGE, // TYPE_MESSAGE
- CPPTYPE_STRING, // TYPE_BYTES
- CPPTYPE_UINT32, // TYPE_UINT32
- CPPTYPE_ENUM, // TYPE_ENUM
- CPPTYPE_INT32, // TYPE_SFIXED32
- CPPTYPE_INT64, // TYPE_SFIXED64
- CPPTYPE_INT32, // TYPE_SINT32
- CPPTYPE_INT64, // TYPE_SINT64
- };
- const char * const FieldDescriptor::kTypeToName[MAX_TYPE + 1] = {
- "ERROR", // 0 is reserved for errors
- "double", // TYPE_DOUBLE
- "float", // TYPE_FLOAT
- "int64", // TYPE_INT64
- "uint64", // TYPE_UINT64
- "int32", // TYPE_INT32
- "fixed64", // TYPE_FIXED64
- "fixed32", // TYPE_FIXED32
- "bool", // TYPE_BOOL
- "string", // TYPE_STRING
- "group", // TYPE_GROUP
- "message", // TYPE_MESSAGE
- "bytes", // TYPE_BYTES
- "uint32", // TYPE_UINT32
- "enum", // TYPE_ENUM
- "sfixed32", // TYPE_SFIXED32
- "sfixed64", // TYPE_SFIXED64
- "sint32", // TYPE_SINT32
- "sint64", // TYPE_SINT64
- };
- const char * const FieldDescriptor::kLabelToName[MAX_LABEL + 1] = {
- "ERROR", // 0 is reserved for errors
- "optional", // LABEL_OPTIONAL
- "required", // LABEL_REQUIRED
- "repeated", // LABEL_REPEATED
- };
- #ifndef _MSC_VER // MSVC doesn't need these and won't even accept them.
- const int FieldDescriptor::kMaxNumber;
- const int FieldDescriptor::kFirstReservedNumber;
- const int FieldDescriptor::kLastReservedNumber;
- #endif
- namespace {
- const string kEmptyString;
- string ToCamelCase(const string& input) {
- bool capitalize_next = false;
- string result;
- result.reserve(input.size());
- for (int i = 0; i < input.size(); i++) {
- if (input[i] == '_') {
- capitalize_next = true;
- } else if (capitalize_next) {
- // Note: I distrust ctype.h due to locales.
- if ('a' <= input[i] && input[i] <= 'z') {
- result.push_back(input[i] - 'a' + 'A');
- } else {
- result.push_back(input[i]);
- }
- capitalize_next = false;
- } else {
- result.push_back(input[i]);
- }
- }
- // Lower-case the first letter.
- if (!result.empty() && 'A' <= result[0] && result[0] <= 'Z') {
- result[0] = result[0] - 'A' + 'a';
- }
- return result;
- }
- // A DescriptorPool contains a bunch of hash_maps to implement the
- // various Find*By*() methods. Since hashtable lookups are O(1), it's
- // most efficient to construct a fixed set of large hash_maps used by
- // all objects in the pool rather than construct one or more small
- // hash_maps for each object.
- //
- // The keys to these hash_maps are (parent, name) or (parent, number)
- // pairs. Unfortunately STL doesn't provide hash functions for pair<>,
- // so we must invent our own.
- //
- // TODO(kenton): Use StringPiece rather than const char* in keys? It would
- // be a lot cleaner but we'd just have to convert it back to const char*
- // for the open source release.
- typedef pair<const void*, const char*> PointerStringPair;
- struct PointerStringPairEqual {
- inline bool operator()(const PointerStringPair& a,
- const PointerStringPair& b) const {
- return a.first == b.first && strcmp(a.second, b.second) == 0;
- }
- };
- template<typename PairType>
- struct PointerIntegerPairHash {
- size_t operator()(const PairType& p) const {
- // FIXME(kenton): What is the best way to compute this hash? I have
- // no idea! This seems a bit better than an XOR.
- return reinterpret_cast<intptr_t>(p.first) * ((1 << 16) - 1) + p.second;
- }
- // Used only by MSVC and platforms where hash_map is not available.
- static const size_t bucket_size = 4;
- static const size_t min_buckets = 8;
- inline bool operator()(const PairType& a, const PairType& b) const {
- return a.first < b.first ||
- (a.first == b.first && a.second < b.second);
- }
- };
- typedef pair<const Descriptor*, int> DescriptorIntPair;
- typedef pair<const EnumDescriptor*, int> EnumIntPair;
- struct PointerStringPairHash {
- size_t operator()(const PointerStringPair& p) const {
- // FIXME(kenton): What is the best way to compute this hash? I have
- // no idea! This seems a bit better than an XOR.
- hash<const char*> cstring_hash;
- return reinterpret_cast<intptr_t>(p.first) * ((1 << 16) - 1) +
- cstring_hash(p.second);
- }
- // Used only by MSVC and platforms where hash_map is not available.
- static const size_t bucket_size = 4;
- static const size_t min_buckets = 8;
- inline bool operator()(const PointerStringPair& a,
- const PointerStringPair& b) const {
- if (a.first < b.first) return true;
- if (a.first > b.first) return false;
- return strcmp(a.second, b.second) < 0;
- }
- };
- struct Symbol {
- enum Type {
- NULL_SYMBOL, MESSAGE, FIELD, ENUM, ENUM_VALUE, SERVICE, METHOD, PACKAGE
- };
- Type type;
- union {
- const Descriptor* descriptor;
- const FieldDescriptor* field_descriptor;
- const EnumDescriptor* enum_descriptor;
- const EnumValueDescriptor* enum_value_descriptor;
- const ServiceDescriptor* service_descriptor;
- const MethodDescriptor* method_descriptor;
- const FileDescriptor* package_file_descriptor;
- };
- inline Symbol() : type(NULL_SYMBOL) { descriptor = NULL; }
- inline bool IsNull() const { return type == NULL_SYMBOL; }
- inline bool IsType() const {
- return type == MESSAGE || type == ENUM;
- }
- inline bool IsAggregate() const {
- return type == MESSAGE || type == PACKAGE
- || type == ENUM || type == SERVICE;
- }
- #define CONSTRUCTOR(TYPE, TYPE_CONSTANT, FIELD) \
- inline explicit Symbol(const TYPE* value) { \
- type = TYPE_CONSTANT; \
- this->FIELD = value; \
- }
- CONSTRUCTOR(Descriptor , MESSAGE , descriptor )
- CONSTRUCTOR(FieldDescriptor , FIELD , field_descriptor )
- CONSTRUCTOR(EnumDescriptor , ENUM , enum_descriptor )
- CONSTRUCTOR(EnumValueDescriptor, ENUM_VALUE, enum_value_descriptor )
- CONSTRUCTOR(ServiceDescriptor , SERVICE , service_descriptor )
- CONSTRUCTOR(MethodDescriptor , METHOD , method_descriptor )
- CONSTRUCTOR(FileDescriptor , PACKAGE , package_file_descriptor)
- #undef CONSTRUCTOR
- const FileDescriptor* GetFile() const {
- switch (type) {
- case NULL_SYMBOL: return NULL;
- case MESSAGE : return descriptor ->file();
- case FIELD : return field_descriptor ->file();
- case ENUM : return enum_descriptor ->file();
- case ENUM_VALUE : return enum_value_descriptor->type()->file();
- case SERVICE : return service_descriptor ->file();
- case METHOD : return method_descriptor ->service()->file();
- case PACKAGE : return package_file_descriptor;
- }
- return NULL;
- }
- };
- const Symbol kNullSymbol;
- typedef hash_map<const char*, Symbol,
- hash<const char*>, streq>
- SymbolsByNameMap;
- typedef hash_map<PointerStringPair, Symbol,
- PointerStringPairHash, PointerStringPairEqual>
- SymbolsByParentMap;
- typedef hash_map<const char*, const FileDescriptor*,
- hash<const char*>, streq>
- FilesByNameMap;
- typedef hash_map<PointerStringPair, const FieldDescriptor*,
- PointerStringPairHash, PointerStringPairEqual>
- FieldsByNameMap;
- typedef hash_map<DescriptorIntPair, const FieldDescriptor*,
- PointerIntegerPairHash<DescriptorIntPair> >
- FieldsByNumberMap;
- typedef hash_map<EnumIntPair, const EnumValueDescriptor*,
- PointerIntegerPairHash<EnumIntPair> >
- EnumValuesByNumberMap;
- // This is a map rather than a hash_map, since we use it to iterate
- // through all the extensions that extend a given Descriptor, and an
- // ordered data structure that implements lower_bound is convenient
- // for that.
- typedef map<DescriptorIntPair, const FieldDescriptor*>
- ExtensionsGroupedByDescriptorMap;
- } // anonymous namespace
- // ===================================================================
- // DescriptorPool::Tables
- class DescriptorPool::Tables {
- public:
- Tables();
- ~Tables();
- // Checkpoint the state of the tables. Future calls to Rollback() will
- // return the Tables to this state. This is used when building files, since
- // some kinds of validation errors cannot be detected until the file's
- // descriptors have already been added to the tables. BuildFile() calls
- // Checkpoint() before it starts building and Rollback() if it encounters
- // an error.
- void Checkpoint();
- // Roll back the Tables to the state of the last Checkpoint(), removing
- // everything that was added after that point.
- void Rollback();
- // The stack of files which are currently being built. Used to detect
- // cyclic dependencies when loading files from a DescriptorDatabase. Not
- // used when fallback_database_ == NULL.
- vector<string> pending_files_;
- // A set of files which we have tried to load from the fallback database
- // and encountered errors. We will not attempt to load them again.
- // Not used when fallback_database_ == NULL.
- hash_set<string> known_bad_files_;
- // The set of descriptors for which we've already loaded the full
- // set of extensions numbers from fallback_database_.
- hash_set<const Descriptor*> extensions_loaded_from_db_;
- // -----------------------------------------------------------------
- // Finding items.
- // Find symbols. This returns a null Symbol (symbol.IsNull() is true)
- // if not found.
- inline Symbol FindSymbol(const string& key) const;
- // This implements the body of DescriptorPool::Find*ByName(). It should
- // really be a private method of DescriptorPool, but that would require
- // declaring Symbol in descriptor.h, which would drag all kinds of other
- // stuff into the header. Yay C++.
- Symbol FindByNameHelper(
- const DescriptorPool* pool, const string& name) const;
- // These return NULL if not found.
- inline const FileDescriptor* FindFile(const string& key) const;
- inline const FieldDescriptor* FindExtension(const Descriptor* extendee,
- int number);
- inline void FindAllExtensions(const Descriptor* extendee,
- vector<const FieldDescriptor*>* out) const;
- // -----------------------------------------------------------------
- // Adding items.
- // These add items to the corresponding tables. They return false if
- // the key already exists in the table. For AddSymbol(), the string passed
- // in must be one that was constructed using AllocateString(), as it will
- // be used as a key in the symbols_by_name_ map without copying.
- bool AddSymbol(const string& full_name, Symbol symbol);
- bool AddFile(const FileDescriptor* file);
- bool AddExtension(const FieldDescriptor* field);
- // -----------------------------------------------------------------
- // Allocating memory.
- // Allocate an object which will be reclaimed when the pool is
- // destroyed. Note that the object's destructor will never be called,
- // so its fields must be plain old data (primitive data types and
- // pointers). All of the descriptor types are such objects.
- template<typename Type> Type* Allocate();
- // Allocate an array of objects which will be reclaimed when the
- // pool in destroyed. Again, destructors are never called.
- template<typename Type> Type* AllocateArray(int count);
- // Allocate a string which will be destroyed when the pool is destroyed.
- // The string is initialized to the given value for convenience.
- string* AllocateString(const string& value);
- // Allocate a protocol message object. Some older versions of GCC have
- // trouble understanding explicit template instantiations in some cases, so
- // in those cases we have to pass a dummy pointer of the right type as the
- // parameter instead of specifying the type explicitly.
- template<typename Type> Type* AllocateMessage(Type* dummy = NULL);
- // Allocate a FileDescriptorTables object.
- FileDescriptorTables* AllocateFileTables();
- private:
- vector<string*> strings_; // All strings in the pool.
- vector<Message*> messages_; // All messages in the pool.
- vector<FileDescriptorTables*> file_tables_; // All file tables in the pool.
- vector<void*> allocations_; // All other memory allocated in the pool.
- SymbolsByNameMap symbols_by_name_;
- FilesByNameMap files_by_name_;
- ExtensionsGroupedByDescriptorMap extensions_;
- int strings_before_checkpoint_;
- int messages_before_checkpoint_;
- int file_tables_before_checkpoint_;
- int allocations_before_checkpoint_;
- vector<const char* > symbols_after_checkpoint_;
- vector<const char* > files_after_checkpoint_;
- vector<DescriptorIntPair> extensions_after_checkpoint_;
- // Allocate some bytes which will be reclaimed when the pool is
- // destroyed.
- void* AllocateBytes(int size);
- };
- // Contains tables specific to a particular file. These tables are not
- // modified once the file has been constructed, so they need not be
- // protected by a mutex. This makes operations that depend only on the
- // contents of a single file -- e.g. Descriptor::FindFieldByName() --
- // lock-free.
- //
- // For historical reasons, the definitions of the methods of
- // FileDescriptorTables and DescriptorPool::Tables are interleaved below.
- // These used to be a single class.
- class FileDescriptorTables {
- public:
- FileDescriptorTables();
- ~FileDescriptorTables();
- // Empty table, used with placeholder files.
- static const FileDescriptorTables kEmpty;
- // -----------------------------------------------------------------
- // Finding items.
- // Find symbols. These return a null Symbol (symbol.IsNull() is true)
- // if not found.
- inline Symbol FindNestedSymbol(const void* parent,
- const string& name) const;
- inline Symbol FindNestedSymbolOfType(const void* parent,
- const string& name,
- const Symbol::Type type) const;
- // These return NULL if not found.
- inline const FieldDescriptor* FindFieldByNumber(
- const Descriptor* parent, int number) const;
- inline const FieldDescriptor* FindFieldByLowercaseName(
- const void* parent, const string& lowercase_name) const;
- inline const FieldDescriptor* FindFieldByCamelcaseName(
- const void* parent, const string& camelcase_name) const;
- inline const EnumValueDescriptor* FindEnumValueByNumber(
- const EnumDescriptor* parent, int number) const;
- // -----------------------------------------------------------------
- // Adding items.
- // These add items to the corresponding tables. They return false if
- // the key already exists in the table. For AddAliasUnderParent(), the
- // string passed in must be one that was constructed using AllocateString(),
- // as it will be used as a key in the symbols_by_parent_ map without copying.
- bool AddAliasUnderParent(const void* parent, const string& name,
- Symbol symbol);
- bool AddFieldByNumber(const FieldDescriptor* field);
- bool AddEnumValueByNumber(const EnumValueDescriptor* value);
- // Adds the field to the lowercase_name and camelcase_name maps. Never
- // fails because we allow duplicates; the first field by the name wins.
- void AddFieldByStylizedNames(const FieldDescriptor* field);
- private:
- SymbolsByParentMap symbols_by_parent_;
- FieldsByNameMap fields_by_lowercase_name_;
- FieldsByNameMap fields_by_camelcase_name_;
- FieldsByNumberMap fields_by_number_; // Not including extensions.
- EnumValuesByNumberMap enum_values_by_number_;
- };
- DescriptorPool::Tables::Tables()
- : strings_before_checkpoint_(0),
- messages_before_checkpoint_(0),
- allocations_before_checkpoint_(0) {}
- DescriptorPool::Tables::~Tables() {
- // Note that the deletion order is important, since the destructors of some
- // messages may refer to objects in allocations_.
- STLDeleteElements(&messages_);
- for (int i = 0; i < allocations_.size(); i++) {
- operator delete(allocations_[i]);
- }
- STLDeleteElements(&strings_);
- STLDeleteElements(&file_tables_);
- }
- FileDescriptorTables::FileDescriptorTables() {}
- FileDescriptorTables::~FileDescriptorTables() {}
- const FileDescriptorTables FileDescriptorTables::kEmpty;
- void DescriptorPool::Tables::Checkpoint() {
- strings_before_checkpoint_ = strings_.size();
- messages_before_checkpoint_ = messages_.size();
- file_tables_before_checkpoint_ = file_tables_.size();
- allocations_before_checkpoint_ = allocations_.size();
- symbols_after_checkpoint_.clear();
- files_after_checkpoint_.clear();
- extensions_after_checkpoint_.clear();
- }
- void DescriptorPool::Tables::Rollback() {
- for (int i = 0; i < symbols_after_checkpoint_.size(); i++) {
- symbols_by_name_.erase(symbols_after_checkpoint_[i]);
- }
- for (int i = 0; i < files_after_checkpoint_.size(); i++) {
- files_by_name_.erase(files_after_checkpoint_[i]);
- }
- for (int i = 0; i < extensions_after_checkpoint_.size(); i++) {
- extensions_.erase(extensions_after_checkpoint_[i]);
- }
- symbols_after_checkpoint_.clear();
- files_after_checkpoint_.clear();
- extensions_after_checkpoint_.clear();
- STLDeleteContainerPointers(
- strings_.begin() + strings_before_checkpoint_, strings_.end());
- STLDeleteContainerPointers(
- messages_.begin() + messages_before_checkpoint_, messages_.end());
- STLDeleteContainerPointers(
- file_tables_.begin() + file_tables_before_checkpoint_, file_tables_.end());
- for (int i = allocations_before_checkpoint_; i < allocations_.size(); i++) {
- operator delete(allocations_[i]);
- }
- strings_.resize(strings_before_checkpoint_);
- messages_.resize(messages_before_checkpoint_);
- file_tables_.resize(file_tables_before_checkpoint_);
- allocations_.resize(allocations_before_checkpoint_);
- }
- // -------------------------------------------------------------------
- inline Symbol DescriptorPool::Tables::FindSymbol(const string& key) const {
- const Symbol* result = FindOrNull(symbols_by_name_, key.c_str());
- if (result == NULL) {
- return kNullSymbol;
- } else {
- return *result;
- }
- }
- inline Symbol FileDescriptorTables::FindNestedSymbol(
- const void* parent, const string& name) const {
- const Symbol* result =
- FindOrNull(symbols_by_parent_, PointerStringPair(parent, name.c_str()));
- if (result == NULL) {
- return kNullSymbol;
- } else {
- return *result;
- }
- }
- inline Symbol FileDescriptorTables::FindNestedSymbolOfType(
- const void* parent, const string& name, const Symbol::Type type) const {
- Symbol result = FindNestedSymbol(parent, name);
- if (result.type != type) return kNullSymbol;
- return result;
- }
- Symbol DescriptorPool::Tables::FindByNameHelper(
- const DescriptorPool* pool, const string& name) const {
- MutexLockMaybe lock(pool->mutex_);
- Symbol result = FindSymbol(name);
- if (result.IsNull() && pool->underlay_ != NULL) {
- // Symbol not found; check the underlay.
- result =
- pool->underlay_->tables_->FindByNameHelper(pool->underlay_, name);
- }
- if (result.IsNull()) {
- // Symbol still not found, so check fallback database.
- if (pool->TryFindSymbolInFallbackDatabase(name)) {
- result = FindSymbol(name);
- }
- }
- return result;
- }
- inline const FileDescriptor* DescriptorPool::Tables::FindFile(
- const string& key) const {
- return FindPtrOrNull(files_by_name_, key.c_str());
- }
- inline const FieldDescriptor* FileDescriptorTables::FindFieldByNumber(
- const Descriptor* parent, int number) const {
- return FindPtrOrNull(fields_by_number_, make_pair(parent, number));
- }
- inline const FieldDescriptor* FileDescriptorTables::FindFieldByLowercaseName(
- const void* parent, const string& lowercase_name) const {
- return FindPtrOrNull(fields_by_lowercase_name_,
- PointerStringPair(parent, lowercase_name.c_str()));
- }
- inline const FieldDescriptor* FileDescriptorTables::FindFieldByCamelcaseName(
- const void* parent, const string& camelcase_name) const {
- return FindPtrOrNull(fields_by_camelcase_name_,
- PointerStringPair(parent, camelcase_name.c_str()));
- }
- inline const EnumValueDescriptor* FileDescriptorTables::FindEnumValueByNumber(
- const EnumDescriptor* parent, int number) const {
- return FindPtrOrNull(enum_values_by_number_, make_pair(parent, number));
- }
- inline const FieldDescriptor* DescriptorPool::Tables::FindExtension(
- const Descriptor* extendee, int number) {
- return FindPtrOrNull(extensions_, make_pair(extendee, number));
- }
- inline void DescriptorPool::Tables::FindAllExtensions(
- const Descriptor* extendee, vector<const FieldDescriptor*>* out) const {
- ExtensionsGroupedByDescriptorMap::const_iterator it =
- extensions_.lower_bound(make_pair(extendee, 0));
- for (; it != extensions_.end() && it->first.first == extendee; ++it) {
- out->push_back(it->second);
- }
- }
- // -------------------------------------------------------------------
- bool DescriptorPool::Tables::AddSymbol(
- const string& full_name, Symbol symbol) {
- if (InsertIfNotPresent(&symbols_by_name_, full_name.c_str(), symbol)) {
- symbols_after_checkpoint_.push_back(full_name.c_str());
- return true;
- } else {
- return false;
- }
- }
- bool FileDescriptorTables::AddAliasUnderParent(
- const void* parent, const string& name, Symbol symbol) {
- PointerStringPair by_parent_key(parent, name.c_str());
- return InsertIfNotPresent(&symbols_by_parent_, by_parent_key, symbol);
- }
- bool DescriptorPool::Tables::AddFile(const FileDescriptor* file) {
- if (InsertIfNotPresent(&files_by_name_, file->name().c_str(), file)) {
- files_after_checkpoint_.push_back(file->name().c_str());
- return true;
- } else {
- return false;
- }
- }
- void FileDescriptorTables::AddFieldByStylizedNames(
- const FieldDescriptor* field) {
- const void* parent;
- if (field->is_extension()) {
- if (field->extension_scope() == NULL) {
- parent = field->file();
- } else {
- parent = field->extension_scope();
- }
- } else {
- parent = field->containing_type();
- }
- PointerStringPair lowercase_key(parent, field->lowercase_name().c_str());
- InsertIfNotPresent(&fields_by_lowercase_name_, lowercase_key, field);
- PointerStringPair camelcase_key(parent, field->camelcase_name().c_str());
- InsertIfNotPresent(&fields_by_camelcase_name_, camelcase_key, field);
- }
- bool FileDescriptorTables::AddFieldByNumber(const FieldDescriptor* field) {
- DescriptorIntPair key(field->containing_type(), field->number());
- return InsertIfNotPresent(&fields_by_number_, key, field);
- }
- bool FileDescriptorTables::AddEnumValueByNumber(
- const EnumValueDescriptor* value) {
- EnumIntPair key(value->type(), value->number());
- return InsertIfNotPresent(&enum_values_by_number_, key, value);
- }
- bool DescriptorPool::Tables::AddExtension(const FieldDescriptor* field) {
- DescriptorIntPair key(field->containing_type(), field->number());
- if (InsertIfNotPresent(&extensions_, key, field)) {
- extensions_after_checkpoint_.push_back(key);
- return true;
- } else {
- return false;
- }
- }
- // -------------------------------------------------------------------
- template<typename Type>
- Type* DescriptorPool::Tables::Allocate() {
- return reinterpret_cast<Type*>(AllocateBytes(sizeof(Type)));
- }
- template<typename Type>
- Type* DescriptorPool::Tables::AllocateArray(int count) {
- return reinterpret_cast<Type*>(AllocateBytes(sizeof(Type) * count));
- }
- string* DescriptorPool::Tables::AllocateString(const string& value) {
- string* result = new string(value);
- strings_.push_back(result);
- return result;
- }
- template<typename Type>
- Type* DescriptorPool::Tables::AllocateMessage(Type* dummy) {
- Type* result = new Type;
- messages_.push_back(result);
- return result;
- }
- FileDescriptorTables* DescriptorPool::Tables::AllocateFileTables() {
- FileDescriptorTables* result = new FileDescriptorTables;
- file_tables_.push_back(result);
- return result;
- }
- void* DescriptorPool::Tables::AllocateBytes(int size) {
- // TODO(kenton): Would it be worthwhile to implement this in some more
- // sophisticated way? Probably not for the open source release, but for
- // internal use we could easily plug in one of our existing memory pool
- // allocators...
- if (size == 0) return NULL;
- void* result = operator new(size);
- allocations_.push_back(result);
- return result;
- }
- // ===================================================================
- // DescriptorPool
- DescriptorPool::ErrorCollector::~ErrorCollector() {}
- DescriptorPool::DescriptorPool()
- : mutex_(NULL),
- fallback_database_(NULL),
- default_error_collector_(NULL),
- underlay_(NULL),
- tables_(new Tables),
- enforce_dependencies_(true),
- allow_unknown_(false) {}
- DescriptorPool::DescriptorPool(DescriptorDatabase* fallback_database,
- ErrorCollector* error_collector)
- : mutex_(new Mutex),
- fallback_database_(fallback_database),
- default_error_collector_(error_collector),
- underlay_(NULL),
- tables_(new Tables),
- enforce_dependencies_(true),
- allow_unknown_(false) {
- }
- DescriptorPool::DescriptorPool(const DescriptorPool* underlay)
- : mutex_(NULL),
- fallback_database_(NULL),
- default_error_collector_(NULL),
- underlay_(underlay),
- tables_(new Tables),
- enforce_dependencies_(true),
- allow_unknown_(false) {}
- DescriptorPool::~DescriptorPool() {
- if (mutex_ != NULL) delete mutex_;
- }
- // DescriptorPool::BuildFile() defined later.
- // DescriptorPool::BuildFileCollectingErrors() defined later.
- void DescriptorPool::InternalDontEnforceDependencies() {
- enforce_dependencies_ = false;
- }
- bool DescriptorPool::InternalIsFileLoaded(const string& filename) const {
- MutexLockMaybe lock(mutex_);
- return tables_->FindFile(filename) != NULL;
- }
- // generated_pool ====================================================
- namespace {
- EncodedDescriptorDatabase* generated_database_ = NULL;
- DescriptorPool* generated_pool_ = NULL;
- GOOGLE_PROTOBUF_DECLARE_ONCE(generated_pool_init_);
- void DeleteGeneratedPool() {
- delete generated_database_;
- generated_database_ = NULL;
- delete generated_pool_;
- generated_pool_ = NULL;
- }
- void InitGeneratedPool() {
- generated_database_ = new EncodedDescriptorDatabase;
- generated_pool_ = new DescriptorPool(generated_database_);
- internal::OnShutdown(&DeleteGeneratedPool);
- }
- inline void InitGeneratedPoolOnce() {
- ::google::protobuf::GoogleOnceInit(&generated_pool_init_, &InitGeneratedPool);
- }
- } // anonymous namespace
- const DescriptorPool* DescriptorPool::generated_pool() {
- InitGeneratedPoolOnce();
- return generated_pool_;
- }
- DescriptorPool* DescriptorPool::internal_generated_pool() {
- InitGeneratedPoolOnce();
- return generated_pool_;
- }
- void DescriptorPool::InternalAddGeneratedFile(
- const void* encoded_file_descriptor, int size) {
- // So, this function is called in the process of initializing the
- // descriptors for generated proto classes. Each generated .pb.cc file
- // has an internal procedure called AddDescriptors() which is called at
- // process startup, and that function calls this one in order to register
- // the raw bytes of the FileDescriptorProto representing the file.
- //
- // We do not actually construct the descriptor objects right away. We just
- // hang on to the bytes until they are actually needed. We actually construct
- // the descriptor the first time one of the following things happens:
- // * Someone calls a method like descriptor(), GetDescriptor(), or
- // GetReflection() on the generated types, which requires returning the
- // descriptor or an object based on it.
- // * Someone looks up the descriptor in DescriptorPool::generated_pool().
- //
- // Once one of these happens, the DescriptorPool actually parses the
- // FileDescriptorProto and generates a FileDescriptor (and all its children)
- // based on it.
- //
- // Note that FileDescriptorProto is itself a generated protocol message.
- // Therefore, when we parse one, we have to be very careful to avoid using
- // any descriptor-based operations, since this might cause infinite recursion
- // or deadlock.
- InitGeneratedPoolOnce();
- GOOGLE_CHECK(generated_database_->Add(encoded_file_descriptor, size));
- }
- // Find*By* methods ==================================================
- // TODO(kenton): There's a lot of repeated code here, but I'm not sure if
- // there's any good way to factor it out. Think about this some time when
- // there's nothing more important to do (read: never).
- const FileDescriptor* DescriptorPool::FindFileByName(const string& name) const {
- MutexLockMaybe lock(mutex_);
- const FileDescriptor* result = tables_->FindFile(name);
- if (result != NULL) return result;
- if (underlay_ != NULL) {
- const FileDescriptor* result = underlay_->FindFileByName(name);
- if (result != NULL) return result;
- }
- if (TryFindFileInFallbackDatabase(name)) {
- const FileDescriptor* result = tables_->FindFile(name);
- if (result != NULL) return result;
- }
- return NULL;
- }
- const FileDescriptor* DescriptorPool::FindFileContainingSymbol(
- const string& symbol_name) const {
- MutexLockMaybe lock(mutex_);
- Symbol result = tables_->FindSymbol(symbol_name);
- if (!result.IsNull()) return result.GetFile();
- if (underlay_ != NULL) {
- const FileDescriptor* result =
- underlay_->FindFileContainingSymbol(symbol_name);
- if (result != NULL) return result;
- }
- if (TryFindSymbolInFallbackDatabase(symbol_name)) {
- Symbol result = tables_->FindSymbol(symbol_name);
- if (!result.IsNull()) return result.GetFile();
- }
- return NULL;
- }
- const Descriptor* DescriptorPool::FindMessageTypeByName(
- const string& name) const {
- Symbol result = tables_->FindByNameHelper(this, name);
- return (result.type == Symbol::MESSAGE) ? result.descriptor : NULL;
- }
- const FieldDescriptor* DescriptorPool::FindFieldByName(
- const string& name) const {
- Symbol result = tables_->FindByNameHelper(this, name);
- if (result.type == Symbol::FIELD &&
- !result.field_descriptor->is_extension()) {
- return result.field_descriptor;
- } else {
- return NULL;
- }
- }
- const FieldDescriptor* DescriptorPool::FindExtensionByName(
- const string& name) const {
- Symbol result = tables_->FindByNameHelper(this, name);
- if (result.type == Symbol::FIELD &&
- result.field_descriptor->is_extension()) {
- return result.field_descriptor;
- } else {
- return NULL;
- }
- }
- const EnumDescriptor* DescriptorPool::FindEnumTypeByName(
- const string& name) const {
- Symbol result = tables_->FindByNameHelper(this, name);
- return (result.type == Symbol::ENUM) ? result.enum_descriptor : NULL;
- }
- const EnumValueDescriptor* DescriptorPool::FindEnumValueByName(
- const string& name) const {
- Symbol result = tables_->FindByNameHelper(this, name);
- return (result.type == Symbol::ENUM_VALUE) ?
- result.enum_value_descriptor : NULL;
- }
- const ServiceDescriptor* DescriptorPool::FindServiceByName(
- const string& name) const {
- Symbol result = tables_->FindByNameHelper(this, name);
- return (result.type == Symbol::SERVICE) ? result.service_descriptor : NULL;
- }
- const MethodDescriptor* DescriptorPool::FindMethodByName(
- const string& name) const {
- Symbol result = tables_->FindByNameHelper(this, name);
- return (result.type == Symbol::METHOD) ? result.method_descriptor : NULL;
- }
- const FieldDescriptor* DescriptorPool::FindExtensionByNumber(
- const Descriptor* extendee, int number) const {
- MutexLockMaybe lock(mutex_);
- const FieldDescriptor* result = tables_->FindExtension(extendee, number);
- if (result != NULL) {
- return result;
- }
- if (underlay_ != NULL) {
- const FieldDescriptor* result =
- underlay_->FindExtensionByNumber(extendee, number);
- if (result != NULL) return result;
- }
- if (TryFindExtensionInFallbackDatabase(extendee, number)) {
- const FieldDescriptor* result = tables_->FindExtension(extendee, number);
- if (result != NULL) {
- return result;
- }
- }
- return NULL;
- }
- void DescriptorPool::FindAllExtensions(
- const Descriptor* extendee, vector<const FieldDescriptor*>* out) const {
- MutexLockMaybe lock(mutex_);
- // Initialize tables_->extensions_ from the fallback database first
- // (but do this only once per descriptor).
- if (fallback_database_ != NULL &&
- tables_->extensions_loaded_from_db_.count(extendee) == 0) {
- vector<int> numbers;
- if (fallback_database_->FindAllExtensionNumbers(extendee->full_name(),
- &numbers)) {
- for (int i = 0; i < numbers.size(); ++i) {
- int number = numbers[i];
- if (tables_->FindExtension(extendee, number) == NULL) {
- TryFindExtensionInFallbackDatabase(extendee, number);
- }
- }
- tables_->extensions_loaded_from_db_.insert(extendee);
- }
- }
- tables_->FindAllExtensions(extendee, out);
- if (underlay_ != NULL) {
- underlay_->FindAllExtensions(extendee, out);
- }
- }
- // -------------------------------------------------------------------
- const FieldDescriptor*
- Descriptor::FindFieldByNumber(int key) const {
- const FieldDescriptor* result =
- file()->tables_->FindFieldByNumber(this, key);
- if (result == NULL || result->is_extension()) {
- return NULL;
- } else {
- return result;
- }
- }
- const FieldDescriptor*
- Descriptor::FindFieldByLowercaseName(const string& key) const {
- const FieldDescriptor* result =
- file()->tables_->FindFieldByLowercaseName(this, key);
- if (result == NULL || result->is_extension()) {
- return NULL;
- } else {
- return result;
- }
- }
- const FieldDescriptor*
- Descriptor::FindFieldByCamelcaseName(const string& key) const {
- const FieldDescriptor* result =
- file()->tables_->FindFieldByCamelcaseName(this, key);
- if (result == NULL || result->is_extension()) {
- return NULL;
- } else {
- return result;
- }
- }
- const FieldDescriptor*
- Descriptor::FindFieldByName(const string& key) const {
- Symbol result =
- file()->tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD);
- if (!result.IsNull() && !result.field_descriptor->is_extension()) {
- return result.field_descriptor;
- } else {
- return NULL;
- }
- }
- const FieldDescriptor*
- Descriptor::FindExtensionByName(const string& key) const {
- Symbol result =
- file()->tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD);
- if (!result.IsNull() && result.field_descriptor->is_extension()) {
- return result.field_descriptor;
- } else {
- return NULL;
- }
- }
- const FieldDescriptor*
- Descriptor::FindExtensionByLowercaseName(const string& key) const {
- const FieldDescriptor* result =
- file()->tables_->FindFieldByLowercaseName(this, key);
- if (result == NULL || !result->is_extension()) {
- return NULL;
- } else {
- return result;
- }
- }
- const FieldDescriptor*
- Descriptor::FindExtensionByCamelcaseName(const string& key) const {
- const FieldDescriptor* result =
- file()->tables_->FindFieldByCamelcaseName(this, key);
- if (result == NULL || !result->is_extension()) {
- return NULL;
- } else {
- return result;
- }
- }
- const Descriptor*
- Descriptor::FindNestedTypeByName(const string& key) const {
- Symbol result =
- file()->tables_->FindNestedSymbolOfType(this, key, Symbol::MESSAGE);
- if (!result.IsNull()) {
- return result.descriptor;
- } else {
- return NULL;
- }
- }
- const EnumDescriptor*
- Descriptor::FindEnumTypeByName(const string& key) const {
- Symbol result =
- file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM);
- if (!result.IsNull()) {
- return result.enum_descriptor;
- } else {
- return NULL;
- }
- }
- const EnumValueDescriptor*
- Descriptor::FindEnumValueByName(const string& key) const {
- Symbol result =
- file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE);
- if (!result.IsNull()) {
- return result.enum_value_descriptor;
- } else {
- return NULL;
- }
- }
- const EnumValueDescriptor*
- EnumDescriptor::FindValueByName(const string& key) const {
- Symbol result =
- file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE);
- if (!result.IsNull()) {
- return result.enum_value_descriptor;
- } else {
- return NULL;
- }
- }
- const EnumValueDescriptor*
- EnumDescriptor::FindValueByNumber(int key) const {
- return file()->tables_->FindEnumValueByNumber(this, key);
- }
- const MethodDescriptor*
- ServiceDescriptor::FindMethodByName(const string& key) const {
- Symbol result =
- file()->tables_->FindNestedSymbolOfType(this, key, Symbol::METHOD);
- if (!result.IsNull()) {
- return result.method_descriptor;
- } else {
- return NULL;
- }
- }
- const Descriptor*
- FileDescriptor::FindMessageTypeByName(const string& key) const {
- Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::MESSAGE);
- if (!result.IsNull()) {
- return result.descriptor;
- } else {
- return NULL;
- }
- }
- const EnumDescriptor*
- FileDescriptor::FindEnumTypeByName(const string& key) const {
- Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM);
- if (!result.IsNull()) {
- return result.enum_descriptor;
- } else {
- return NULL;
- }
- }
- const EnumValueDescriptor*
- FileDescriptor::FindEnumValueByName(const string& key) const {
- Symbol result =
- tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE);
- if (!result.IsNull()) {
- return result.enum_value_descriptor;
- } else {
- return NULL;
- }
- }
- const ServiceDescriptor*
- FileDescriptor::FindServiceByName(const string& key) const {
- Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::SERVICE);
- if (!result.IsNull()) {
- return result.service_descriptor;
- } else {
- return NULL;
- }
- }
- const FieldDescriptor*
- FileDescriptor::FindExtensionByName(const string& key) const {
- Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD);
- if (!result.IsNull() && result.field_descriptor->is_extension()) {
- return result.field_descriptor;
- } else {
- return NULL;
- }
- }
- const FieldDescriptor*
- FileDescriptor::FindExtensionByLowercaseName(const string& key) const {
- const FieldDescriptor* result = tables_->FindFieldByLowercaseName(this, key);
- if (result == NULL || !result->is_extension()) {
- return NULL;
- } else {
- return result;
- }
- }
- const FieldDescriptor*
- FileDescriptor::FindExtensionByCamelcaseName(const string& key) const {
- const FieldDescriptor* result = tables_->FindFieldByCamelcaseName(this, key);
- if (result == NULL || !result->is_extension()) {
- return NULL;
- } else {
- return result;
- }
- }
- bool Descriptor::IsExtensionNumber(int number) const {
- // Linear search should be fine because we don't expect a message to have
- // more than a couple extension ranges.
- for (int i = 0; i < extension_range_count(); i++) {
- if (number >= extension_range(i)->start &&
- number < extension_range(i)->end) {
- return true;
- }
- }
- return false;
- }
- // -------------------------------------------------------------------
- bool DescriptorPool::TryFindFileInFallbackDatabase(const string& name) const {
- if (fallback_database_ == NULL) return false;
- if (tables_->known_bad_files_.count(name) > 0) return false;
- FileDescriptorProto file_proto;
- if (!fallback_database_->FindFileByName(name, &file_proto) ||
- BuildFileFromDatabase(file_proto) == NULL) {
- tables_->known_bad_files_.insert(name);
- return false;
- }
- return true;
- }
- bool DescriptorPool::TryFindSymbolInFallbackDatabase(const string& name) const {
- if (fallback_database_ == NULL) return false;
- FileDescriptorProto file_proto;
- if (!fallback_database_->FindFileContainingSymbol(name, &file_proto)) {
- return false;
- }
- if (tables_->FindFile(file_proto.name()) != NULL) {
- // We've already loaded this file, and it apparently doesn't contain the
- // symbol we're looking for. Some DescriptorDatabases return false
- // positives.
- return false;
- }
- if (BuildFileFromDatabase(file_proto) == NULL) {
- return false;
- }
- return true;
- }
- bool DescriptorPool::TryFindExtensionInFallbackDatabase(
- const Descriptor* containing_type, int field_number) const {
- if (fallback_database_ == NULL) return false;
- FileDescriptorProto file_proto;
- if (!fallback_database_->FindFileContainingExtension(
- containing_type->full_name(), field_number, &file_proto)) {
- return false;
- }
- if (tables_->FindFile(file_proto.name()) != NULL) {
- // We've already loaded this file, and it apparently doesn't contain the
- // extension we're looking for. Some DescriptorDatabases return false
- // positives.
- return false;
- }
- if (BuildFileFromDatabase(file_proto) == NULL) {
- return false;
- }
- return true;
- }
- // ===================================================================
- string FieldDescriptor::DefaultValueAsString(bool quote_string_type) const {
- GOOGLE_CHECK(has_default_value()) << "No default value";
- switch (cpp_type()) {
- case CPPTYPE_INT32:
- return SimpleItoa(default_value_int32());
- break;
- case CPPTYPE_INT64:
- return SimpleItoa(default_value_int64());
- break;
- case CPPTYPE_UINT32:
- return SimpleItoa(default_value_uint32());
- break;
- case CPPTYPE_UINT64:
- return SimpleItoa(default_value_uint64());
- break;
- case CPPTYPE_FLOAT:
- return SimpleFtoa(default_value_float());
- break;
- case CPPTYPE_DOUBLE:
- return SimpleDtoa(default_value_double());
- break;
- case CPPTYPE_BOOL:
- return default_value_bool() ? "true" : "false";
- break;
- case CPPTYPE_STRING:
- if (quote_string_type) {
- return "\"" + CEscape(default_value_string()) + "\"";
- } else {
- if (type() == TYPE_BYTES) {
- return CEscape(default_value_string());
- } else {
- return default_value_string();
- }
- }
- break;
- case CPPTYPE_ENUM:
- return default_value_enum()->name();
- break;
- case CPPTYPE_MESSAGE:
- GOOGLE_LOG(DFATAL) << "Messages can't have default values!";
- break;
- }
- GOOGLE_LOG(FATAL) << "Can't get here: failed to get default value as string";
- return "";
- }
- // CopyTo methods ====================================================
- void FileDescriptor::CopyTo(FileDescriptorProto* proto) const {
- proto->set_name(name());
- if (!package().empty()) proto->set_package(package());
- for (int i = 0; i < dependency_count(); i++) {
- proto->add_dependency(dependency(i)->name());
- }
- for (int i = 0; i < message_type_count(); i++) {
- message_type(i)->CopyTo(proto->add_message_type());
- }
- for (int i = 0; i < enum_type_count(); i++) {
- enum_type(i)->CopyTo(proto->add_enum_type());
- }
- for (int i = 0; i < service_count(); i++) {
- service(i)->CopyTo(proto->add_service());
- }
- for (int i = 0; i < extension_count(); i++) {
- extension(i)->CopyTo(proto->add_extension());
- }
- if (&options() != &FileOptions::default_instance()) {
- proto->mutable_options()->CopyFrom(options());
- }
- }
- void Descriptor::CopyTo(DescriptorProto* proto) const {
- proto->set_name(name());
- for (int i = 0; i < field_count(); i++) {
- field(i)->CopyTo(proto->add_field());
- }
- for (int i = 0; i < nested_type_count(); i++) {
- nested_type(i)->CopyTo(proto->add_nested_type());
- }
- for (int i = 0; i < enum_type_count(); i++) {
- enum_type(i)->CopyTo(proto->add_enum_type());
- }
- for (int i = 0; i < extension_range_count(); i++) {
- DescriptorProto::ExtensionRange* range = proto->add_extension_range();
- range->set_start(extension_range(i)->start);
- range->set_end(extension_range(i)->end);
- }
- for (int i = 0; i < extension_count(); i++) {
- extension(i)->CopyTo(proto->add_extension());
- }
- if (&options() != &MessageOptions::default_instance()) {
- proto->mutable_options()->CopyFrom(options());
- }
- }
- void FieldDescriptor::CopyTo(FieldDescriptorProto* proto) const {
- proto->set_name(name());
- proto->set_number(number());
- // Some compilers do not allow static_cast directly between two enum types,
- // so we must cast to int first.
- proto->set_label(static_cast<FieldDescriptorProto::Label>(
- implicit_cast<int>(label())));
- proto->set_type(static_cast<FieldDescriptorProto::Type>(
- implicit_cast<int>(type())));
- if (is_extension()) {
- if (!containing_type()->is_unqualified_placeholder_) {
- proto->set_extendee(".");
- }
- proto->mutable_extendee()->append(containing_type()->full_name());
- }
- if (cpp_type() == CPPTYPE_MESSAGE) {
- if (message_type()->is_placeholder_) {
- // We don't actually know if the type is a message type. It could be
- // an enum.
- proto->clear_type();
- }
- if (!message_type()->is_unqualified_placeholder_) {
- proto->set_type_name(".");
- }
- proto->mutable_type_name()->append(message_type()->full_name());
- } else if (cpp_type() == CPPTYPE_ENUM) {
- if (!enum_type()->is_unqualified_placeholder_) {
- proto->set_type_name(".");
- }
- proto->mutable_type_name()->append(enum_type()->full_name());
- }
- if (has_default_value()) {
- proto->set_default_value(DefaultValueAsString(false));
- }
- if (&options() != &FieldOptions::default_instance()) {
- proto->mutable_options()->CopyFrom(options());
- }
- }
- void EnumDescriptor::CopyTo(EnumDescriptorProto* proto) const {
- proto->set_name(name());
- for (int i = 0; i < value_count(); i++) {
- value(i)->CopyTo(proto->add_value());
- }
- if (&options() != &EnumOptions::default_instance()) {
- proto->mutable_options()->CopyFrom(options());
- }
- }
- void EnumValueDescriptor::CopyTo(EnumValueDescriptorProto* proto) const {
- proto->set_name(name());
- proto->set_number(number());
- if (&options() != &EnumValueOptions::default_instance()) {
- proto->mutable_options()->CopyFrom(options());
- }
- }
- void ServiceDescriptor::CopyTo(ServiceDescriptorProto* proto) const {
- proto->set_name(name());
- for (int i = 0; i < method_count(); i++) {
- method(i)->CopyTo(proto->add_method());
- }
- if (&options() != &ServiceOptions::default_instance()) {
- proto->mutable_options()->CopyFrom(options());
- }
- }
- void MethodDescriptor::CopyTo(MethodDescriptorProto* proto) const {
- proto->set_name(name());
- if (!input_type()->is_unqualified_placeholder_) {
- proto->set_input_type(".");
- }
- proto->mutable_input_type()->append(input_type()->full_name());
- if (!output_type()->is_unqualified_placeholder_) {
- proto->set_output_type(".");
- }
- proto->mutable_output_type()->append(output_type()->full_name());
- if (&options() != &MethodOptions::default_instance()) {
- proto->mutable_options()->CopyFrom(options());
- }
- }
- // DebugString methods ===============================================
- namespace {
- // Used by each of the option formatters.
- bool RetrieveOptions(const Message &options, vector<string> *option_entries) {
- option_entries->clear();
- const Reflection* reflection = options.GetReflection();
- vector<const FieldDescriptor*> fields;
- reflection->ListFields(options, &fields);
- for (int i = 0; i < fields.size(); i++) {
- // Doesn't make sense to have message type fields here
- if (fields[i]->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- continue;
- }
- int count = 1;
- bool repeated = false;
- if (fields[i]->is_repeated()) {
- count = reflection->FieldSize(options, fields[i]);
- repeated = true;
- }
- for (int j = 0; j < count; j++) {
- string fieldval;
- TextFormat::PrintFieldValueToString(options, fields[i],
- repeated ? count : -1, &fieldval);
- option_entries->push_back(fields[i]->name() + " = " + fieldval);
- }
- }
- return !option_entries->empty();
- }
- // Formats options that all appear together in brackets. Does not include
- // brackets.
- bool FormatBracketedOptions(const Message &options, string *output) {
- vector<string> all_options;
- if (RetrieveOptions(options, &all_options)) {
- output->append(JoinStrings(all_options, ", "));
- }
- return !all_options.empty();
- }
- // Formats options one per line
- bool FormatLineOptions(int depth, const Message &options, string *output) {
- string prefix(depth * 2, ' ');
- vector<string> all_options;
- if (RetrieveOptions(options, &all_options)) {
- for (int i = 0; i < all_options.size(); i++) {
- strings::SubstituteAndAppend(output, "$0option $1;\n",
- prefix, all_options[i]);
- }
- }
- return !all_options.empty();
- }
- } // anonymous namespace
- string FileDescriptor::DebugString() const {
- string contents = "syntax = \"proto2\";\n\n";
- for (int i = 0; i < dependency_count(); i++) {
- strings::SubstituteAndAppend(&contents, "import \"$0\";\n",
- dependency(i)->name());
- }
- if (!package().empty()) {
- strings::SubstituteAndAppend(&contents, "package $0;\n\n", package());
- }
- if (FormatLineOptions(0, options(), &contents)) {
- contents.append("\n"); // add some space if we had options
- }
- for (int i = 0; i < enum_type_count(); i++) {
- enum_type(i)->DebugString(0, &contents);
- contents.append("\n");
- }
- // Find all the 'group' type extensions; we will not output their nested
- // definitions (those will be done with their group field descriptor).
- set<const Descriptor*> groups;
- for (int i = 0; i < extension_count(); i++) {
- if (extension(i)->type() == FieldDescriptor::TYPE_GROUP) {
- groups.insert(extension(i)->message_type());
- }
- }
- for (int i = 0; i < message_type_count(); i++) {
- if (groups.count(message_type(i)) == 0) {
- strings::SubstituteAndAppend(&contents, "message $0",
- message_type(i)->name());
- message_type(i)->DebugString(0, &contents);
- contents.append("\n");
- }
- }
- for (int i = 0; i < service_count(); i++) {
- service(i)->DebugString(&contents);
- contents.append("\n");
- }
- const Descriptor* containing_type = NULL;
- for (int i = 0; i < extension_count(); i++) {
- if (extension(i)->containing_type() != containing_type) {
- if (i > 0) contents.append("}\n\n");
- containing_type = extension(i)->containing_type();
- strings::SubstituteAndAppend(&contents, "extend .$0 {\n",
- containing_type->full_name());
- }
- extension(i)->DebugString(1, &contents);
- }
- if (extension_count() > 0) contents.append("}\n\n");
- return contents;
- }
- string Descriptor::DebugString() const {
- string contents;
- strings::SubstituteAndAppend(&contents, "message $0", name());
- DebugString(0, &contents);
- return contents;
- }
- void Descriptor::DebugString(int depth, string *contents) const {
- string prefix(depth * 2, ' ');
- ++depth;
- contents->append(" {\n");
- FormatLineOptions(depth, options(), contents);
- // Find all the 'group' types for fields and extensions; we will not output
- // their nested definitions (those will be done with their group field
- // descriptor).
- set<const Descriptor*> groups;
- for (int i = 0; i < field_count(); i++) {
- if (field(i)->type() == FieldDescriptor::TYPE_GROUP) {
- groups.insert(field(i)->message_type());
- }
- }
- for (int i = 0; i < extension_count(); i++) {
- if (extension(i)->type() == FieldDescriptor::TYPE_GROUP) {
- groups.insert(extension(i)->message_type());
- }
- }
- for (int i = 0; i < nested_type_count(); i++) {
- if (groups.count(nested_type(i)) == 0) {
- strings::SubstituteAndAppend(contents, "$0 message $1",
- prefix, nested_type(i)->name());
- nested_type(i)->DebugString(depth, contents);
- }
- }
- for (int i = 0; i < enum_type_count(); i++) {
- enum_type(i)->DebugString(depth, contents);
- }
- for (int i = 0; i < field_count(); i++) {
- field(i)->DebugString(depth, contents);
- }
- for (int i = 0; i < extension_range_count(); i++) {
- strings::SubstituteAndAppend(contents, "$0 extensions $1 to $2;\n",
- prefix,
- extension_range(i)->start,
- extension_range(i)->end - 1);
- }
- // Group extensions by what they extend, so they can be printed out together.
- const Descriptor* containing_type = NULL;
- for (int i = 0; i < extension_count(); i++) {
- if (extension(i)->containing_type() != containing_type) {
- if (i > 0) strings::SubstituteAndAppend(contents, "$0 }\n", prefix);
- containing_type = extension(i)->containing_type();
- strings::SubstituteAndAppend(contents, "$0 extend .$1 {\n",
- prefix, containing_type->full_name());
- }
- extension(i)->DebugString(depth + 1, contents);
- }
- if (extension_count() > 0)
- strings::SubstituteAndAppend(contents, "$0 }\n", prefix);
- strings::SubstituteAndAppend(contents, "$0}\n", prefix);
- }
- string FieldDescriptor::DebugString() const {
- string contents;
- int depth = 0;
- if (is_extension()) {
- strings::SubstituteAndAppend(&contents, "extend .$0 {\n",
- containing_type()->full_name());
- depth = 1;
- }
- DebugString(depth, &contents);
- if (is_extension()) {
- contents.append("}\n");
- }
- return contents;
- }
- void FieldDescriptor::DebugString(int depth, string *contents) const {
- string prefix(depth * 2, ' ');
- string field_type;
- switch (type()) {
- case TYPE_MESSAGE:
- field_type = "." + message_type()->full_name();
- break;
- case TYPE_ENUM:
- field_type = "." + enum_type()->full_name();
- break;
- default:
- field_type = kTypeToName[type()];
- }
- strings::SubstituteAndAppend(contents, "$0$1 $2 $3 = $4",
- prefix,
- kLabelToName[label()],
- field_type,
- type() == TYPE_GROUP ? message_type()->name() :
- name(),
- number());
- bool bracketed = false;
- if (has_default_value()) {
- bracketed = true;
- strings::SubstituteAndAppend(contents, " [default = $0",
- DefaultValueAsString(true));
- }
- string formatted_options;
- if (FormatBracketedOptions(options(), &formatted_options)) {
- contents->append(bracketed ? ", " : " [");
- bracketed = true;
- contents->append(formatted_options);
- }
- if (bracketed) {
- contents->append("]");
- }
- if (type() == TYPE_GROUP) {
- message_type()->DebugString(depth, contents);
- } else {
- contents->append(";\n");
- }
- }
- string EnumDescriptor::DebugString() const {
- string contents;
- DebugString(0, &contents);
- return contents;
- }
- void EnumDescriptor::DebugString(int depth, string *contents) const {
- string prefix(depth * 2, ' ');
- ++depth;
- strings::SubstituteAndAppend(contents, "$0enum $1 {\n",
- prefix, name());
- FormatLineOptions(depth, options(), contents);
- for (int i = 0; i < value_count(); i++) {
- value(i)->DebugString(depth, contents);
- }
- strings::SubstituteAndAppend(contents, "$0}\n", prefix);
- }
- string EnumValueDescriptor::DebugString() const {
- string contents;
- DebugString(0, &contents);
- return contents;
- }
- void EnumValueDescriptor::DebugString(int depth, string *contents) const {
- string prefix(depth * 2, ' ');
- strings::SubstituteAndAppend(contents, "$0$1 = $2",
- prefix, name(), number());
- string formatted_options;
- if (FormatBracketedOptions(options(), &formatted_options)) {
- strings::SubstituteAndAppend(contents, " [$0]", formatted_options);
- }
- contents->append(";\n");
- }
- string ServiceDescriptor::DebugString() const {
- string contents;
- DebugString(&contents);
- return contents;
- }
- void ServiceDescriptor::DebugString(string *contents) const {
- strings::SubstituteAndAppend(contents, "service $0 {\n", name());
- FormatLineOptions(1, options(), contents);
- for (int i = 0; i < method_count(); i++) {
- method(i)->DebugString(1, contents);
- }
- contents->append("}\n");
- }
- string MethodDescriptor::DebugString() const {
- string contents;
- DebugString(0, &contents);
- return contents;
- }
- void MethodDescriptor::DebugString(int depth, string *contents) const {
- string prefix(depth * 2, ' ');
- ++depth;
- strings::SubstituteAndAppend(contents, "$0rpc $1(.$2) returns (.$3)",
- prefix, name(),
- input_type()->full_name(),
- output_type()->full_name());
- string formatted_options;
- if (FormatLineOptions(depth, options(), &formatted_options)) {
- strings::SubstituteAndAppend(contents, " {\n$0$1}\n",
- formatted_options, prefix);
- } else {
- contents->append(";\n");
- }
- }
- // ===================================================================
- namespace {
- // Represents an options message to interpret. Extension names in the option
- // name are respolved relative to name_scope. element_name and orig_opt are
- // used only for error reporting (since the parser records locations against
- // pointers in the original options, not the mutable copy). The Message must be
- // one of the Options messages in descriptor.proto.
- struct OptionsToInterpret {
- OptionsToInterpret(const string& ns,
- const string& el,
- const Message* orig_opt,
- Message* opt)
- : name_scope(ns),
- element_name(el),
- original_options(orig_opt),
- options(opt) {
- }
- string name_scope;
- string element_name;
- const Message* original_options;
- Message* options;
- };
- } // namespace
- class DescriptorBuilder {
- public:
- DescriptorBuilder(const DescriptorPool* pool,
- DescriptorPool::Tables* tables,
- DescriptorPool::ErrorCollector* error_collector);
- ~DescriptorBuilder();
- const FileDescriptor* BuildFile(const FileDescriptorProto& proto);
- private:
- friend class OptionInterpreter;
- const DescriptorPool* pool_;
- DescriptorPool::Tables* tables_; // for convenience
- DescriptorPool::ErrorCollector* error_collector_;
- // As we build descriptors we store copies of the options messages in
- // them. We put pointers to those copies in this vector, as we build, so we
- // can later (after cross-linking) interpret those options.
- vector<OptionsToInterpret> options_to_interpret_;
- bool had_errors_;
- string filename_;
- FileDescriptor* file_;
- FileDescriptorTables* file_tables_;
- // If LookupSymbol() finds a symbol that is in a file which is not a declared
- // dependency of this file, it will fail, but will set
- // possible_undeclared_dependency_ to point at that file. This is only used
- // by AddNotDefinedError() to report a more useful error message.
- // possible_undeclared_dependency_name_ is the name of the symbol that was
- // actually found in possible_undeclared_dependency_, which may be a parent
- // of the symbol actually looked for.
- const FileDescriptor* possible_undeclared_dependency_;
- string possible_undeclared_dependency_name_;
- void AddError(const string& element_name,
- const Message& descriptor,
- DescriptorPool::ErrorCollector::ErrorLocation location,
- const string& error);
- // Adds an error indicating that undefined_symbol was not defined. Must
- // only be called after LookupSymbol() fails.
- void AddNotDefinedError(
- const string& element_name,
- const Message& descriptor,
- DescriptorPool::ErrorCollector::ErrorLocation location,
- const string& undefined_symbol);
- // Silly helper which determines if the given file is in the given package.
- // I.e., either file->package() == package_name or file->package() is a
- // nested package within package_name.
- bool IsInPackage(const FileDescriptor* file, const string& package_name);
- // Like tables_->FindSymbol(), but additionally:
- // - Search the pool's underlay if not found in tables_.
- // - Insure that the resulting Symbol is from one of the file's declared
- // dependencies.
- Symbol FindSymbol(const string& name);
- // Like FindSymbol() but does not require that the symbol is in one of the
- // file's declared dependencies.
- Symbol FindSymbolNotEnforcingDeps(const string& name);
- // Like FindSymbol(), but looks up the name relative to some other symbol
- // name. This first searches siblings of relative_to, then siblings of its
- // parents, etc. For example, LookupSymbol("foo.bar", "baz.qux.corge") makes
- // the following calls, returning the first non-null result:
- // FindSymbol("baz.qux.foo.bar"), FindSymbol("baz.foo.bar"),
- // FindSymbol("foo.bar"). If AllowUnknownDependencies() has been called
- // on the DescriptorPool, this will generate a placeholder type if
- // the name is not found (unless the name itself is malformed). The
- // placeholder_type parameter indicates what kind of placeholder should be
- // constructed in this case. The resolve_mode parameter determines whether
- // any symbol is returned, or only symbols that are types. Note, however,
- // that LookupSymbol may still return a non-type symbol in LOOKUP_TYPES mode,
- // if it believes that's all it could refer to. The caller should always
- // check that it receives the type of symbol it was expecting.
- enum PlaceholderType {
- PLACEHOLDER_MESSAGE,
- PLACEHOLDER_ENUM,
- PLACEHOLDER_EXTENDABLE_MESSAGE
- };
- enum ResolveMode {
- LOOKUP_ALL, LOOKUP_TYPES
- };
- Symbol LookupSymbol(const string& name, const string& relative_to,
- PlaceholderType placeholder_type = PLACEHOLDER_MESSAGE,
- ResolveMode resolve_mode = LOOKUP_ALL);
- // Like LookupSymbol() but will not return a placeholder even if
- // AllowUnknownDependencies() has been used.
- Symbol LookupSymbolNoPlaceholder(const string& name,
- const string& relative_to,
- ResolveMode resolve_mode = LOOKUP_ALL);
- // Creates a placeholder type suitable for return from LookupSymbol(). May
- // return kNullSymbol if the name is not a valid type name.
- Symbol NewPlaceholder(const string& name, PlaceholderType placeholder_type);
- // Creates a placeholder file. Never returns NULL. This is used when an
- // import is not found and AllowUnknownDependencies() is enabled.
- const FileDescriptor* NewPlaceholderFile(const string& name);
- // Calls tables_->AddSymbol() and records an error if it fails. Returns
- // true if successful or false if failed, though most callers can ignore
- // the return value since