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 // Interface for manipulating databases of descriptors. 36 37 #ifndef GOOGLE_PROTOBUF_DESCRIPTOR_DATABASE_H__ 38 #define GOOGLE_PROTOBUF_DESCRIPTOR_DATABASE_H__ 39 40 #include <map> 41 #include <string> 42 #include <utility> 43 #include <vector> 44 #include <google/protobuf/stubs/common.h> 45 #include <google/protobuf/descriptor.h> 46 47 #include <google/protobuf/port_def.inc> 48 49 #ifdef SWIG 50 #define PROTOBUF_EXPORT 51 #endif 52 53 namespace google { 54 namespace protobuf { 55 56 // Defined in this file. 57 class DescriptorDatabase; 58 class SimpleDescriptorDatabase; 59 class EncodedDescriptorDatabase; 60 class DescriptorPoolDatabase; 61 class MergedDescriptorDatabase; 62 63 // Abstract interface for a database of descriptors. 64 // 65 // This is useful if you want to create a DescriptorPool which loads 66 // descriptors on-demand from some sort of large database. If the database 67 // is large, it may be inefficient to enumerate every .proto file inside it 68 // calling DescriptorPool::BuildFile() for each one. Instead, a DescriptorPool 69 // can be created which wraps a DescriptorDatabase and only builds particular 70 // descriptors when they are needed. 71 class PROTOBUF_EXPORT DescriptorDatabase { 72 public: DescriptorDatabase()73 inline DescriptorDatabase() {} 74 virtual ~DescriptorDatabase(); 75 76 // Find a file by file name. Fills in in *output and returns true if found. 77 // Otherwise, returns false, leaving the contents of *output undefined. 78 virtual bool FindFileByName(const std::string& filename, 79 FileDescriptorProto* output) = 0; 80 81 // Find the file that declares the given fully-qualified symbol name. 82 // If found, fills in *output and returns true, otherwise returns false 83 // and leaves *output undefined. 84 virtual bool FindFileContainingSymbol(const std::string& symbol_name, 85 FileDescriptorProto* output) = 0; 86 87 // Find the file which defines an extension extending the given message type 88 // with the given field number. If found, fills in *output and returns true, 89 // otherwise returns false and leaves *output undefined. containing_type 90 // must be a fully-qualified type name. 91 virtual bool FindFileContainingExtension(const std::string& containing_type, 92 int field_number, 93 FileDescriptorProto* output) = 0; 94 95 // Finds the tag numbers used by all known extensions of 96 // extendee_type, and appends them to output in an undefined 97 // order. This method is best-effort: it's not guaranteed that the 98 // database will find all extensions, and it's not guaranteed that 99 // FindFileContainingExtension will return true on all of the found 100 // numbers. Returns true if the search was successful, otherwise 101 // returns false and leaves output unchanged. 102 // 103 // This method has a default implementation that always returns 104 // false. FindAllExtensionNumbers(const std::string &,std::vector<int> *)105 virtual bool FindAllExtensionNumbers(const std::string& /* extendee_type */, 106 std::vector<int>* /* output */) { 107 return false; 108 } 109 110 111 // Finds the file names and appends them to the output in an 112 // undefined order. This method is best-effort: it's not guaranteed that the 113 // database will find all files. Returns true if the database supports 114 // searching all file names, otherwise returns false and leaves output 115 // unchanged. 116 // 117 // This method has a default implementation that always returns 118 // false. FindAllFileNames(std::vector<std::string> * output)119 virtual bool FindAllFileNames(std::vector<std::string>* output) { 120 return false; 121 } 122 123 // Finds the package names and appends them to the output in an 124 // undefined order. This method is best-effort: it's not guaranteed that the 125 // database will find all packages. Returns true if the database supports 126 // searching all package names, otherwise returns false and leaves output 127 // unchanged. 128 bool FindAllPackageNames(std::vector<std::string>* output); 129 130 // Finds the message names and appends them to the output in an 131 // undefined order. This method is best-effort: it's not guaranteed that the 132 // database will find all messages. Returns true if the database supports 133 // searching all message names, otherwise returns false and leaves output 134 // unchanged. 135 bool FindAllMessageNames(std::vector<std::string>* output); 136 137 private: 138 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorDatabase); 139 }; 140 141 // A DescriptorDatabase into which you can insert files manually. 142 // 143 // FindFileContainingSymbol() is fully-implemented. When you add a file, its 144 // symbols will be indexed for this purpose. Note that the implementation 145 // may return false positives, but only if it isn't possible for the symbol 146 // to be defined in any other file. In particular, if a file defines a symbol 147 // "Foo", then searching for "Foo.[anything]" will match that file. This way, 148 // the database does not need to aggressively index all children of a symbol. 149 // 150 // FindFileContainingExtension() is mostly-implemented. It works if and only 151 // if the original FieldDescriptorProto defining the extension has a 152 // fully-qualified type name in its "extendee" field (i.e. starts with a '.'). 153 // If the extendee is a relative name, SimpleDescriptorDatabase will not 154 // attempt to resolve the type, so it will not know what type the extension is 155 // extending. Therefore, calling FindFileContainingExtension() with the 156 // extension's containing type will never actually find that extension. Note 157 // that this is an unlikely problem, as all FileDescriptorProtos created by the 158 // protocol compiler (as well as ones created by calling 159 // FileDescriptor::CopyTo()) will always use fully-qualified names for all 160 // types. You only need to worry if you are constructing FileDescriptorProtos 161 // yourself, or are calling compiler::Parser directly. 162 class PROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { 163 public: 164 SimpleDescriptorDatabase(); 165 ~SimpleDescriptorDatabase() override; 166 167 // Adds the FileDescriptorProto to the database, making a copy. The object 168 // can be deleted after Add() returns. Returns false if the file conflicted 169 // with a file already in the database, in which case an error will have 170 // been written to GOOGLE_LOG(ERROR). 171 bool Add(const FileDescriptorProto& file); 172 173 // Adds the FileDescriptorProto to the database and takes ownership of it. 174 bool AddAndOwn(const FileDescriptorProto* file); 175 176 // implements DescriptorDatabase ----------------------------------- 177 bool FindFileByName(const std::string& filename, 178 FileDescriptorProto* output) override; 179 bool FindFileContainingSymbol(const std::string& symbol_name, 180 FileDescriptorProto* output) override; 181 bool FindFileContainingExtension(const std::string& containing_type, 182 int field_number, 183 FileDescriptorProto* output) override; 184 bool FindAllExtensionNumbers(const std::string& extendee_type, 185 std::vector<int>* output) override; 186 187 bool FindAllFileNames(std::vector<std::string>* output) override; 188 189 private: 190 // So that it can use DescriptorIndex. 191 friend class EncodedDescriptorDatabase; 192 193 // An index mapping file names, symbol names, and extension numbers to 194 // some sort of values. 195 template <typename Value> 196 class DescriptorIndex { 197 public: 198 // Helpers to recursively add particular descriptors and all their contents 199 // to the index. 200 bool AddFile(const FileDescriptorProto& file, Value value); 201 bool AddSymbol(const std::string& name, Value value); 202 bool AddNestedExtensions(const std::string& filename, 203 const DescriptorProto& message_type, Value value); 204 bool AddExtension(const std::string& filename, 205 const FieldDescriptorProto& field, Value value); 206 207 Value FindFile(const std::string& filename); 208 Value FindSymbol(const std::string& name); 209 Value FindExtension(const std::string& containing_type, int field_number); 210 bool FindAllExtensionNumbers(const std::string& containing_type, 211 std::vector<int>* output); 212 void FindAllFileNames(std::vector<std::string>* output); 213 214 private: 215 std::map<std::string, Value> by_name_; 216 std::map<std::string, Value> by_symbol_; 217 std::map<std::pair<std::string, int>, Value> by_extension_; 218 219 // Invariant: The by_symbol_ map does not contain any symbols which are 220 // prefixes of other symbols in the map. For example, "foo.bar" is a 221 // prefix of "foo.bar.baz" (but is not a prefix of "foo.barbaz"). 222 // 223 // This invariant is important because it means that given a symbol name, 224 // we can find a key in the map which is a prefix of the symbol in O(lg n) 225 // time, and we know that there is at most one such key. 226 // 227 // The prefix lookup algorithm works like so: 228 // 1) Find the last key in the map which is less than or equal to the 229 // search key. 230 // 2) If the found key is a prefix of the search key, then return it. 231 // Otherwise, there is no match. 232 // 233 // I am sure this algorithm has been described elsewhere, but since I 234 // wasn't able to find it quickly I will instead prove that it works 235 // myself. The key to the algorithm is that if a match exists, step (1) 236 // will find it. Proof: 237 // 1) Define the "search key" to be the key we are looking for, the "found 238 // key" to be the key found in step (1), and the "match key" to be the 239 // key which actually matches the search key (i.e. the key we're trying 240 // to find). 241 // 2) The found key must be less than or equal to the search key by 242 // definition. 243 // 3) The match key must also be less than or equal to the search key 244 // (because it is a prefix). 245 // 4) The match key cannot be greater than the found key, because if it 246 // were, then step (1) of the algorithm would have returned the match 247 // key instead (since it finds the *greatest* key which is less than or 248 // equal to the search key). 249 // 5) Therefore, the found key must be between the match key and the search 250 // key, inclusive. 251 // 6) Since the search key must be a sub-symbol of the match key, if it is 252 // not equal to the match key, then search_key[match_key.size()] must 253 // be '.'. 254 // 7) Since '.' sorts before any other character that is valid in a symbol 255 // name, then if the found key is not equal to the match key, then 256 // found_key[match_key.size()] must also be '.', because any other value 257 // would make it sort after the search key. 258 // 8) Therefore, if the found key is not equal to the match key, then the 259 // found key must be a sub-symbol of the match key. However, this would 260 // contradict our map invariant which says that no symbol in the map is 261 // a sub-symbol of any other. 262 // 9) Therefore, the found key must match the match key. 263 // 264 // The above proof assumes the match key exists. In the case that the 265 // match key does not exist, then step (1) will return some other symbol. 266 // That symbol cannot be a super-symbol of the search key since if it were, 267 // then it would be a match, and we're assuming the match key doesn't exist. 268 // Therefore, step 2 will correctly return no match. 269 270 // Find the last entry in the by_symbol_ map whose key is less than or 271 // equal to the given name. 272 typename std::map<std::string, Value>::iterator FindLastLessOrEqual( 273 const std::string& name); 274 275 // True if either the arguments are equal or super_symbol identifies a 276 // parent symbol of sub_symbol (e.g. "foo.bar" is a parent of 277 // "foo.bar.baz", but not a parent of "foo.barbaz"). 278 bool IsSubSymbol(const std::string& sub_symbol, 279 const std::string& super_symbol); 280 281 // Returns true if and only if all characters in the name are alphanumerics, 282 // underscores, or periods. 283 bool ValidateSymbolName(const std::string& name); 284 }; 285 286 DescriptorIndex<const FileDescriptorProto*> index_; 287 std::vector<const FileDescriptorProto*> files_to_delete_; 288 289 // If file is non-NULL, copy it into *output and return true, otherwise 290 // return false. 291 bool MaybeCopy(const FileDescriptorProto* file, FileDescriptorProto* output); 292 293 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SimpleDescriptorDatabase); 294 }; 295 296 // Very similar to SimpleDescriptorDatabase, but stores all the descriptors 297 // as raw bytes and generally tries to use as little memory as possible. 298 // 299 // The same caveats regarding FindFileContainingExtension() apply as with 300 // SimpleDescriptorDatabase. 301 class PROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase { 302 public: 303 EncodedDescriptorDatabase(); 304 ~EncodedDescriptorDatabase() override; 305 306 // Adds the FileDescriptorProto to the database. The descriptor is provided 307 // in encoded form. The database does not make a copy of the bytes, nor 308 // does it take ownership; it's up to the caller to make sure the bytes 309 // remain valid for the life of the database. Returns false and logs an error 310 // if the bytes are not a valid FileDescriptorProto or if the file conflicted 311 // with a file already in the database. 312 bool Add(const void* encoded_file_descriptor, int size); 313 314 // Like Add(), but makes a copy of the data, so that the caller does not 315 // need to keep it around. 316 bool AddCopy(const void* encoded_file_descriptor, int size); 317 318 // Like FindFileContainingSymbol but returns only the name of the file. 319 bool FindNameOfFileContainingSymbol(const std::string& symbol_name, 320 std::string* output); 321 322 // implements DescriptorDatabase ----------------------------------- 323 bool FindFileByName(const std::string& filename, 324 FileDescriptorProto* output) override; 325 bool FindFileContainingSymbol(const std::string& symbol_name, 326 FileDescriptorProto* output) override; 327 bool FindFileContainingExtension(const std::string& containing_type, 328 int field_number, 329 FileDescriptorProto* output) override; 330 bool FindAllExtensionNumbers(const std::string& extendee_type, 331 std::vector<int>* output) override; 332 bool FindAllFileNames(std::vector<std::string>* output) override; 333 334 private: 335 SimpleDescriptorDatabase::DescriptorIndex<std::pair<const void*, int> > 336 index_; 337 std::vector<void*> files_to_delete_; 338 339 // If encoded_file.first is non-NULL, parse the data into *output and return 340 // true, otherwise return false. 341 bool MaybeParse(std::pair<const void*, int> encoded_file, 342 FileDescriptorProto* output); 343 344 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EncodedDescriptorDatabase); 345 }; 346 347 // A DescriptorDatabase that fetches files from a given pool. 348 class PROTOBUF_EXPORT DescriptorPoolDatabase : public DescriptorDatabase { 349 public: 350 explicit DescriptorPoolDatabase(const DescriptorPool& pool); 351 ~DescriptorPoolDatabase() override; 352 353 // implements DescriptorDatabase ----------------------------------- 354 bool FindFileByName(const std::string& filename, 355 FileDescriptorProto* output) override; 356 bool FindFileContainingSymbol(const std::string& symbol_name, 357 FileDescriptorProto* output) override; 358 bool FindFileContainingExtension(const std::string& containing_type, 359 int field_number, 360 FileDescriptorProto* output) override; 361 bool FindAllExtensionNumbers(const std::string& extendee_type, 362 std::vector<int>* output) override; 363 364 private: 365 const DescriptorPool& pool_; 366 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorPoolDatabase); 367 }; 368 369 // A DescriptorDatabase that wraps two or more others. It first searches the 370 // first database and, if that fails, tries the second, and so on. 371 class PROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase { 372 public: 373 // Merge just two databases. The sources remain property of the caller. 374 MergedDescriptorDatabase(DescriptorDatabase* source1, 375 DescriptorDatabase* source2); 376 // Merge more than two databases. The sources remain property of the caller. 377 // The vector may be deleted after the constructor returns but the 378 // DescriptorDatabases need to stick around. 379 explicit MergedDescriptorDatabase( 380 const std::vector<DescriptorDatabase*>& sources); 381 ~MergedDescriptorDatabase() override; 382 383 // implements DescriptorDatabase ----------------------------------- 384 bool FindFileByName(const std::string& filename, 385 FileDescriptorProto* output) override; 386 bool FindFileContainingSymbol(const std::string& symbol_name, 387 FileDescriptorProto* output) override; 388 bool FindFileContainingExtension(const std::string& containing_type, 389 int field_number, 390 FileDescriptorProto* output) override; 391 // Merges the results of calling all databases. Returns true iff any 392 // of the databases returned true. 393 bool FindAllExtensionNumbers(const std::string& extendee_type, 394 std::vector<int>* output) override; 395 396 397 private: 398 std::vector<DescriptorDatabase*> sources_; 399 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MergedDescriptorDatabase); 400 }; 401 402 } // namespace protobuf 403 } // namespace google 404 405 #include <google/protobuf/port_undef.inc> 406 407 #endif // GOOGLE_PROTOBUF_DESCRIPTOR_DATABASE_H__ 408