You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

descriptor_database.h 19 kB

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