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/Basic/Diagnostic.h"
34 #include "clang/Basic/FileManager.h"
35 #include "clang/Basic/LLVM.h"
36 #include "clang/Driver/Util.h"
37 #include "clang/Frontend/FrontendAction.h"
38 #include "clang/Tooling/ArgumentsAdjusters.h"
39 #include "clang/Tooling/CompilationDatabase.h"
40 #include "llvm/ADT/StringMap.h"
41 #include "llvm/ADT/Twine.h"
50 } // end namespace driver
52 class CompilerInvocation;
58 /// \brief Interface to process a clang::CompilerInvocation.
60 /// If your tool is based on FrontendAction, you should be deriving from
61 /// FrontendActionFactory instead.
64 virtual ~ToolAction();
66 /// \brief Perform an action for an invocation.
67 virtual bool runInvocation(clang::CompilerInvocation *Invocation,
69 DiagnosticConsumer *DiagConsumer) = 0;
72 /// \brief Interface to generate clang::FrontendActions.
74 /// Having a factory interface allows, for example, a new FrontendAction to be
75 /// created for each translation unit processed by ClangTool. This class is
76 /// also a ToolAction which uses the FrontendActions created by create() to
77 /// process each translation unit.
78 class FrontendActionFactory : public ToolAction {
80 virtual ~FrontendActionFactory();
82 /// \brief Invokes the compiler with a FrontendAction created by create().
83 bool runInvocation(clang::CompilerInvocation *Invocation, FileManager *Files,
84 DiagnosticConsumer *DiagConsumer) override;
86 /// \brief Returns a new clang::FrontendAction.
88 /// The caller takes ownership of the returned action.
89 virtual clang::FrontendAction *create() = 0;
92 /// \brief Returns a new FrontendActionFactory for a given type.
94 /// T must derive from clang::FrontendAction.
97 /// FrontendActionFactory *Factory =
98 /// newFrontendActionFactory<clang::SyntaxOnlyAction>();
100 std::unique_ptr<FrontendActionFactory> newFrontendActionFactory();
102 /// \brief Callbacks called before and after each source file processed by a
103 /// FrontendAction created by the FrontedActionFactory returned by \c
104 /// newFrontendActionFactory.
105 class SourceFileCallbacks {
107 virtual ~SourceFileCallbacks() {}
109 /// \brief Called before a source file is processed by a FrontEndAction.
110 /// \see clang::FrontendAction::BeginSourceFileAction
111 virtual bool handleBeginSource(CompilerInstance &CI, StringRef Filename) {
115 /// \brief Called after a source file is processed by a FrontendAction.
116 /// \see clang::FrontendAction::EndSourceFileAction
117 virtual void handleEndSource() {}
120 /// \brief Returns a new FrontendActionFactory for any type that provides an
121 /// implementation of newASTConsumer().
123 /// FactoryT must implement: ASTConsumer *newASTConsumer().
126 /// struct ProvidesASTConsumers {
127 /// clang::ASTConsumer *newASTConsumer();
129 /// std::unique_ptr<FrontendActionFactory> FactoryAdapter(
130 /// newFrontendActionFactory(&Factory));
131 template <typename FactoryT>
132 inline std::unique_ptr<FrontendActionFactory> newFrontendActionFactory(
133 FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks = nullptr);
135 /// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag.
137 /// \param ToolAction The action to run over the code.
138 /// \param Code C++ code.
139 /// \param FileName The file name which 'Code' will be mapped as.
141 /// \return - True if 'ToolAction' was successfully executed.
142 bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
143 const Twine &FileName = "input.cc");
145 /// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag and
146 /// with additional other flags.
148 /// \param ToolAction The action to run over the code.
149 /// \param Code C++ code.
150 /// \param Args Additional flags to pass on.
151 /// \param FileName The file name which 'Code' will be mapped as.
153 /// \return - True if 'ToolAction' was successfully executed.
154 bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
155 const std::vector<std::string> &Args,
156 const Twine &FileName = "input.cc");
158 /// \brief Builds an AST for 'Code'.
160 /// \param Code C++ code.
161 /// \param FileName The file name which 'Code' will be mapped as.
163 /// \return The resulting AST or null if an error occurred.
164 std::unique_ptr<ASTUnit> buildASTFromCode(const Twine &Code,
165 const Twine &FileName = "input.cc");
167 /// \brief Builds an AST for 'Code' with additional flags.
169 /// \param Code C++ code.
170 /// \param Args Additional flags to pass on.
171 /// \param FileName The file name which 'Code' will be mapped as.
173 /// \return The resulting AST or null if an error occurred.
174 std::unique_ptr<ASTUnit>
175 buildASTFromCodeWithArgs(const Twine &Code,
176 const std::vector<std::string> &Args,
177 const Twine &FileName = "input.cc");
179 /// \brief Utility to run a FrontendAction in a single clang invocation.
180 class ToolInvocation {
182 /// \brief Create a tool invocation.
184 /// \param CommandLine The command line arguments to clang. Note that clang
185 /// uses its binary name (CommandLine[0]) to locate its builtin headers.
186 /// Callers have to ensure that they are installed in a compatible location
187 /// (see clang driver implementation) or mapped in via mapVirtualFile.
188 /// \param FAction The action to be executed. Class takes ownership.
189 /// \param Files The FileManager used for the execution. Class does not take
191 ToolInvocation(std::vector<std::string> CommandLine, FrontendAction *FAction,
194 /// \brief Create a tool invocation.
196 /// \param CommandLine The command line arguments to clang.
197 /// \param Action The action to be executed.
198 /// \param Files The FileManager used for the execution.
199 ToolInvocation(std::vector<std::string> CommandLine, ToolAction *Action,
204 /// \brief Set a \c DiagnosticConsumer to use during parsing.
205 void setDiagnosticConsumer(DiagnosticConsumer *DiagConsumer);
207 /// \brief Map a virtual file to be used while running the tool.
209 /// \param FilePath The path at which the content will be mapped.
210 /// \param Content A null terminated buffer of the file's content.
211 void mapVirtualFile(StringRef FilePath, StringRef Content);
213 /// \brief Run the clang invocation.
215 /// \returns True if there were no errors during execution.
219 void addFileMappingsTo(SourceManager &SourceManager);
221 bool runInvocation(const char *BinaryName,
222 clang::driver::Compilation *Compilation,
223 clang::CompilerInvocation *Invocation);
225 std::vector<std::string> CommandLine;
229 // Maps <file name> -> <file content>.
230 llvm::StringMap<StringRef> MappedFileContents;
231 DiagnosticConsumer *DiagConsumer;
234 /// \brief Utility to run a FrontendAction over a set of files.
236 /// This class is written to be usable for command line utilities.
237 /// By default the class uses ClangSyntaxOnlyAdjuster to modify
238 /// command line arguments before the arguments are used to run
239 /// a frontend action. One could install an additional command line
240 /// arguments adjuster by calling the appendArgumentsAdjuster() method.
243 /// \brief Constructs a clang tool to run over a list of files.
245 /// \param Compilations The CompilationDatabase which contains the compile
246 /// command lines for the given source paths.
247 /// \param SourcePaths The source files to run over. If a source files is
248 /// not found in Compilations, it is skipped.
249 ClangTool(const CompilationDatabase &Compilations,
250 ArrayRef<std::string> SourcePaths);
252 virtual ~ClangTool() { clearArgumentsAdjusters(); }
254 /// \brief Set a \c DiagnosticConsumer to use during parsing.
255 void setDiagnosticConsumer(DiagnosticConsumer *DiagConsumer);
257 /// \brief Map a virtual file to be used while running the tool.
259 /// \param FilePath The path at which the content will be mapped.
260 /// \param Content A null terminated buffer of the file's content.
261 void mapVirtualFile(StringRef FilePath, StringRef Content);
263 /// \brief Install command line arguments adjuster.
265 /// \param Adjuster Command line arguments adjuster.
267 /// FIXME: Function is deprecated. Use (clear/append)ArgumentsAdjuster instead.
268 /// Remove it once all callers are gone.
269 void setArgumentsAdjuster(ArgumentsAdjuster *Adjuster);
271 /// \brief Append a command line arguments adjuster to the adjuster chain.
273 /// \param Adjuster An argument adjuster, which will be run on the output of
274 /// previous argument adjusters.
275 void appendArgumentsAdjuster(ArgumentsAdjuster *Adjuster);
277 /// \brief Clear the command line arguments adjuster chain.
278 void clearArgumentsAdjusters();
280 /// Runs an action over all files specified in the command line.
282 /// \param Action Tool action.
283 int run(ToolAction *Action);
285 /// \brief Create an AST for each file specified in the command line and
286 /// append them to ASTs.
287 int buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs);
289 /// \brief Returns the file manager used in the tool.
291 /// The file manager is shared between all translation units.
292 FileManager &getFiles() { return *Files; }
295 // We store compile commands as pair (file name, compile command).
296 std::vector< std::pair<std::string, CompileCommand> > CompileCommands;
298 llvm::IntrusiveRefCntPtr<FileManager> Files;
299 // Contains a list of pairs (<file name>, <file content>).
300 std::vector< std::pair<StringRef, StringRef> > MappedFileContents;
302 SmallVector<ArgumentsAdjuster *, 2> ArgsAdjusters;
304 DiagnosticConsumer *DiagConsumer;
307 template <typename T>
308 std::unique_ptr<FrontendActionFactory> newFrontendActionFactory() {
309 class SimpleFrontendActionFactory : public FrontendActionFactory {
311 clang::FrontendAction *create() override { return new T; }
314 return std::unique_ptr<FrontendActionFactory>(
315 new SimpleFrontendActionFactory);
318 template <typename FactoryT>
319 inline std::unique_ptr<FrontendActionFactory> newFrontendActionFactory(
320 FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks) {
321 class FrontendActionFactoryAdapter : public FrontendActionFactory {
323 explicit FrontendActionFactoryAdapter(FactoryT *ConsumerFactory,
324 SourceFileCallbacks *Callbacks)
325 : ConsumerFactory(ConsumerFactory), Callbacks(Callbacks) {}
327 clang::FrontendAction *create() override {
328 return new ConsumerFactoryAdaptor(ConsumerFactory, Callbacks);
332 class ConsumerFactoryAdaptor : public clang::ASTFrontendAction {
334 ConsumerFactoryAdaptor(FactoryT *ConsumerFactory,
335 SourceFileCallbacks *Callbacks)
336 : ConsumerFactory(ConsumerFactory), Callbacks(Callbacks) {}
338 clang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &,
339 StringRef) override {
340 return ConsumerFactory->newASTConsumer();
344 bool BeginSourceFileAction(CompilerInstance &CI,
345 StringRef Filename) override {
346 if (!clang::ASTFrontendAction::BeginSourceFileAction(CI, Filename))
349 return Callbacks->handleBeginSource(CI, Filename);
352 void EndSourceFileAction() override {
354 Callbacks->handleEndSource();
355 clang::ASTFrontendAction::EndSourceFileAction();
359 FactoryT *ConsumerFactory;
360 SourceFileCallbacks *Callbacks;
362 FactoryT *ConsumerFactory;
363 SourceFileCallbacks *Callbacks;
366 return std::unique_ptr<FrontendActionFactory>(
367 new FrontendActionFactoryAdapter(ConsumerFactory, Callbacks));
370 /// \brief Returns the absolute path of \c File, by prepending it with
371 /// the current directory if \c File is not absolute.
373 /// Otherwise returns \c File.
374 /// If 'File' starts with "./", the returned path will not contain the "./".
375 /// Otherwise, the returned path will contain the literal path-concatenation of
376 /// the current directory and \c File.
378 /// The difference to llvm::sys::fs::make_absolute is the canonicalization this
379 /// does by removing "./" and computing native paths.
381 /// \param File Either an absolute or relative path.
382 std::string getAbsolutePath(StringRef File);
384 } // end namespace tooling
385 } // end namespace clang
387 #endif // LLVM_CLANG_TOOLING_TOOLING_H