blob: 8ad2675ee9fd9bcc8eb932083713eba9ba03bfdf [file] [log] [blame]
Manuel Klimek47c245a2012-04-04 12:07:46 +00001//===--- Tooling.cpp - Running clang standalone tools ---------------------===//
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//===----------------------------------------------------------------------===//
14
15#include "clang/Tooling/Tooling.h"
Peter Collingbournec689ee72013-11-06 20:12:45 +000016#include "clang/AST/ASTConsumer.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000017#include "clang/Driver/Compilation.h"
18#include "clang/Driver/Driver.h"
19#include "clang/Driver/Tool.h"
Peter Collingbournec689ee72013-11-06 20:12:45 +000020#include "clang/Frontend/ASTUnit.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000021#include "clang/Frontend/CompilerInstance.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000022#include "clang/Frontend/FrontendDiagnostic.h"
23#include "clang/Frontend/TextDiagnosticPrinter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Tooling/ArgumentsAdjusters.h"
25#include "clang/Tooling/CompilationDatabase.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000026#include "llvm/ADT/STLExtras.h"
Hans Wennborg501eadb2014-03-12 16:07:46 +000027#include "llvm/Config/config.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000028#include "llvm/Option/Option.h"
Edwin Vane34794c52013-03-15 20:14:01 +000029#include "llvm/Support/Debug.h"
NAKAMURA Takumif0c87792012-04-04 13:59:36 +000030#include "llvm/Support/FileSystem.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000031#include "llvm/Support/Host.h"
32#include "llvm/Support/raw_ostream.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000033
Manuel Klimek74cec542012-05-07 09:45:46 +000034// For chdir, see the comment in ClangTool::run for more information.
Hans Wennborg501eadb2014-03-12 16:07:46 +000035#ifdef LLVM_ON_WIN32
Manuel Klimek74cec542012-05-07 09:45:46 +000036# include <direct.h>
Manuel Klimekf33dcb02012-05-07 10:02:55 +000037#else
38# include <unistd.h>
Manuel Klimek74cec542012-05-07 09:45:46 +000039#endif
40
Manuel Klimek47c245a2012-04-04 12:07:46 +000041namespace clang {
42namespace tooling {
43
Peter Collingbournec689ee72013-11-06 20:12:45 +000044ToolAction::~ToolAction() {}
45
Manuel Klimek47c245a2012-04-04 12:07:46 +000046FrontendActionFactory::~FrontendActionFactory() {}
47
48// FIXME: This file contains structural duplication with other parts of the
49// code that sets up a compiler to run tools on it, and we should refactor
50// it to be based on the same framework.
51
52/// \brief Builds a clang driver initialized for running clang tools.
53static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics,
54 const char *BinaryName) {
55 const std::string DefaultOutputName = "a.out";
56 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Alexander Kornienko8388d242012-06-04 19:02:59 +000057 BinaryName, llvm::sys::getDefaultTargetTriple(),
Rafael Espindolab0448cd2012-11-27 16:10:37 +000058 DefaultOutputName, *Diagnostics);
Manuel Klimek47c245a2012-04-04 12:07:46 +000059 CompilerDriver->setTitle("clang_based_tool");
60 return CompilerDriver;
61}
62
63/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
64///
65/// Returns NULL on error.
Reid Kleckner898229a2013-06-14 17:17:23 +000066static const llvm::opt::ArgStringList *getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +000067 clang::DiagnosticsEngine *Diagnostics,
68 clang::driver::Compilation *Compilation) {
69 // We expect to get back exactly one Command job, if we didn't something
70 // failed. Extract that job from the Compilation.
71 const clang::driver::JobList &Jobs = Compilation->getJobs();
72 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000073 SmallString<256> error_msg;
Manuel Klimek47c245a2012-04-04 12:07:46 +000074 llvm::raw_svector_ostream error_stream(error_msg);
Hans Wennborgb212b342013-09-12 18:23:34 +000075 Jobs.Print(error_stream, "; ", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +000076 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
77 << error_stream.str();
78 return NULL;
79 }
80
81 // The one job we find should be to invoke clang again.
82 const clang::driver::Command *Cmd =
83 cast<clang::driver::Command>(*Jobs.begin());
84 if (StringRef(Cmd->getCreator().getName()) != "clang") {
85 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
86 return NULL;
87 }
88
89 return &Cmd->getArguments();
90}
91
92/// \brief Returns a clang build invocation initialized from the CC1 flags.
93static clang::CompilerInvocation *newInvocation(
94 clang::DiagnosticsEngine *Diagnostics,
Reid Kleckner898229a2013-06-14 17:17:23 +000095 const llvm::opt::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000096 assert(!CC1Args.empty() && "Must at least contain the program name!");
97 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
98 clang::CompilerInvocation::CreateFromArgs(
99 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
100 *Diagnostics);
101 Invocation->getFrontendOpts().DisableFree = false;
Nick Lewycky39dc9f82013-06-25 17:01:21 +0000102 Invocation->getCodeGenOpts().DisableFree = false;
Peter Collingbournec0423b32014-03-02 23:37:26 +0000103 Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000104 return Invocation;
105}
106
107bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
108 const Twine &FileName) {
Nico Weber077a53e2012-08-30 02:02:19 +0000109 return runToolOnCodeWithArgs(
110 ToolAction, Code, std::vector<std::string>(), FileName);
111}
112
Peter Collingbournec689ee72013-11-06 20:12:45 +0000113static std::vector<std::string>
114getSyntaxOnlyToolArgs(const std::vector<std::string> &ExtraArgs,
115 StringRef FileName) {
116 std::vector<std::string> Args;
117 Args.push_back("clang-tool");
118 Args.push_back("-fsyntax-only");
119 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
120 Args.push_back(FileName.str());
121 return Args;
122}
123
Nico Weber077a53e2012-08-30 02:02:19 +0000124bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
125 const std::vector<std::string> &Args,
126 const Twine &FileName) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000127 SmallString<16> FileNameStorage;
128 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000129 llvm::IntrusiveRefCntPtr<FileManager> Files(
130 new FileManager(FileSystemOptions()));
131 ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), ToolAction,
132 Files.getPtr());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000133
134 SmallString<1024> CodeStorage;
135 Invocation.mapVirtualFile(FileNameRef,
136 Code.toNullTerminatedStringRef(CodeStorage));
137 return Invocation.run();
138}
139
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000140std::string getAbsolutePath(StringRef File) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000141 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000142 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000143 if (RelativePath.startswith("./")) {
144 RelativePath = RelativePath.substr(strlen("./"));
145 }
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000146
147 SmallString<1024> AbsolutePath = RelativePath;
148 llvm::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
149 assert(!EC);
Rafael Espindola0b8e4a12013-08-10 04:25:53 +0000150 (void)EC;
Benjamin Kramer2d4d8cb2013-09-11 11:23:15 +0000151 llvm::sys::path::native(AbsolutePath);
152 return AbsolutePath.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000153}
154
Peter Collingbournec689ee72013-11-06 20:12:45 +0000155namespace {
156
157class SingleFrontendActionFactory : public FrontendActionFactory {
158 FrontendAction *Action;
159
160public:
161 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
162
163 FrontendAction *create() { return Action; }
164};
165
166}
167
168ToolInvocation::ToolInvocation(ArrayRef<std::string> CommandLine,
169 ToolAction *Action, FileManager *Files)
Manuel Klimek64083012013-11-07 23:18:05 +0000170 : CommandLine(CommandLine.vec()),
171 Action(Action),
172 OwnsAction(false),
173 Files(Files),
174 DiagConsumer(NULL) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000175
176ToolInvocation::ToolInvocation(ArrayRef<std::string> CommandLine,
177 FrontendAction *FAction, FileManager *Files)
178 : CommandLine(CommandLine.vec()),
Manuel Klimek64083012013-11-07 23:18:05 +0000179 Action(new SingleFrontendActionFactory(FAction)),
180 OwnsAction(true),
181 Files(Files),
182 DiagConsumer(NULL) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000183
184ToolInvocation::~ToolInvocation() {
185 if (OwnsAction)
186 delete Action;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000187}
188
Manuel Klimek64083012013-11-07 23:18:05 +0000189void ToolInvocation::setDiagnosticConsumer(DiagnosticConsumer *D) {
190 DiagConsumer = D;
191}
192
Manuel Klimek47c245a2012-04-04 12:07:46 +0000193void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000194 SmallString<1024> PathStorage;
195 llvm::sys::path::native(FilePath, PathStorage);
196 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000197}
198
199bool ToolInvocation::run() {
200 std::vector<const char*> Argv;
201 for (int I = 0, E = CommandLine.size(); I != E; ++I)
202 Argv.push_back(CommandLine[I].c_str());
203 const char *const BinaryName = Argv[0];
Douglas Gregor811db4e2012-10-23 22:26:28 +0000204 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000205 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000206 llvm::errs(), &*DiagOpts);
207 DiagnosticsEngine Diagnostics(
Manuel Klimek64083012013-11-07 23:18:05 +0000208 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
209 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000210
Ahmed Charlesb8984322014-03-07 20:03:18 +0000211 const std::unique_ptr<clang::driver::Driver> Driver(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000212 newDriver(&Diagnostics, BinaryName));
213 // Since the input might only be virtual, don't check whether it exists.
214 Driver->setCheckInputsExist(false);
Ahmed Charlesb8984322014-03-07 20:03:18 +0000215 const std::unique_ptr<clang::driver::Compilation> Compilation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000216 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Reid Kleckner898229a2013-06-14 17:17:23 +0000217 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000218 &Diagnostics, Compilation.get());
219 if (CC1Args == NULL) {
220 return false;
221 }
Ahmed Charlesb8984322014-03-07 20:03:18 +0000222 std::unique_ptr<clang::CompilerInvocation> Invocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000223 newInvocation(&Diagnostics, *CC1Args));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000224 for (llvm::StringMap<StringRef>::const_iterator
225 It = MappedFileContents.begin(), End = MappedFileContents.end();
226 It != End; ++It) {
227 // Inject the code as the given file name into the preprocessor options.
228 const llvm::MemoryBuffer *Input =
229 llvm::MemoryBuffer::getMemBuffer(It->getValue());
230 Invocation->getPreprocessorOpts().addRemappedFile(It->getKey(), Input);
231 }
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000232 return runInvocation(BinaryName, Compilation.get(), Invocation.release());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000233}
234
Manuel Klimek47c245a2012-04-04 12:07:46 +0000235bool ToolInvocation::runInvocation(
236 const char *BinaryName,
237 clang::driver::Compilation *Compilation,
Sean Silvaf1b49e22013-01-20 01:58:28 +0000238 clang::CompilerInvocation *Invocation) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000239 // Show the invocation, with -v.
240 if (Invocation->getHeaderSearchOpts().Verbose) {
241 llvm::errs() << "clang Invocation:\n";
Hans Wennborgb212b342013-09-12 18:23:34 +0000242 Compilation->getJobs().Print(llvm::errs(), "\n", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000243 llvm::errs() << "\n";
244 }
245
Manuel Klimek64083012013-11-07 23:18:05 +0000246 return Action->runInvocation(Invocation, Files, DiagConsumer);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000247}
248
249bool FrontendActionFactory::runInvocation(CompilerInvocation *Invocation,
Manuel Klimek64083012013-11-07 23:18:05 +0000250 FileManager *Files,
251 DiagnosticConsumer *DiagConsumer) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000252 // Create a compiler instance to handle the actual work.
253 clang::CompilerInstance Compiler;
254 Compiler.setInvocation(Invocation);
255 Compiler.setFileManager(Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000256
Peter Collingbournec689ee72013-11-06 20:12:45 +0000257 // The FrontendAction can have lifetime requirements for Compiler or its
258 // members, and we need to ensure it's deleted earlier than Compiler. So we
Ahmed Charlesb8984322014-03-07 20:03:18 +0000259 // pass it to an std::unique_ptr declared after the Compiler variable.
260 std::unique_ptr<FrontendAction> ScopedToolAction(create());
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000261
Manuel Klimek47c245a2012-04-04 12:07:46 +0000262 // Create the compilers actual diagnostics engine.
Manuel Klimek64083012013-11-07 23:18:05 +0000263 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000264 if (!Compiler.hasDiagnostics())
265 return false;
266
267 Compiler.createSourceManager(*Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000268
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000269 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000270
Manuel Klimek3aad8552012-07-31 13:56:54 +0000271 Files->clearStatCaches();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000272 return Success;
273}
274
Manuel Klimek47c245a2012-04-04 12:07:46 +0000275ClangTool::ClangTool(const CompilationDatabase &Compilations,
276 ArrayRef<std::string> SourcePaths)
Manuel Klimek64083012013-11-07 23:18:05 +0000277 : Files(new FileManager(FileSystemOptions())), DiagConsumer(NULL) {
Pavel Labathdee20c12013-06-06 11:52:19 +0000278 ArgsAdjusters.push_back(new ClangStripOutputAdjuster());
279 ArgsAdjusters.push_back(new ClangSyntaxOnlyAdjuster());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000280 for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000281 SmallString<1024> File(getAbsolutePath(SourcePaths[I]));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000282
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000283 std::vector<CompileCommand> CompileCommandsForFile =
Manuel Klimek47c245a2012-04-04 12:07:46 +0000284 Compilations.getCompileCommands(File.str());
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000285 if (!CompileCommandsForFile.empty()) {
286 for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) {
287 CompileCommands.push_back(std::make_pair(File.str(),
288 CompileCommandsForFile[I]));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000289 }
290 } else {
291 // FIXME: There are two use cases here: doing a fuzzy
292 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
293 // about the .cc files that were not found, and the use case where I
294 // specify all files I want to run over explicitly, where this should
295 // be an error. We'll want to add an option for this.
296 llvm::outs() << "Skipping " << File << ". Command line not found.\n";
297 }
298 }
299}
300
Manuel Klimek64083012013-11-07 23:18:05 +0000301void ClangTool::setDiagnosticConsumer(DiagnosticConsumer *D) {
302 DiagConsumer = D;
303}
304
Manuel Klimek47c245a2012-04-04 12:07:46 +0000305void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
306 MappedFileContents.push_back(std::make_pair(FilePath, Content));
307}
308
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000309void ClangTool::setArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
Manuel Klimekd91ac932013-06-04 14:44:44 +0000310 clearArgumentsAdjusters();
311 appendArgumentsAdjuster(Adjuster);
312}
313
314void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
315 ArgsAdjusters.push_back(Adjuster);
316}
317
318void ClangTool::clearArgumentsAdjusters() {
319 for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I)
320 delete ArgsAdjusters[I];
321 ArgsAdjusters.clear();
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000322}
323
Peter Collingbournec689ee72013-11-06 20:12:45 +0000324int ClangTool::run(ToolAction *Action) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000325 // Exists solely for the purpose of lookup of the resource path.
326 // This just needs to be some symbol in the binary.
327 static int StaticSymbol;
328 // The driver detects the builtin header path based on the path of the
329 // executable.
330 // FIXME: On linux, GetMainExecutable is independent of the value of the
331 // first argument, thus allowing ClangTool and runToolOnCode to just
332 // pass in made-up names here. Make sure this works on other platforms.
333 std::string MainExecutable =
Rafael Espindola9678d272013-06-26 05:03:40 +0000334 llvm::sys::fs::getMainExecutable("clang_tool", &StaticSymbol);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000335
Manuel Klimek47c245a2012-04-04 12:07:46 +0000336 bool ProcessingFailed = false;
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000337 for (unsigned I = 0; I < CompileCommands.size(); ++I) {
338 std::string File = CompileCommands[I].first;
339 // FIXME: chdir is thread hostile; on the other hand, creating the same
340 // behavior as chdir is complex: chdir resolves the path once, thus
341 // guaranteeing that all subsequent relative path operations work
342 // on the same path the original chdir resulted in. This makes a difference
Alexander Kornienko8388d242012-06-04 19:02:59 +0000343 // for example on network filesystems, where symlinks might be switched
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000344 // during runtime of the tool. Fixing this depends on having a file system
345 // abstraction that allows openat() style interactions.
346 if (chdir(CompileCommands[I].second.Directory.c_str()))
347 llvm::report_fatal_error("Cannot chdir into \"" +
348 CompileCommands[I].second.Directory + "\n!");
Manuel Klimekd91ac932013-06-04 14:44:44 +0000349 std::vector<std::string> CommandLine = CompileCommands[I].second.CommandLine;
350 for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I)
351 CommandLine = ArgsAdjusters[I]->Adjust(CommandLine);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000352 assert(!CommandLine.empty());
353 CommandLine[0] = MainExecutable;
Edwin Vane34794c52013-03-15 20:14:01 +0000354 // FIXME: We need a callback mechanism for the tool writer to output a
355 // customized message for each file.
356 DEBUG({
357 llvm::dbgs() << "Processing: " << File << ".\n";
358 });
Peter Collingbournec689ee72013-11-06 20:12:45 +0000359 ToolInvocation Invocation(CommandLine, Action, Files.getPtr());
Manuel Klimek64083012013-11-07 23:18:05 +0000360 Invocation.setDiagnosticConsumer(DiagConsumer);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000361 for (int I = 0, E = MappedFileContents.size(); I != E; ++I) {
362 Invocation.mapVirtualFile(MappedFileContents[I].first,
363 MappedFileContents[I].second);
364 }
365 if (!Invocation.run()) {
Edwin Vane34794c52013-03-15 20:14:01 +0000366 // FIXME: Diagnostics should be used instead.
367 llvm::errs() << "Error while processing " << File << ".\n";
Manuel Klimek47c245a2012-04-04 12:07:46 +0000368 ProcessingFailed = true;
369 }
370 }
371 return ProcessingFailed ? 1 : 0;
372}
373
Peter Collingbournec689ee72013-11-06 20:12:45 +0000374namespace {
375
376class ASTBuilderAction : public ToolAction {
377 std::vector<ASTUnit *> &ASTs;
378
379public:
380 ASTBuilderAction(std::vector<ASTUnit *> &ASTs) : ASTs(ASTs) {}
381
Manuel Klimek64083012013-11-07 23:18:05 +0000382 bool runInvocation(CompilerInvocation *Invocation, FileManager *Files,
383 DiagnosticConsumer *DiagConsumer) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000384 // FIXME: This should use the provided FileManager.
385 ASTUnit *AST = ASTUnit::LoadFromCompilerInvocation(
Manuel Klimek64083012013-11-07 23:18:05 +0000386 Invocation, CompilerInstance::createDiagnostics(
387 &Invocation->getDiagnosticOpts(), DiagConsumer,
388 /*ShouldOwnClient=*/false));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000389 if (!AST)
390 return false;
391
392 ASTs.push_back(AST);
393 return true;
394 }
395};
396
397}
398
399int ClangTool::buildASTs(std::vector<ASTUnit *> &ASTs) {
400 ASTBuilderAction Action(ASTs);
401 return run(&Action);
402}
403
404ASTUnit *buildASTFromCode(const Twine &Code, const Twine &FileName) {
405 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName);
406}
407
408ASTUnit *buildASTFromCodeWithArgs(const Twine &Code,
409 const std::vector<std::string> &Args,
410 const Twine &FileName) {
411 SmallString<16> FileNameStorage;
412 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
413
414 std::vector<ASTUnit *> ASTs;
415 ASTBuilderAction Action(ASTs);
416 ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), &Action, 0);
417
418 SmallString<1024> CodeStorage;
419 Invocation.mapVirtualFile(FileNameRef,
420 Code.toNullTerminatedStringRef(CodeStorage));
421 if (!Invocation.run())
422 return 0;
423
424 assert(ASTs.size() == 1);
425 return ASTs[0];
426}
427
Manuel Klimek47c245a2012-04-04 12:07:46 +0000428} // end namespace tooling
429} // end namespace clang