CompilationDatabase.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- CompilationDatabase.h ------------------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file provides an interface and multiple implementations for
  15. // CompilationDatabases.
  16. //
  17. // While C++ refactoring and analysis tools are not compilers, and thus
  18. // don't run as part of the build system, they need the exact information
  19. // of a build in order to be able to correctly understand the C++ code of
  20. // the project. This information is provided via the CompilationDatabase
  21. // interface.
  22. //
  23. // To create a CompilationDatabase from a build directory one can call
  24. // CompilationDatabase::loadFromDirectory(), which deduces the correct
  25. // compilation database from the root of the build tree.
  26. //
  27. // See the concrete subclasses of CompilationDatabase for currently supported
  28. // formats.
  29. //
  30. //===----------------------------------------------------------------------===//
  31. #ifndef LLVM_CLANG_TOOLING_COMPILATIONDATABASE_H
  32. #define LLVM_CLANG_TOOLING_COMPILATIONDATABASE_H
  33. #include "clang/Basic/LLVM.h"
  34. #include "llvm/ADT/ArrayRef.h"
  35. #include "llvm/ADT/StringRef.h"
  36. #include "llvm/ADT/Twine.h"
  37. #include "llvm/Support/VirtualFileSystem.h"
  38. #include <memory>
  39. #include <string>
  40. #include <utility>
  41. #include <vector>
  42. namespace clang {
  43. namespace tooling {
  44. /// Specifies the working directory and command of a compilation.
  45. struct CompileCommand {
  46. CompileCommand() = default;
  47. CompileCommand(const Twine &Directory, const Twine &Filename,
  48. std::vector<std::string> CommandLine, const Twine &Output)
  49. : Directory(Directory.str()), Filename(Filename.str()),
  50. CommandLine(std::move(CommandLine)), Output(Output.str()) {}
  51. /// The working directory the command was executed from.
  52. std::string Directory;
  53. /// The source file associated with the command.
  54. std::string Filename;
  55. /// The command line that was executed.
  56. std::vector<std::string> CommandLine;
  57. /// The output file associated with the command.
  58. std::string Output;
  59. /// If this compile command was guessed rather than read from an authoritative
  60. /// source, a short human-readable explanation.
  61. /// e.g. "inferred from foo/bar.h".
  62. std::string Heuristic;
  63. friend bool operator==(const CompileCommand &LHS, const CompileCommand &RHS) {
  64. return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
  65. LHS.CommandLine == RHS.CommandLine && LHS.Output == RHS.Output &&
  66. LHS.Heuristic == RHS.Heuristic;
  67. }
  68. friend bool operator!=(const CompileCommand &LHS, const CompileCommand &RHS) {
  69. return !(LHS == RHS);
  70. }
  71. };
  72. /// Interface for compilation databases.
  73. ///
  74. /// A compilation database allows the user to retrieve compile command lines
  75. /// for the files in a project.
  76. ///
  77. /// Many implementations are enumerable, allowing all command lines to be
  78. /// retrieved. These can be used to run clang tools over a subset of the files
  79. /// in a project.
  80. class CompilationDatabase {
  81. public:
  82. virtual ~CompilationDatabase();
  83. /// Loads a compilation database from a build directory.
  84. ///
  85. /// Looks at the specified 'BuildDirectory' and creates a compilation database
  86. /// that allows to query compile commands for source files in the
  87. /// corresponding source tree.
  88. ///
  89. /// Returns NULL and sets ErrorMessage if we were not able to build up a
  90. /// compilation database for the build directory.
  91. ///
  92. /// FIXME: Currently only supports JSON compilation databases, which
  93. /// are named 'compile_commands.json' in the given directory. Extend this
  94. /// for other build types (like ninja build files).
  95. static std::unique_ptr<CompilationDatabase>
  96. loadFromDirectory(StringRef BuildDirectory, std::string &ErrorMessage);
  97. /// Tries to detect a compilation database location and load it.
  98. ///
  99. /// Looks for a compilation database in all parent paths of file 'SourceFile'
  100. /// by calling loadFromDirectory.
  101. static std::unique_ptr<CompilationDatabase>
  102. autoDetectFromSource(StringRef SourceFile, std::string &ErrorMessage);
  103. /// Tries to detect a compilation database location and load it.
  104. ///
  105. /// Looks for a compilation database in directory 'SourceDir' and all
  106. /// its parent paths by calling loadFromDirectory.
  107. static std::unique_ptr<CompilationDatabase>
  108. autoDetectFromDirectory(StringRef SourceDir, std::string &ErrorMessage);
  109. /// Returns all compile commands in which the specified file was
  110. /// compiled.
  111. ///
  112. /// This includes compile commands that span multiple source files.
  113. /// For example, consider a project with the following compilations:
  114. /// $ clang++ -o test a.cc b.cc t.cc
  115. /// $ clang++ -o production a.cc b.cc -DPRODUCTION
  116. /// A compilation database representing the project would return both command
  117. /// lines for a.cc and b.cc and only the first command line for t.cc.
  118. virtual std::vector<CompileCommand> getCompileCommands(
  119. StringRef FilePath) const = 0;
  120. /// Returns the list of all files available in the compilation database.
  121. ///
  122. /// By default, returns nothing. Implementations should override this if they
  123. /// can enumerate their source files.
  124. virtual std::vector<std::string> getAllFiles() const { return {}; }
  125. /// Returns all compile commands for all the files in the compilation
  126. /// database.
  127. ///
  128. /// FIXME: Add a layer in Tooling that provides an interface to run a tool
  129. /// over all files in a compilation database. Not all build systems have the
  130. /// ability to provide a feasible implementation for \c getAllCompileCommands.
  131. ///
  132. /// By default, this is implemented in terms of getAllFiles() and
  133. /// getCompileCommands(). Subclasses may override this for efficiency.
  134. virtual std::vector<CompileCommand> getAllCompileCommands() const;
  135. };
  136. /// A compilation database that returns a single compile command line.
  137. ///
  138. /// Useful when we want a tool to behave more like a compiler invocation.
  139. /// This compilation database is not enumerable: getAllFiles() returns {}.
  140. class FixedCompilationDatabase : public CompilationDatabase {
  141. public:
  142. /// Creates a FixedCompilationDatabase from the arguments after "--".
  143. ///
  144. /// Parses the given command line for "--". If "--" is found, the rest of
  145. /// the arguments will make up the command line in the returned
  146. /// FixedCompilationDatabase.
  147. /// The arguments after "--" must not include positional parameters or the
  148. /// argv[0] of the tool. Those will be added by the FixedCompilationDatabase
  149. /// when a CompileCommand is requested. The argv[0] of the returned command
  150. /// line will be "clang-tool".
  151. ///
  152. /// Returns NULL in case "--" is not found.
  153. ///
  154. /// The argument list is meant to be compatible with normal llvm command line
  155. /// parsing in main methods.
  156. /// int main(int argc, char **argv) {
  157. /// std::unique_ptr<FixedCompilationDatabase> Compilations(
  158. /// FixedCompilationDatabase::loadFromCommandLine(argc, argv));
  159. /// cl::ParseCommandLineOptions(argc, argv);
  160. /// ...
  161. /// }
  162. ///
  163. /// \param Argc The number of command line arguments - will be changed to
  164. /// the number of arguments before "--", if "--" was found in the argument
  165. /// list.
  166. /// \param Argv Points to the command line arguments.
  167. /// \param ErrorMsg Contains error text if the function returns null pointer.
  168. /// \param Directory The base directory used in the FixedCompilationDatabase.
  169. static std::unique_ptr<FixedCompilationDatabase>
  170. loadFromCommandLine(int &Argc, const char *const *Argv, std::string &ErrorMsg,
  171. const Twine &Directory = ".");
  172. /// Reads flags from the given file, one-per-line.
  173. /// Returns nullptr and sets ErrorMessage if we can't read the file.
  174. static std::unique_ptr<FixedCompilationDatabase>
  175. loadFromFile(StringRef Path, std::string &ErrorMsg);
  176. /// Reads flags from the given buffer, one-per-line.
  177. /// Directory is the command CWD, typically the parent of compile_flags.txt.
  178. static std::unique_ptr<FixedCompilationDatabase>
  179. loadFromBuffer(StringRef Directory, StringRef Data, std::string &ErrorMsg);
  180. /// Constructs a compilation data base from a specified directory
  181. /// and command line.
  182. FixedCompilationDatabase(const Twine &Directory,
  183. ArrayRef<std::string> CommandLine);
  184. /// Returns the given compile command.
  185. ///
  186. /// Will always return a vector with one entry that contains the directory
  187. /// and command line specified at construction with "clang-tool" as argv[0]
  188. /// and 'FilePath' as positional argument.
  189. std::vector<CompileCommand>
  190. getCompileCommands(StringRef FilePath) const override;
  191. private:
  192. /// This is built up to contain a single entry vector to be returned from
  193. /// getCompileCommands after adding the positional argument.
  194. std::vector<CompileCommand> CompileCommands;
  195. };
  196. /// Transforms a compile command so that it applies the same configuration to
  197. /// a different file. Most args are left intact, but tweaks may be needed
  198. /// to certain flags (-x, -std etc).
  199. ///
  200. /// The output command will always end in {"--", Filename}.
  201. tooling::CompileCommand transferCompileCommand(tooling::CompileCommand,
  202. StringRef Filename);
  203. /// Returns a wrapped CompilationDatabase that defers to the provided one,
  204. /// but getCompileCommands() will infer commands for unknown files.
  205. /// The return value of getAllFiles() or getAllCompileCommands() is unchanged.
  206. /// See InterpolatingCompilationDatabase.cpp for details on heuristics.
  207. std::unique_ptr<CompilationDatabase>
  208. inferMissingCompileCommands(std::unique_ptr<CompilationDatabase>);
  209. /// Returns a wrapped CompilationDatabase that will add -target and -mode flags
  210. /// to commandline when they can be deduced from argv[0] of commandline returned
  211. /// by underlying database.
  212. std::unique_ptr<CompilationDatabase>
  213. inferTargetAndDriverMode(std::unique_ptr<CompilationDatabase> Base);
  214. /// Returns a wrapped CompilationDatabase that will expand all rsp(response)
  215. /// files on commandline returned by underlying database.
  216. std::unique_ptr<CompilationDatabase>
  217. expandResponseFiles(std::unique_ptr<CompilationDatabase> Base,
  218. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS);
  219. } // namespace tooling
  220. } // namespace clang
  221. #endif // LLVM_CLANG_TOOLING_COMPILATIONDATABASE_H
  222. #ifdef __GNUC__
  223. #pragma GCC diagnostic pop
  224. #endif