1 //===--- Tooling.h - Framework for standalone Clang tools -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements functions to run clang tools standalone instead
11 // of running them as a plugin.
13 // A ClangTool is initialized with a CompilationDatabase and a set of files
14 // to run over. The tool will then run a user-specified FrontendAction over
15 // all TUs in which the given files are compiled.
17 // It is also possible to run a FrontendAction over a snippet of code by
18 // calling runToolOnCode, which is useful for unit testing.
20 // Applications that need more fine grained control over how to run
21 // multiple FrontendActions over code can use ToolInvocation.
24 // - running clang -fsyntax-only over source code from an editor to get
26 // - running match/replace tools over C++ code
28 //===----------------------------------------------------------------------===//
30 #ifndef LLVM_CLANG_TOOLING_TOOLING_H
31 #define LLVM_CLANG_TOOLING_TOOLING_H
33 #include "clang/AST/ASTConsumer.h"
34 #include "clang/Frontend/PCHContainerOperations.h"
35 #include "clang/Basic/Diagnostic.h"
36 #include "clang/Basic/FileManager.h"
37 #include "clang/Basic/LLVM.h"
38 #include "clang/Driver/Util.h"
39 #include "clang/Frontend/FrontendAction.h"
40 #include "clang/Lex/ModuleLoader.h"
41 #include "clang/Tooling/ArgumentsAdjusters.h"
42 #include "clang/Tooling/CompilationDatabase.h"
43 #include "llvm/ADT/StringMap.h"
44 #include "llvm/ADT/Twine.h"
45 #include "llvm/Option/Option.h"
54 } // end namespace driver
56 class CompilerInvocation;
62 /// \brief Interface to process a clang::CompilerInvocation.
64 /// If your tool is based on FrontendAction, you should be deriving from
65 /// FrontendActionFactory instead.
68 virtual ~ToolAction();
70 /// \brief Perform an action for an invocation.
72 runInvocation(std::shared_ptr<clang::CompilerInvocation> Invocation,
74 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
75 DiagnosticConsumer *DiagConsumer) = 0;
78 /// \brief Interface to generate clang::FrontendActions.
80 /// Having a factory interface allows, for example, a new FrontendAction to be
81 /// created for each translation unit processed by ClangTool. This class is
82 /// also a ToolAction which uses the FrontendActions created by create() to
83 /// process each translation unit.
84 class FrontendActionFactory : public ToolAction {
86 ~FrontendActionFactory() override;
88 /// \brief Invokes the compiler with a FrontendAction created by create().
89 bool runInvocation(std::shared_ptr<clang::CompilerInvocation> Invocation,
91 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
92 DiagnosticConsumer *DiagConsumer) override;
94 /// \brief Returns a new clang::FrontendAction.
96 /// The caller takes ownership of the returned action.
97 virtual clang::FrontendAction *create() = 0;
100 /// \brief Returns a new FrontendActionFactory for a given type.
102 /// T must derive from clang::FrontendAction.
105 /// FrontendActionFactory *Factory =
106 /// newFrontendActionFactory<clang::SyntaxOnlyAction>();
107 template <typename T>
108 std::unique_ptr<FrontendActionFactory> newFrontendActionFactory();
110 /// \brief Callbacks called before and after each source file processed by a
111 /// FrontendAction created by the FrontedActionFactory returned by \c
112 /// newFrontendActionFactory.
113 class SourceFileCallbacks {
115 virtual ~SourceFileCallbacks() {}
117 /// \brief Called before a source file is processed by a FrontEndAction.
118 /// \see clang::FrontendAction::BeginSourceFileAction
119 virtual bool handleBeginSource(CompilerInstance &CI) {
123 /// \brief Called after a source file is processed by a FrontendAction.
124 /// \see clang::FrontendAction::EndSourceFileAction
125 virtual void handleEndSource() {}
128 /// \brief Returns a new FrontendActionFactory for any type that provides an
129 /// implementation of newASTConsumer().
131 /// FactoryT must implement: ASTConsumer *newASTConsumer().
134 /// struct ProvidesASTConsumers {
135 /// clang::ASTConsumer *newASTConsumer();
137 /// std::unique_ptr<FrontendActionFactory> FactoryAdapter(
138 /// newFrontendActionFactory(&Factory));
139 template <typename FactoryT>
140 inline std::unique_ptr<FrontendActionFactory> newFrontendActionFactory(
141 FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks = nullptr);
143 /// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag.
145 /// \param ToolAction The action to run over the code.
146 /// \param Code C++ code.
147 /// \param FileName The file name which 'Code' will be mapped as.
148 /// \param PCHContainerOps The PCHContainerOperations for loading and creating
151 /// \return - True if 'ToolAction' was successfully executed.
152 bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
153 const Twine &FileName = "input.cc",
154 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
155 std::make_shared<PCHContainerOperations>());
157 /// The first part of the pair is the filename, the second part the
159 typedef std::vector<std::pair<std::string, std::string>> FileContentMappings;
161 /// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag and
162 /// with additional other flags.
164 /// \param ToolAction The action to run over the code.
165 /// \param Code C++ code.
166 /// \param Args Additional flags to pass on.
167 /// \param FileName The file name which 'Code' will be mapped as.
168 /// \param ToolName The name of the binary running the tool. Standard library
169 /// header paths will be resolved relative to this.
170 /// \param PCHContainerOps The PCHContainerOperations for loading and creating
173 /// \return - True if 'ToolAction' was successfully executed.
174 bool runToolOnCodeWithArgs(
175 clang::FrontendAction *ToolAction, const Twine &Code,
176 const std::vector<std::string> &Args, const Twine &FileName = "input.cc",
177 const Twine &ToolName = "clang-tool",
178 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
179 std::make_shared<PCHContainerOperations>(),
180 const FileContentMappings &VirtualMappedFiles = FileContentMappings());
182 /// \brief Builds an AST for 'Code'.
184 /// \param Code C++ code.
185 /// \param FileName The file name which 'Code' will be mapped as.
186 /// \param PCHContainerOps The PCHContainerOperations for loading and creating
189 /// \return The resulting AST or null if an error occurred.
190 std::unique_ptr<ASTUnit>
191 buildASTFromCode(const Twine &Code, const Twine &FileName = "input.cc",
192 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
193 std::make_shared<PCHContainerOperations>());
195 /// \brief Builds an AST for 'Code' with additional flags.
197 /// \param Code C++ code.
198 /// \param Args Additional flags to pass on.
199 /// \param FileName The file name which 'Code' will be mapped as.
200 /// \param ToolName The name of the binary running the tool. Standard library
201 /// header paths will be resolved relative to this.
202 /// \param PCHContainerOps The PCHContainerOperations for loading and creating
205 /// \return The resulting AST or null if an error occurred.
206 std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
207 const Twine &Code, const std::vector<std::string> &Args,
208 const Twine &FileName = "input.cc", const Twine &ToolName = "clang-tool",
209 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
210 std::make_shared<PCHContainerOperations>());
212 /// \brief Utility to run a FrontendAction in a single clang invocation.
213 class ToolInvocation {
215 /// \brief Create a tool invocation.
217 /// \param CommandLine The command line arguments to clang. Note that clang
218 /// uses its binary name (CommandLine[0]) to locate its builtin headers.
219 /// Callers have to ensure that they are installed in a compatible location
220 /// (see clang driver implementation) or mapped in via mapVirtualFile.
221 /// \param FAction The action to be executed. Class takes ownership.
222 /// \param Files The FileManager used for the execution. Class does not take
224 /// \param PCHContainerOps The PCHContainerOperations for loading and creating
226 ToolInvocation(std::vector<std::string> CommandLine, FrontendAction *FAction,
228 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
229 std::make_shared<PCHContainerOperations>());
231 /// \brief Create a tool invocation.
233 /// \param CommandLine The command line arguments to clang.
234 /// \param Action The action to be executed.
235 /// \param Files The FileManager used for the execution.
236 /// \param PCHContainerOps The PCHContainerOperations for loading and creating
238 ToolInvocation(std::vector<std::string> CommandLine, ToolAction *Action,
240 std::shared_ptr<PCHContainerOperations> PCHContainerOps);
244 /// \brief Set a \c DiagnosticConsumer to use during parsing.
245 void setDiagnosticConsumer(DiagnosticConsumer *DiagConsumer) {
246 this->DiagConsumer = DiagConsumer;
249 /// \brief Map a virtual file to be used while running the tool.
251 /// \param FilePath The path at which the content will be mapped.
252 /// \param Content A null terminated buffer of the file's content.
253 // FIXME: remove this when all users have migrated!
254 void mapVirtualFile(StringRef FilePath, StringRef Content);
256 /// \brief Run the clang invocation.
258 /// \returns True if there were no errors during execution.
262 void addFileMappingsTo(SourceManager &SourceManager);
264 bool runInvocation(const char *BinaryName,
265 clang::driver::Compilation *Compilation,
266 std::shared_ptr<clang::CompilerInvocation> Invocation,
267 std::shared_ptr<PCHContainerOperations> PCHContainerOps);
269 std::vector<std::string> CommandLine;
273 std::shared_ptr<PCHContainerOperations> PCHContainerOps;
274 // Maps <file name> -> <file content>.
275 llvm::StringMap<StringRef> MappedFileContents;
276 DiagnosticConsumer *DiagConsumer;
279 /// \brief Utility to run a FrontendAction over a set of files.
281 /// This class is written to be usable for command line utilities.
282 /// By default the class uses ClangSyntaxOnlyAdjuster to modify
283 /// command line arguments before the arguments are used to run
284 /// a frontend action. One could install an additional command line
285 /// arguments adjuster by calling the appendArgumentsAdjuster() method.
288 /// \brief Constructs a clang tool to run over a list of files.
290 /// \param Compilations The CompilationDatabase which contains the compile
291 /// command lines for the given source paths.
292 /// \param SourcePaths The source files to run over. If a source files is
293 /// not found in Compilations, it is skipped.
294 /// \param PCHContainerOps The PCHContainerOperations for loading and creating
296 ClangTool(const CompilationDatabase &Compilations,
297 ArrayRef<std::string> SourcePaths,
298 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
299 std::make_shared<PCHContainerOperations>());
303 /// \brief Set a \c DiagnosticConsumer to use during parsing.
304 void setDiagnosticConsumer(DiagnosticConsumer *DiagConsumer) {
305 this->DiagConsumer = DiagConsumer;
308 /// \brief Map a virtual file to be used while running the tool.
310 /// \param FilePath The path at which the content will be mapped.
311 /// \param Content A null terminated buffer of the file's content.
312 void mapVirtualFile(StringRef FilePath, StringRef Content);
314 /// \brief Append a command line arguments adjuster to the adjuster chain.
316 /// \param Adjuster An argument adjuster, which will be run on the output of
317 /// previous argument adjusters.
318 void appendArgumentsAdjuster(ArgumentsAdjuster Adjuster);
320 /// \brief Clear the command line arguments adjuster chain.
321 void clearArgumentsAdjusters();
323 /// Runs an action over all files specified in the command line.
325 /// \param Action Tool action.
326 int run(ToolAction *Action);
328 /// \brief Create an AST for each file specified in the command line and
329 /// append them to ASTs.
330 int buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs);
332 /// \brief Returns the file manager used in the tool.
334 /// The file manager is shared between all translation units.
335 FileManager &getFiles() { return *Files; }
338 const CompilationDatabase &Compilations;
339 std::vector<std::string> SourcePaths;
340 std::shared_ptr<PCHContainerOperations> PCHContainerOps;
342 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem;
343 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem;
344 llvm::IntrusiveRefCntPtr<FileManager> Files;
345 // Contains a list of pairs (<file name>, <file content>).
346 std::vector< std::pair<StringRef, StringRef> > MappedFileContents;
347 llvm::StringSet<> SeenWorkingDirectories;
349 ArgumentsAdjuster ArgsAdjuster;
351 DiagnosticConsumer *DiagConsumer;
354 template <typename T>
355 std::unique_ptr<FrontendActionFactory> newFrontendActionFactory() {
356 class SimpleFrontendActionFactory : public FrontendActionFactory {
358 clang::FrontendAction *create() override { return new T; }
361 return std::unique_ptr<FrontendActionFactory>(
362 new SimpleFrontendActionFactory);
365 template <typename FactoryT>
366 inline std::unique_ptr<FrontendActionFactory> newFrontendActionFactory(
367 FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks) {
368 class FrontendActionFactoryAdapter : public FrontendActionFactory {
370 explicit FrontendActionFactoryAdapter(FactoryT *ConsumerFactory,
371 SourceFileCallbacks *Callbacks)
372 : ConsumerFactory(ConsumerFactory), Callbacks(Callbacks) {}
374 clang::FrontendAction *create() override {
375 return new ConsumerFactoryAdaptor(ConsumerFactory, Callbacks);
379 class ConsumerFactoryAdaptor : public clang::ASTFrontendAction {
381 ConsumerFactoryAdaptor(FactoryT *ConsumerFactory,
382 SourceFileCallbacks *Callbacks)
383 : ConsumerFactory(ConsumerFactory), Callbacks(Callbacks) {}
385 std::unique_ptr<clang::ASTConsumer>
386 CreateASTConsumer(clang::CompilerInstance &, StringRef) override {
387 return ConsumerFactory->newASTConsumer();
391 bool BeginSourceFileAction(CompilerInstance &CI) override {
392 if (!clang::ASTFrontendAction::BeginSourceFileAction(CI))
395 return Callbacks->handleBeginSource(CI);
398 void EndSourceFileAction() override {
400 Callbacks->handleEndSource();
401 clang::ASTFrontendAction::EndSourceFileAction();
405 FactoryT *ConsumerFactory;
406 SourceFileCallbacks *Callbacks;
408 FactoryT *ConsumerFactory;
409 SourceFileCallbacks *Callbacks;
412 return std::unique_ptr<FrontendActionFactory>(
413 new FrontendActionFactoryAdapter(ConsumerFactory, Callbacks));
416 /// \brief Returns the absolute path of \c File, by prepending it with
417 /// the current directory if \c File is not absolute.
419 /// Otherwise returns \c File.
420 /// If 'File' starts with "./", the returned path will not contain the "./".
421 /// Otherwise, the returned path will contain the literal path-concatenation of
422 /// the current directory and \c File.
424 /// The difference to llvm::sys::fs::make_absolute is the canonicalization this
425 /// does by removing "./" and computing native paths.
427 /// \param File Either an absolute or relative path.
428 std::string getAbsolutePath(StringRef File);
430 /// \brief Changes CommandLine to contain implicit flags that would have been
431 /// defined had the compiler driver been invoked through the path InvokedAs.
433 /// For example, when called with \c InvokedAs set to `i686-linux-android-g++`,
434 /// the arguments '-target', 'i686-linux-android`, `--driver-mode=g++` will
435 /// be inserted after the first argument in \c CommandLine.
437 /// This function will not add new `-target` or `--driver-mode` flags if they
438 /// are already present in `CommandLine` (even if they have different settings
439 /// than would have been inserted).
441 /// \pre `llvm::InitializeAllTargets()` has been called.
443 /// \param CommandLine the command line used to invoke the compiler driver or
444 /// Clang tool, including the path to the executable as \c CommandLine[0].
445 /// \param InvokedAs the path to the driver used to infer implicit flags.
447 /// \note This will not set \c CommandLine[0] to \c InvokedAs. The tooling
448 /// infrastructure expects that CommandLine[0] is a tool path relative to which
449 /// the builtin headers can be found.
450 void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
451 StringRef InvokedAs);
453 /// \brief Creates a \c CompilerInvocation.
454 clang::CompilerInvocation *newInvocation(
455 clang::DiagnosticsEngine *Diagnostics,
456 const llvm::opt::ArgStringList &CC1Args);
458 } // end namespace tooling
459 } // end namespace clang
461 #endif // LLVM_CLANG_TOOLING_TOOLING_H