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.

importer.h 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. // This file is the public interface to the .proto file parser.
  35. #ifndef GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__
  36. #define GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__
  37. #include <set>
  38. #include <string>
  39. #include <utility>
  40. #include <vector>
  41. #include <google/protobuf/compiler/parser.h>
  42. #include <google/protobuf/descriptor.h>
  43. #include <google/protobuf/descriptor_database.h>
  44. // Must be included last.
  45. #include <google/protobuf/port_def.inc>
  46. namespace google {
  47. namespace protobuf {
  48. namespace io {
  49. class ZeroCopyInputStream;
  50. }
  51. namespace compiler {
  52. // Defined in this file.
  53. class Importer;
  54. class MultiFileErrorCollector;
  55. class SourceTree;
  56. class DiskSourceTree;
  57. // TODO(kenton): Move all SourceTree stuff to a separate file?
  58. // An implementation of DescriptorDatabase which loads files from a SourceTree
  59. // and parses them.
  60. //
  61. // Note: This class is not thread-safe since it maintains a table of source
  62. // code locations for error reporting. However, when a DescriptorPool wraps
  63. // a DescriptorDatabase, it uses mutex locking to make sure only one method
  64. // of the database is called at a time, even if the DescriptorPool is used
  65. // from multiple threads. Therefore, there is only a problem if you create
  66. // multiple DescriptorPools wrapping the same SourceTreeDescriptorDatabase
  67. // and use them from multiple threads.
  68. //
  69. // Note: This class does not implement FindFileContainingSymbol() or
  70. // FindFileContainingExtension(); these will always return false.
  71. class PROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabase {
  72. public:
  73. SourceTreeDescriptorDatabase(SourceTree* source_tree);
  74. // If non-NULL, fallback_database will be checked if a file doesn't exist in
  75. // the specified source_tree.
  76. SourceTreeDescriptorDatabase(SourceTree* source_tree,
  77. DescriptorDatabase* fallback_database);
  78. ~SourceTreeDescriptorDatabase() override;
  79. // Instructs the SourceTreeDescriptorDatabase to report any parse errors
  80. // to the given MultiFileErrorCollector. This should be called before
  81. // parsing. error_collector must remain valid until either this method
  82. // is called again or the SourceTreeDescriptorDatabase is destroyed.
  83. void RecordErrorsTo(MultiFileErrorCollector* error_collector) {
  84. error_collector_ = error_collector;
  85. }
  86. // Gets a DescriptorPool::ErrorCollector which records errors to the
  87. // MultiFileErrorCollector specified with RecordErrorsTo(). This collector
  88. // has the ability to determine exact line and column numbers of errors
  89. // from the information given to it by the DescriptorPool.
  90. DescriptorPool::ErrorCollector* GetValidationErrorCollector() {
  91. using_validation_error_collector_ = true;
  92. return &validation_error_collector_;
  93. }
  94. // implements DescriptorDatabase -----------------------------------
  95. bool FindFileByName(const std::string& filename,
  96. FileDescriptorProto* output) override;
  97. bool FindFileContainingSymbol(const std::string& symbol_name,
  98. FileDescriptorProto* output) override;
  99. bool FindFileContainingExtension(const std::string& containing_type,
  100. int field_number,
  101. FileDescriptorProto* output) override;
  102. private:
  103. class SingleFileErrorCollector;
  104. SourceTree* source_tree_;
  105. DescriptorDatabase* fallback_database_;
  106. MultiFileErrorCollector* error_collector_;
  107. class PROTOBUF_EXPORT ValidationErrorCollector
  108. : public DescriptorPool::ErrorCollector {
  109. public:
  110. ValidationErrorCollector(SourceTreeDescriptorDatabase* owner);
  111. ~ValidationErrorCollector() override;
  112. // implements ErrorCollector ---------------------------------------
  113. void AddError(const std::string& filename, const std::string& element_name,
  114. const Message* descriptor, ErrorLocation location,
  115. const std::string& message) override;
  116. void AddWarning(const std::string& filename,
  117. const std::string& element_name, const Message* descriptor,
  118. ErrorLocation location,
  119. const std::string& message) override;
  120. private:
  121. SourceTreeDescriptorDatabase* owner_;
  122. };
  123. friend class ValidationErrorCollector;
  124. bool using_validation_error_collector_;
  125. SourceLocationTable source_locations_;
  126. ValidationErrorCollector validation_error_collector_;
  127. };
  128. // Simple interface for parsing .proto files. This wraps the process
  129. // of opening the file, parsing it with a Parser, recursively parsing all its
  130. // imports, and then cross-linking the results to produce a FileDescriptor.
  131. //
  132. // This is really just a thin wrapper around SourceTreeDescriptorDatabase.
  133. // You may find that SourceTreeDescriptorDatabase is more flexible.
  134. //
  135. // TODO(kenton): I feel like this class is not well-named.
  136. class PROTOBUF_EXPORT Importer {
  137. public:
  138. Importer(SourceTree* source_tree, MultiFileErrorCollector* error_collector);
  139. ~Importer();
  140. // Import the given file and build a FileDescriptor representing it. If
  141. // the file is already in the DescriptorPool, the existing FileDescriptor
  142. // will be returned. The FileDescriptor is property of the DescriptorPool,
  143. // and will remain valid until it is destroyed. If any errors occur, they
  144. // will be reported using the error collector and Import() will return NULL.
  145. //
  146. // A particular Importer object will only report errors for a particular
  147. // file once. All future attempts to import the same file will return NULL
  148. // without reporting any errors. The idea is that you might want to import
  149. // a lot of files without seeing the same errors over and over again. If
  150. // you want to see errors for the same files repeatedly, you can use a
  151. // separate Importer object to import each one (but use the same
  152. // DescriptorPool so that they can be cross-linked).
  153. const FileDescriptor* Import(const std::string& filename);
  154. // The DescriptorPool in which all imported FileDescriptors and their
  155. // contents are stored.
  156. inline const DescriptorPool* pool() const { return &pool_; }
  157. void AddUnusedImportTrackFile(const std::string& file_name,
  158. bool is_error = false);
  159. void ClearUnusedImportTrackFiles();
  160. private:
  161. SourceTreeDescriptorDatabase database_;
  162. DescriptorPool pool_;
  163. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Importer);
  164. };
  165. // If the importer encounters problems while trying to import the proto files,
  166. // it reports them to a MultiFileErrorCollector.
  167. class PROTOBUF_EXPORT MultiFileErrorCollector {
  168. public:
  169. inline MultiFileErrorCollector() {}
  170. virtual ~MultiFileErrorCollector();
  171. // Line and column numbers are zero-based. A line number of -1 indicates
  172. // an error with the entire file (e.g. "not found").
  173. virtual void AddError(const std::string& filename, int line, int column,
  174. const std::string& message) = 0;
  175. virtual void AddWarning(const std::string& /* filename */, int /* line */,
  176. int /* column */, const std::string& /* message */) {}
  177. private:
  178. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MultiFileErrorCollector);
  179. };
  180. // Abstract interface which represents a directory tree containing proto files.
  181. // Used by the default implementation of Importer to resolve import statements
  182. // Most users will probably want to use the DiskSourceTree implementation,
  183. // below.
  184. class PROTOBUF_EXPORT SourceTree {
  185. public:
  186. inline SourceTree() {}
  187. virtual ~SourceTree();
  188. // Open the given file and return a stream that reads it, or NULL if not
  189. // found. The caller takes ownership of the returned object. The filename
  190. // must be a path relative to the root of the source tree and must not
  191. // contain "." or ".." components.
  192. virtual io::ZeroCopyInputStream* Open(const std::string& filename) = 0;
  193. // If Open() returns NULL, calling this method immediately will return an
  194. // description of the error.
  195. // Subclasses should implement this method and return a meaningful value for
  196. // better error reporting.
  197. // TODO(xiaofeng): change this to a pure virtual function.
  198. virtual std::string GetLastErrorMessage();
  199. private:
  200. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SourceTree);
  201. };
  202. // An implementation of SourceTree which loads files from locations on disk.
  203. // Multiple mappings can be set up to map locations in the DiskSourceTree to
  204. // locations in the physical filesystem.
  205. class PROTOBUF_EXPORT DiskSourceTree : public SourceTree {
  206. public:
  207. DiskSourceTree();
  208. ~DiskSourceTree() override;
  209. // Map a path on disk to a location in the SourceTree. The path may be
  210. // either a file or a directory. If it is a directory, the entire tree
  211. // under it will be mapped to the given virtual location. To map a directory
  212. // to the root of the source tree, pass an empty string for virtual_path.
  213. //
  214. // If multiple mapped paths apply when opening a file, they will be searched
  215. // in order. For example, if you do:
  216. // MapPath("bar", "foo/bar");
  217. // MapPath("", "baz");
  218. // and then you do:
  219. // Open("bar/qux");
  220. // the DiskSourceTree will first try to open foo/bar/qux, then baz/bar/qux,
  221. // returning the first one that opens successfully.
  222. //
  223. // disk_path may be an absolute path or relative to the current directory,
  224. // just like a path you'd pass to open().
  225. void MapPath(const std::string& virtual_path, const std::string& disk_path);
  226. // Return type for DiskFileToVirtualFile().
  227. enum DiskFileToVirtualFileResult {
  228. SUCCESS,
  229. SHADOWED,
  230. CANNOT_OPEN,
  231. NO_MAPPING
  232. };
  233. // Given a path to a file on disk, find a virtual path mapping to that
  234. // file. The first mapping created with MapPath() whose disk_path contains
  235. // the filename is used. However, that virtual path may not actually be
  236. // usable to open the given file. Possible return values are:
  237. // * SUCCESS: The mapping was found. *virtual_file is filled in so that
  238. // calling Open(*virtual_file) will open the file named by disk_file.
  239. // * SHADOWED: A mapping was found, but using Open() to open this virtual
  240. // path will end up returning some different file. This is because some
  241. // other mapping with a higher precedence also matches this virtual path
  242. // and maps it to a different file that exists on disk. *virtual_file
  243. // is filled in as it would be in the SUCCESS case. *shadowing_disk_file
  244. // is filled in with the disk path of the file which would be opened if
  245. // you were to call Open(*virtual_file).
  246. // * CANNOT_OPEN: The mapping was found and was not shadowed, but the
  247. // file specified cannot be opened. When this value is returned,
  248. // errno will indicate the reason the file cannot be opened. *virtual_file
  249. // will be set to the virtual path as in the SUCCESS case, even though
  250. // it is not useful.
  251. // * NO_MAPPING: Indicates that no mapping was found which contains this
  252. // file.
  253. DiskFileToVirtualFileResult DiskFileToVirtualFile(
  254. const std::string& disk_file, std::string* virtual_file,
  255. std::string* shadowing_disk_file);
  256. // Given a virtual path, find the path to the file on disk.
  257. // Return true and update disk_file with the on-disk path if the file exists.
  258. // Return false and leave disk_file untouched if the file doesn't exist.
  259. bool VirtualFileToDiskFile(const std::string& virtual_file,
  260. std::string* disk_file);
  261. // implements SourceTree -------------------------------------------
  262. io::ZeroCopyInputStream* Open(const std::string& filename) override;
  263. std::string GetLastErrorMessage() override;
  264. private:
  265. struct Mapping {
  266. std::string virtual_path;
  267. std::string disk_path;
  268. inline Mapping(const std::string& virtual_path_param,
  269. const std::string& disk_path_param)
  270. : virtual_path(virtual_path_param), disk_path(disk_path_param) {}
  271. };
  272. std::vector<Mapping> mappings_;
  273. std::string last_error_message_;
  274. // Like Open(), but returns the on-disk path in disk_file if disk_file is
  275. // non-NULL and the file could be successfully opened.
  276. io::ZeroCopyInputStream* OpenVirtualFile(const std::string& virtual_file,
  277. std::string* disk_file);
  278. // Like Open() but given the actual on-disk path.
  279. io::ZeroCopyInputStream* OpenDiskFile(const std::string& filename);
  280. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DiskSourceTree);
  281. };
  282. } // namespace compiler
  283. } // namespace protobuf
  284. } // namespace google
  285. #include <google/protobuf/port_undef.inc>
  286. #endif // GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__