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 "llvm/ADT/StringMap.h"
34 #include "llvm/ADT/Twine.h"
35 #include "clang/Basic/FileManager.h"
36 #include "clang/Basic/LLVM.h"
37 #include "clang/Driver/Util.h"
38 #include "clang/Frontend/FrontendAction.h"
39 #include "clang/Tooling/ArgumentsAdjusters.h"
40 #include "clang/Tooling/CompilationDatabase.h"
48 } // end namespace driver
50 class CompilerInvocation;
56 /// \brief Interface to generate clang::FrontendActions.
57 class FrontendActionFactory {
59 virtual ~FrontendActionFactory();
61 /// \brief Returns a new clang::FrontendAction.
63 /// The caller takes ownership of the returned action.
64 virtual clang::FrontendAction *create() = 0;
67 /// \brief Returns a new FrontendActionFactory for a given type.
69 /// T must extend clang::FrontendAction.
72 /// FrontendActionFactory *Factory =
73 /// newFrontendActionFactory<clang::SyntaxOnlyAction>();
75 FrontendActionFactory *newFrontendActionFactory();
77 /// \brief Returns a new FrontendActionFactory for any type that provides an
78 /// implementation of newASTConsumer().
80 /// FactoryT must implement: ASTConsumer *newASTConsumer().
83 /// struct ProvidesASTConsumers {
84 /// clang::ASTConsumer *newASTConsumer();
86 /// FrontendActionFactory *FactoryAdapter =
87 /// newFrontendActionFactory(&Factory);
88 template <typename FactoryT>
89 inline FrontendActionFactory *newFrontendActionFactory(
90 FactoryT *ConsumerFactory);
92 /// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag.
94 /// \param ToolAction The action to run over the code.
95 /// \param Code C++ code.
96 /// \param FileName The file name which 'Code' will be mapped as.
98 /// \return - True if 'ToolAction' was successfully executed.
99 bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
100 const Twine &FileName = "input.cc");
102 /// \brief Utility to run a FrontendAction in a single clang invocation.
103 class ToolInvocation {
105 /// \brief Create a tool invocation.
107 /// \param CommandLine The command line arguments to clang. Note that clang
108 /// uses its binary name (CommandLine[0]) to locate its builtin headers.
109 /// Callers have to ensure that they are installed in a compatible location
110 /// (see clang driver implementation) or mapped in via mapVirtualFile.
111 /// \param ToolAction The action to be executed. Class takes ownership.
112 /// \param Files The FileManager used for the execution. Class does not take
114 ToolInvocation(ArrayRef<std::string> CommandLine, FrontendAction *ToolAction,
117 /// \brief Map a virtual file to be used while running the tool.
119 /// \param FilePath The path at which the content will be mapped.
120 /// \param Content A null terminated buffer of the file's content.
121 void mapVirtualFile(StringRef FilePath, StringRef Content);
123 /// \brief Run the clang invocation.
125 /// \returns True if there were no errors during execution.
129 void addFileMappingsTo(SourceManager &SourceManager);
131 bool runInvocation(const char *BinaryName,
132 clang::driver::Compilation *Compilation,
133 clang::CompilerInvocation *Invocation,
134 const clang::driver::ArgStringList &CC1Args);
136 std::vector<std::string> CommandLine;
137 llvm::OwningPtr<FrontendAction> ToolAction;
139 // Maps <file name> -> <file content>.
140 llvm::StringMap<StringRef> MappedFileContents;
143 /// \brief Utility to run a FrontendAction over a set of files.
145 /// This class is written to be usable for command line utilities.
146 /// By default the class uses ClangSyntaxOnlyAdjuster to modify
147 /// command line arguments before the arguments are used to run
148 /// a frontend action. One could install another command line
149 /// arguments adjuster by call setArgumentsAdjuster() method.
152 /// \brief Constructs a clang tool to run over a list of files.
154 /// \param Compilations The CompilationDatabase which contains the compile
155 /// command lines for the given source paths.
156 /// \param SourcePaths The source files to run over. If a source files is
157 /// not found in Compilations, it is skipped.
158 ClangTool(const CompilationDatabase &Compilations,
159 ArrayRef<std::string> SourcePaths);
161 /// \brief Map a virtual file to be used while running the tool.
163 /// \param FilePath The path at which the content will be mapped.
164 /// \param Content A null terminated buffer of the file's content.
165 void mapVirtualFile(StringRef FilePath, StringRef Content);
167 /// \brief Install command line arguments adjuster.
169 /// \param Adjuster Command line arguments adjuster.
170 void setArgumentsAdjuster(ArgumentsAdjuster *Adjuster);
172 /// Runs a frontend action over all files specified in the command line.
174 /// \param ActionFactory Factory generating the frontend actions. The function
175 /// takes ownership of this parameter. A new action is generated for every
176 /// processed translation unit.
177 int run(FrontendActionFactory *ActionFactory);
179 /// \brief Returns the file manager used in the tool.
181 /// The file manager is shared between all translation units.
182 FileManager &getFiles() { return Files; }
185 // We store compile commands as pair (file name, compile command).
186 std::vector< std::pair<std::string, CompileCommand> > CompileCommands;
189 // Contains a list of pairs (<file name>, <file content>).
190 std::vector< std::pair<StringRef, StringRef> > MappedFileContents;
192 llvm::OwningPtr<ArgumentsAdjuster> ArgsAdjuster;
195 template <typename T>
196 FrontendActionFactory *newFrontendActionFactory() {
197 class SimpleFrontendActionFactory : public FrontendActionFactory {
199 virtual clang::FrontendAction *create() { return new T; }
202 return new SimpleFrontendActionFactory;
205 template <typename FactoryT>
206 inline FrontendActionFactory *newFrontendActionFactory(
207 FactoryT *ConsumerFactory) {
208 class FrontendActionFactoryAdapter : public FrontendActionFactory {
210 explicit FrontendActionFactoryAdapter(FactoryT *ConsumerFactory)
211 : ConsumerFactory(ConsumerFactory) {}
213 virtual clang::FrontendAction *create() {
214 return new ConsumerFactoryAdaptor(ConsumerFactory);
218 class ConsumerFactoryAdaptor : public clang::ASTFrontendAction {
220 ConsumerFactoryAdaptor(FactoryT *ConsumerFactory)
221 : ConsumerFactory(ConsumerFactory) {}
223 clang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &,
225 return ConsumerFactory->newASTConsumer();
229 FactoryT *ConsumerFactory;
231 FactoryT *ConsumerFactory;
234 return new FrontendActionFactoryAdapter(ConsumerFactory);
237 /// \brief Returns the absolute path of \c File, by prepending it with
238 /// the current directory if \c File is not absolute.
240 /// Otherwise returns \c File.
241 /// If 'File' starts with "./", the returned path will not contain the "./".
242 /// Otherwise, the returned path will contain the literal path-concatenation of
243 /// the current directory and \c File.
245 /// The difference to llvm::sys::fs::make_absolute is that we prefer
246 /// ::getenv("PWD") if available.
247 /// FIXME: Make this functionality available from llvm::sys::fs and delete
250 /// \param File Either an absolute or relative path.
251 std::string getAbsolutePath(StringRef File);
253 } // end namespace tooling
254 } // end namespace clang
256 #endif // LLVM_CLANG_TOOLING_TOOLING_H