descriptor_database.h 18 KB

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