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"
49 } // end namespace driver
51 class CompilerInvocation;
57 /// \brief Interface to process a clang::CompilerInvocation.
59 /// If your tool is based on FrontendAction, you should be deriving from
60 /// FrontendActionFactory instead.
63 virtual ~ToolAction();
65 /// \brief Perform an action for an invocation.
66 virtual bool runInvocation(clang::CompilerInvocation *Invocation,
68 DiagnosticConsumer *DiagConsumer) = 0;
71 /// \brief Interface to generate clang::FrontendActions.
73 /// Having a factory interface allows, for example, a new FrontendAction to be
74 /// created for each translation unit processed by ClangTool. This class is
75 /// also a ToolAction which uses the FrontendActions created by create() to
76 /// process each translation unit.
77 class FrontendActionFactory : public ToolAction {
79 virtual ~FrontendActionFactory();
81 /// \brief Invokes the compiler with a FrontendAction created by create().
82 bool runInvocation(clang::CompilerInvocation *Invocation, FileManager *Files,
83 DiagnosticConsumer *DiagConsumer);
85 /// \brief Returns a new clang::FrontendAction.
87 /// The caller takes ownership of the returned action.
88 virtual clang::FrontendAction *create() = 0;
91 /// \brief Returns a new FrontendActionFactory for a given type.
93 /// T must derive from clang::FrontendAction.
96 /// FrontendActionFactory *Factory =
97 /// newFrontendActionFactory<clang::SyntaxOnlyAction>();
99 FrontendActionFactory *newFrontendActionFactory();
101 /// \brief Callbacks called before and after each source file processed by a
102 /// FrontendAction created by the FrontedActionFactory returned by \c
103 /// newFrontendActionFactory.
104 class SourceFileCallbacks {
106 virtual ~SourceFileCallbacks() {}
108 /// \brief Called before a source file is processed by a FrontEndAction.
109 /// \see clang::FrontendAction::BeginSourceFileAction
110 virtual bool handleBeginSource(CompilerInstance &CI, StringRef Filename) {
114 /// \brief Called after a source file is processed by a FrontendAction.
115 /// \see clang::FrontendAction::EndSourceFileAction
116 virtual void handleEndSource() {}
119 /// \brief Returns a new FrontendActionFactory for any type that provides an
120 /// implementation of newASTConsumer().
122 /// FactoryT must implement: ASTConsumer *newASTConsumer().
125 /// struct ProvidesASTConsumers {
126 /// clang::ASTConsumer *newASTConsumer();
128 /// FrontendActionFactory *FactoryAdapter =
129 /// newFrontendActionFactory(&Factory);
130 template <typename FactoryT>
131 inline FrontendActionFactory *newFrontendActionFactory(
132 FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks = NULL);
134 /// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag.
136 /// \param ToolAction The action to run over the code.
137 /// \param Code C++ code.
138 /// \param FileName The file name which 'Code' will be mapped as.
140 /// \return - True if 'ToolAction' was successfully executed.
141 bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
142 const Twine &FileName = "input.cc");
144 /// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag and
145 /// with additional other flags.
147 /// \param ToolAction The action to run over the code.
148 /// \param Code C++ code.
149 /// \param Args Additional flags to pass on.
150 /// \param FileName The file name which 'Code' will be mapped as.
152 /// \return - True if 'ToolAction' was successfully executed.
153 bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
154 const std::vector<std::string> &Args,
155 const Twine &FileName = "input.cc");
157 /// \brief Builds an AST for 'Code'.
159 /// \param Code C++ code.
160 /// \param FileName The file name which 'Code' will be mapped as.
162 /// \return The resulting AST or null if an error occurred.
163 ASTUnit *buildASTFromCode(const Twine &Code,
164 const Twine &FileName = "input.cc");
166 /// \brief Builds an AST for 'Code' with additional flags.
168 /// \param Code C++ code.
169 /// \param Args Additional flags to pass on.
170 /// \param FileName The file name which 'Code' will be mapped as.
172 /// \return The resulting AST or null if an error occurred.
173 ASTUnit *buildASTFromCodeWithArgs(const Twine &Code,
174 const std::vector<std::string> &Args,
175 const Twine &FileName = "input.cc");
177 /// \brief Utility to run a FrontendAction in a single clang invocation.
178 class ToolInvocation {
180 /// \brief Create a tool invocation.
182 /// \param CommandLine The command line arguments to clang. Note that clang
183 /// uses its binary name (CommandLine[0]) to locate its builtin headers.
184 /// Callers have to ensure that they are installed in a compatible location
185 /// (see clang driver implementation) or mapped in via mapVirtualFile.
186 /// \param FAction The action to be executed. Class takes ownership.
187 /// \param Files The FileManager used for the execution. Class does not take
189 ToolInvocation(ArrayRef<std::string> CommandLine, FrontendAction *FAction,
192 /// \brief Create a tool invocation.
194 /// \param CommandLine The command line arguments to clang.
195 /// \param Action The action to be executed.
196 /// \param Files The FileManager used for the execution.
197 ToolInvocation(ArrayRef<std::string> CommandLine, ToolAction *Action,
202 /// \brief Set a \c DiagnosticConsumer to use during parsing.
203 void setDiagnosticConsumer(DiagnosticConsumer *DiagConsumer);
205 /// \brief Map a virtual file to be used while running the tool.
207 /// \param FilePath The path at which the content will be mapped.
208 /// \param Content A null terminated buffer of the file's content.
209 void mapVirtualFile(StringRef FilePath, StringRef Content);
211 /// \brief Run the clang invocation.
213 /// \returns True if there were no errors during execution.
217 void addFileMappingsTo(SourceManager &SourceManager);
219 bool runInvocation(const char *BinaryName,
220 clang::driver::Compilation *Compilation,
221 clang::CompilerInvocation *Invocation);
223 std::vector<std::string> CommandLine;
227 // Maps <file name> -> <file content>.
228 llvm::StringMap<StringRef> MappedFileContents;
229 DiagnosticConsumer *DiagConsumer;
232 /// \brief Utility to run a FrontendAction over a set of files.
234 /// This class is written to be usable for command line utilities.
235 /// By default the class uses ClangSyntaxOnlyAdjuster to modify
236 /// command line arguments before the arguments are used to run
237 /// a frontend action. One could install an additional command line
238 /// arguments adjuster by calling the appendArgumentsAdjuster() method.
241 /// \brief Constructs a clang tool to run over a list of files.
243 /// \param Compilations The CompilationDatabase which contains the compile
244 /// command lines for the given source paths.
245 /// \param SourcePaths The source files to run over. If a source files is
246 /// not found in Compilations, it is skipped.
247 ClangTool(const CompilationDatabase &Compilations,
248 ArrayRef<std::string> SourcePaths);
250 virtual ~ClangTool() { clearArgumentsAdjusters(); }
252 /// \brief Set a \c DiagnosticConsumer to use during parsing.
253 void setDiagnosticConsumer(DiagnosticConsumer *DiagConsumer);
255 /// \brief Map a virtual file to be used while running the tool.
257 /// \param FilePath The path at which the content will be mapped.
258 /// \param Content A null terminated buffer of the file's content.
259 void mapVirtualFile(StringRef FilePath, StringRef Content);
261 /// \brief Install command line arguments adjuster.
263 /// \param Adjuster Command line arguments adjuster.
265 /// FIXME: Function is deprecated. Use (clear/append)ArgumentsAdjuster instead.
266 /// Remove it once all callers are gone.
267 void setArgumentsAdjuster(ArgumentsAdjuster *Adjuster);
269 /// \brief Append a command line arguments adjuster to the adjuster chain.
271 /// \param Adjuster An argument adjuster, which will be run on the output of
272 /// previous argument adjusters.
273 void appendArgumentsAdjuster(ArgumentsAdjuster *Adjuster);
275 /// \brief Clear the command line arguments adjuster chain.
276 void clearArgumentsAdjusters();
278 /// Runs an action over all files specified in the command line.
280 /// \param Action Tool action.
281 int run(ToolAction *Action);
283 /// \brief Create an AST for each file specified in the command line and
284 /// append them to ASTs.
285 int buildASTs(std::vector<ASTUnit *> &ASTs);
287 /// \brief Returns the file manager used in the tool.
289 /// The file manager is shared between all translation units.
290 FileManager &getFiles() { return *Files; }
293 // We store compile commands as pair (file name, compile command).
294 std::vector< std::pair<std::string, CompileCommand> > CompileCommands;
296 llvm::IntrusiveRefCntPtr<FileManager> Files;
297 // Contains a list of pairs (<file name>, <file content>).
298 std::vector< std::pair<StringRef, StringRef> > MappedFileContents;
300 SmallVector<ArgumentsAdjuster *, 2> ArgsAdjusters;
302 DiagnosticConsumer *DiagConsumer;
305 template <typename T>
306 FrontendActionFactory *newFrontendActionFactory() {
307 class SimpleFrontendActionFactory : public FrontendActionFactory {
309 virtual clang::FrontendAction *create() { return new T; }
312 return new SimpleFrontendActionFactory;
315 template <typename FactoryT>
316 inline FrontendActionFactory *newFrontendActionFactory(
317 FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks) {
318 class FrontendActionFactoryAdapter : public FrontendActionFactory {
320 explicit FrontendActionFactoryAdapter(FactoryT *ConsumerFactory,
321 SourceFileCallbacks *Callbacks)
322 : ConsumerFactory(ConsumerFactory), Callbacks(Callbacks) {}
324 virtual clang::FrontendAction *create() {
325 return new ConsumerFactoryAdaptor(ConsumerFactory, Callbacks);
329 class ConsumerFactoryAdaptor : public clang::ASTFrontendAction {
331 ConsumerFactoryAdaptor(FactoryT *ConsumerFactory,
332 SourceFileCallbacks *Callbacks)
333 : ConsumerFactory(ConsumerFactory), Callbacks(Callbacks) {}
335 clang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &,
337 return ConsumerFactory->newASTConsumer();
341 virtual bool BeginSourceFileAction(CompilerInstance &CI,
342 StringRef Filename) LLVM_OVERRIDE {
343 if (!clang::ASTFrontendAction::BeginSourceFileAction(CI, Filename))
345 if (Callbacks != NULL)
346 return Callbacks->handleBeginSource(CI, Filename);
349 virtual void EndSourceFileAction() LLVM_OVERRIDE {
350 if (Callbacks != NULL)
351 Callbacks->handleEndSource();
352 clang::ASTFrontendAction::EndSourceFileAction();
356 FactoryT *ConsumerFactory;
357 SourceFileCallbacks *Callbacks;
359 FactoryT *ConsumerFactory;
360 SourceFileCallbacks *Callbacks;
363 return new FrontendActionFactoryAdapter(ConsumerFactory, Callbacks);
366 /// \brief Returns the absolute path of \c File, by prepending it with
367 /// the current directory if \c File is not absolute.
369 /// Otherwise returns \c File.
370 /// If 'File' starts with "./", the returned path will not contain the "./".
371 /// Otherwise, the returned path will contain the literal path-concatenation of
372 /// the current directory and \c File.
374 /// The difference to llvm::sys::fs::make_absolute is the canonicalization this
375 /// does by removing "./" and computing native paths.
377 /// \param File Either an absolute or relative path.
378 std::string getAbsolutePath(StringRef File);
380 } // end namespace tooling
381 } // end namespace clang
383 #endif // LLVM_CLANG_TOOLING_TOOLING_H