• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- CompilationDatabase.h - --------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file provides an interface and multiple implementations for
11 //  CompilationDatabases.
12 //
13 //  While C++ refactoring and analysis tools are not compilers, and thus
14 //  don't run as part of the build system, they need the exact information
15 //  of a build in order to be able to correctly understand the C++ code of
16 //  the project. This information is provided via the CompilationDatabase
17 //  interface.
18 //
19 //  To create a CompilationDatabase from a build directory one can call
20 //  CompilationDatabase::loadFromDirectory(), which deduces the correct
21 //  compilation database from the root of the build tree.
22 //
23 //  See the concrete subclasses of CompilationDatabase for currently supported
24 //  formats.
25 //
26 //===----------------------------------------------------------------------===//
27 
28 #ifndef LLVM_CLANG_TOOLING_COMPILATIONDATABASE_H
29 #define LLVM_CLANG_TOOLING_COMPILATIONDATABASE_H
30 
31 #include "clang/Basic/LLVM.h"
32 #include "llvm/ADT/ArrayRef.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/ADT/Twine.h"
35 #include <memory>
36 #include <string>
37 #include <vector>
38 
39 namespace clang {
40 namespace tooling {
41 
42 /// \brief Specifies the working directory and command of a compilation.
43 struct CompileCommand {
CompileCommandCompileCommand44   CompileCommand() {}
CompileCommandCompileCommand45   CompileCommand(Twine Directory, Twine Filename,
46                  std::vector<std::string> CommandLine)
47       : Directory(Directory.str()),
48         Filename(Filename.str()),
49         CommandLine(std::move(CommandLine)) {}
50 
51   /// \brief The working directory the command was executed from.
52   std::string Directory;
53 
54   /// The source file associated with the command.
55   std::string Filename;
56 
57   /// \brief The command line that was executed.
58   std::vector<std::string> CommandLine;
59 
60   /// \brief An optional mapping from each file's path to its content for all
61   /// files needed for the compilation that are not available via the file
62   /// system.
63   ///
64   /// Note that a tool implementation is required to fall back to the file
65   /// system if a source file is not provided in the mapped sources, as
66   /// compilation databases will usually not provide all files in mapped sources
67   /// for performance reasons.
68   std::vector<std::pair<std::string, std::string> > MappedSources;
69 };
70 
71 /// \brief Interface for compilation databases.
72 ///
73 /// A compilation database allows the user to retrieve all compile command lines
74 /// that a specified file is compiled with in a project.
75 /// The retrieved compile command lines can be used to run clang tools over
76 /// a subset of the files in a project.
77 class CompilationDatabase {
78 public:
79   virtual ~CompilationDatabase();
80 
81   /// \brief Loads a compilation database from a build directory.
82   ///
83   /// Looks at the specified 'BuildDirectory' and creates a compilation database
84   /// that allows to query compile commands for source files in the
85   /// corresponding source tree.
86   ///
87   /// Returns NULL and sets ErrorMessage if we were not able to build up a
88   /// compilation database for the build directory.
89   ///
90   /// FIXME: Currently only supports JSON compilation databases, which
91   /// are named 'compile_commands.json' in the given directory. Extend this
92   /// for other build types (like ninja build files).
93   static std::unique_ptr<CompilationDatabase>
94   loadFromDirectory(StringRef BuildDirectory, std::string &ErrorMessage);
95 
96   /// \brief Tries to detect a compilation database location and load it.
97   ///
98   /// Looks for a compilation database in all parent paths of file 'SourceFile'
99   /// by calling loadFromDirectory.
100   static std::unique_ptr<CompilationDatabase>
101   autoDetectFromSource(StringRef SourceFile, std::string &ErrorMessage);
102 
103   /// \brief 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 
110   /// \brief Returns all compile commands in which the specified file was
111   /// compiled.
112   ///
113   /// This includes compile comamnds that span multiple source files.
114   /// For example, consider a project with the following compilations:
115   /// $ clang++ -o test a.cc b.cc t.cc
116   /// $ clang++ -o production a.cc b.cc -DPRODUCTION
117   /// A compilation database representing the project would return both command
118   /// lines for a.cc and b.cc and only the first command line for t.cc.
119   virtual std::vector<CompileCommand> getCompileCommands(
120     StringRef FilePath) const = 0;
121 
122   /// \brief Returns the list of all files available in the compilation database.
123   virtual std::vector<std::string> getAllFiles() const = 0;
124 
125   /// \brief 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   virtual std::vector<CompileCommand> getAllCompileCommands() const = 0;
132 };
133 
134 /// \brief Interface for compilation database plugins.
135 ///
136 /// A compilation database plugin allows the user to register custom compilation
137 /// databases that are picked up as compilation database if the corresponding
138 /// library is linked in. To register a plugin, declare a static variable like:
139 ///
140 /// \code
141 /// static CompilationDatabasePluginRegistry::Add<MyDatabasePlugin>
142 /// X("my-compilation-database", "Reads my own compilation database");
143 /// \endcode
144 class CompilationDatabasePlugin {
145 public:
146   virtual ~CompilationDatabasePlugin();
147 
148   /// \brief Loads a compilation database from a build directory.
149   ///
150   /// \see CompilationDatabase::loadFromDirectory().
151   virtual std::unique_ptr<CompilationDatabase>
152   loadFromDirectory(StringRef Directory, std::string &ErrorMessage) = 0;
153 };
154 
155 /// \brief A compilation database that returns a single compile command line.
156 ///
157 /// Useful when we want a tool to behave more like a compiler invocation.
158 class FixedCompilationDatabase : public CompilationDatabase {
159 public:
160   /// \brief Creates a FixedCompilationDatabase from the arguments after "--".
161   ///
162   /// Parses the given command line for "--". If "--" is found, the rest of
163   /// the arguments will make up the command line in the returned
164   /// FixedCompilationDatabase.
165   /// The arguments after "--" must not include positional parameters or the
166   /// argv[0] of the tool. Those will be added by the FixedCompilationDatabase
167   /// when a CompileCommand is requested. The argv[0] of the returned command
168   /// line will be "clang-tool".
169   ///
170   /// Returns NULL in case "--" is not found.
171   ///
172   /// The argument list is meant to be compatible with normal llvm command line
173   /// parsing in main methods.
174   /// int main(int argc, char **argv) {
175   ///   std::unique_ptr<FixedCompilationDatabase> Compilations(
176   ///     FixedCompilationDatabase::loadFromCommandLine(argc, argv));
177   ///   cl::ParseCommandLineOptions(argc, argv);
178   ///   ...
179   /// }
180   ///
181   /// \param Argc The number of command line arguments - will be changed to
182   /// the number of arguments before "--", if "--" was found in the argument
183   /// list.
184   /// \param Argv Points to the command line arguments.
185   /// \param Directory The base directory used in the FixedCompilationDatabase.
186   static FixedCompilationDatabase *loadFromCommandLine(int &Argc,
187                                                        const char *const *Argv,
188                                                        Twine Directory = ".");
189 
190   /// \brief Constructs a compilation data base from a specified directory
191   /// and command line.
192   FixedCompilationDatabase(Twine Directory, ArrayRef<std::string> CommandLine);
193 
194   /// \brief Returns the given compile command.
195   ///
196   /// Will always return a vector with one entry that contains the directory
197   /// and command line specified at construction with "clang-tool" as argv[0]
198   /// and 'FilePath' as positional argument.
199   std::vector<CompileCommand>
200   getCompileCommands(StringRef FilePath) const override;
201 
202   /// \brief Returns the list of all files available in the compilation database.
203   ///
204   /// Note: This is always an empty list for the fixed compilation database.
205   std::vector<std::string> getAllFiles() const override;
206 
207   /// \brief Returns all compile commands for all the files in the compilation
208   /// database.
209   ///
210   /// Note: This is always an empty list for the fixed compilation database.
211   std::vector<CompileCommand> getAllCompileCommands() const override;
212 
213 private:
214   /// This is built up to contain a single entry vector to be returned from
215   /// getCompileCommands after adding the positional argument.
216   std::vector<CompileCommand> CompileCommands;
217 };
218 
219 } // end namespace tooling
220 } // end namespace clang
221 
222 #endif
223