]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Tooling/Tooling.h
Merge OpenBSM 1.2-alpha2 from vendor branch to FreeBSD 10-CURRENT; the
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / Tooling / Tooling.h
1 //===--- Tooling.h - Framework for standalone Clang tools -------*- 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 implements functions to run clang tools standalone instead
11 //  of running them as a plugin.
12 //
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.
16 //
17 //  It is also possible to run a FrontendAction over a snippet of code by
18 //  calling runToolOnCode, which is useful for unit testing.
19 //
20 //  Applications that need more fine grained control over how to run
21 //  multiple FrontendActions over code can use ToolInvocation.
22 //
23 //  Example tools:
24 //  - running clang -fsyntax-only over source code from an editor to get
25 //    fast syntax checks
26 //  - running match/replace tools over C++ code
27 //
28 //===----------------------------------------------------------------------===//
29
30 #ifndef LLVM_CLANG_TOOLING_TOOLING_H
31 #define LLVM_CLANG_TOOLING_TOOLING_H
32
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"
41 #include <string>
42 #include <vector>
43
44 namespace clang {
45
46 namespace driver {
47 class Compilation;
48 } // end namespace driver
49
50 class CompilerInvocation;
51 class SourceManager;
52 class FrontendAction;
53
54 namespace tooling {
55
56 /// \brief Interface to generate clang::FrontendActions.
57 class FrontendActionFactory {
58 public:
59   virtual ~FrontendActionFactory();
60
61   /// \brief Returns a new clang::FrontendAction.
62   ///
63   /// The caller takes ownership of the returned action.
64   virtual clang::FrontendAction *create() = 0;
65 };
66
67 /// \brief Returns a new FrontendActionFactory for a given type.
68 ///
69 /// T must extend clang::FrontendAction.
70 ///
71 /// Example:
72 /// FrontendActionFactory *Factory =
73 ///   newFrontendActionFactory<clang::SyntaxOnlyAction>();
74 template <typename T>
75 FrontendActionFactory *newFrontendActionFactory();
76
77 /// \brief Returns a new FrontendActionFactory for any type that provides an
78 /// implementation of newASTConsumer().
79 ///
80 /// FactoryT must implement: ASTConsumer *newASTConsumer().
81 ///
82 /// Example:
83 /// struct ProvidesASTConsumers {
84 ///   clang::ASTConsumer *newASTConsumer();
85 /// } Factory;
86 /// FrontendActionFactory *FactoryAdapter =
87 ///   newFrontendActionFactory(&Factory);
88 template <typename FactoryT>
89 inline FrontendActionFactory *newFrontendActionFactory(
90     FactoryT *ConsumerFactory);
91
92 /// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag.
93 ///
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.
97 ///
98 /// \return - True if 'ToolAction' was successfully executed.
99 bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
100                    const Twine &FileName = "input.cc");
101
102 /// \brief Utility to run a FrontendAction in a single clang invocation.
103 class ToolInvocation {
104  public:
105   /// \brief Create a tool invocation.
106   ///
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
113   /// ownership.
114   ToolInvocation(ArrayRef<std::string> CommandLine, FrontendAction *ToolAction,
115                  FileManager *Files);
116
117   /// \brief Map a virtual file to be used while running the tool.
118   ///
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);
122
123   /// \brief Run the clang invocation.
124   ///
125   /// \returns True if there were no errors during execution.
126   bool run();
127
128  private:
129   void addFileMappingsTo(SourceManager &SourceManager);
130
131   bool runInvocation(const char *BinaryName,
132                      clang::driver::Compilation *Compilation,
133                      clang::CompilerInvocation *Invocation,
134                      const clang::driver::ArgStringList &CC1Args);
135
136   std::vector<std::string> CommandLine;
137   llvm::OwningPtr<FrontendAction> ToolAction;
138   FileManager *Files;
139   // Maps <file name> -> <file content>.
140   llvm::StringMap<StringRef> MappedFileContents;
141 };
142
143 /// \brief Utility to run a FrontendAction over a set of files.
144 ///
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.
150 class ClangTool {
151  public:
152   /// \brief Constructs a clang tool to run over a list of files.
153   ///
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);
160
161   /// \brief Map a virtual file to be used while running the tool.
162   ///
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);
166
167   /// \brief Install command line arguments adjuster.
168   ///
169   /// \param Adjuster Command line arguments adjuster.
170   void setArgumentsAdjuster(ArgumentsAdjuster *Adjuster);
171
172   /// Runs a frontend action over all files specified in the command line.
173   ///
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);
178
179   /// \brief Returns the file manager used in the tool.
180   ///
181   /// The file manager is shared between all translation units.
182   FileManager &getFiles() { return Files; }
183
184  private:
185   // We store compile commands as pair (file name, compile command).
186   std::vector< std::pair<std::string, CompileCommand> > CompileCommands;
187
188   FileManager Files;
189   // Contains a list of pairs (<file name>, <file content>).
190   std::vector< std::pair<StringRef, StringRef> > MappedFileContents;
191
192   llvm::OwningPtr<ArgumentsAdjuster> ArgsAdjuster;
193 };
194
195 template <typename T>
196 FrontendActionFactory *newFrontendActionFactory() {
197   class SimpleFrontendActionFactory : public FrontendActionFactory {
198   public:
199     virtual clang::FrontendAction *create() { return new T; }
200   };
201
202   return new SimpleFrontendActionFactory;
203 }
204
205 template <typename FactoryT>
206 inline FrontendActionFactory *newFrontendActionFactory(
207     FactoryT *ConsumerFactory) {
208   class FrontendActionFactoryAdapter : public FrontendActionFactory {
209   public:
210     explicit FrontendActionFactoryAdapter(FactoryT *ConsumerFactory)
211       : ConsumerFactory(ConsumerFactory) {}
212
213     virtual clang::FrontendAction *create() {
214       return new ConsumerFactoryAdaptor(ConsumerFactory);
215     }
216
217   private:
218     class ConsumerFactoryAdaptor : public clang::ASTFrontendAction {
219     public:
220       ConsumerFactoryAdaptor(FactoryT *ConsumerFactory)
221         : ConsumerFactory(ConsumerFactory) {}
222
223       clang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &,
224                                             llvm::StringRef) {
225         return ConsumerFactory->newASTConsumer();
226       }
227
228     private:
229       FactoryT *ConsumerFactory;
230     };
231     FactoryT *ConsumerFactory;
232   };
233
234   return new FrontendActionFactoryAdapter(ConsumerFactory);
235 }
236
237 /// \brief Returns the absolute path of \c File, by prepending it with
238 /// the current directory if \c File is not absolute.
239 ///
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.
244 ///
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
248 ///        this function.
249 ///
250 /// \param File Either an absolute or relative path.
251 std::string getAbsolutePath(StringRef File);
252
253 } // end namespace tooling
254 } // end namespace clang
255
256 #endif // LLVM_CLANG_TOOLING_TOOLING_H