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