blob: 5f4c46d6ef3d7ba8989778a00f1512e909fbed77 [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
Chandler Carruth57f5fbe2014-04-21 22:55:36 +000041#define DEBUG_TYPE "clang-tooling"
42
Manuel Klimek47c245a2012-04-04 12:07:46 +000043namespace clang {
44namespace tooling {
45
Peter Collingbournec689ee72013-11-06 20:12:45 +000046ToolAction::~ToolAction() {}
47
Manuel Klimek47c245a2012-04-04 12:07:46 +000048FrontendActionFactory::~FrontendActionFactory() {}
49
50// FIXME: This file contains structural duplication with other parts of the
51// code that sets up a compiler to run tools on it, and we should refactor
52// it to be based on the same framework.
53
54/// \brief Builds a clang driver initialized for running clang tools.
55static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics,
56 const char *BinaryName) {
Benjamin Kramerefb1eb92014-03-20 12:48:36 +000057 const char *DefaultOutputName = "a.out";
Manuel Klimek47c245a2012-04-04 12:07:46 +000058 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Alexander Kornienko8388d242012-06-04 19:02:59 +000059 BinaryName, llvm::sys::getDefaultTargetTriple(),
Rafael Espindolab0448cd2012-11-27 16:10:37 +000060 DefaultOutputName, *Diagnostics);
Manuel Klimek47c245a2012-04-04 12:07:46 +000061 CompilerDriver->setTitle("clang_based_tool");
62 return CompilerDriver;
63}
64
65/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
66///
67/// Returns NULL on error.
Reid Kleckner898229a2013-06-14 17:17:23 +000068static const llvm::opt::ArgStringList *getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +000069 clang::DiagnosticsEngine *Diagnostics,
70 clang::driver::Compilation *Compilation) {
71 // We expect to get back exactly one Command job, if we didn't something
72 // failed. Extract that job from the Compilation.
73 const clang::driver::JobList &Jobs = Compilation->getJobs();
74 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000075 SmallString<256> error_msg;
Manuel Klimek47c245a2012-04-04 12:07:46 +000076 llvm::raw_svector_ostream error_stream(error_msg);
Hans Wennborgb212b342013-09-12 18:23:34 +000077 Jobs.Print(error_stream, "; ", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +000078 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
79 << error_stream.str();
80 return NULL;
81 }
82
83 // The one job we find should be to invoke clang again.
84 const clang::driver::Command *Cmd =
85 cast<clang::driver::Command>(*Jobs.begin());
86 if (StringRef(Cmd->getCreator().getName()) != "clang") {
87 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
88 return NULL;
89 }
90
91 return &Cmd->getArguments();
92}
93
94/// \brief Returns a clang build invocation initialized from the CC1 flags.
95static clang::CompilerInvocation *newInvocation(
96 clang::DiagnosticsEngine *Diagnostics,
Reid Kleckner898229a2013-06-14 17:17:23 +000097 const llvm::opt::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000098 assert(!CC1Args.empty() && "Must at least contain the program name!");
99 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
100 clang::CompilerInvocation::CreateFromArgs(
101 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
102 *Diagnostics);
103 Invocation->getFrontendOpts().DisableFree = false;
Nick Lewycky39dc9f82013-06-25 17:01:21 +0000104 Invocation->getCodeGenOpts().DisableFree = false;
Peter Collingbournec0423b32014-03-02 23:37:26 +0000105 Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000106 return Invocation;
107}
108
109bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
110 const Twine &FileName) {
Nico Weber077a53e2012-08-30 02:02:19 +0000111 return runToolOnCodeWithArgs(
112 ToolAction, Code, std::vector<std::string>(), FileName);
113}
114
Peter Collingbournec689ee72013-11-06 20:12:45 +0000115static std::vector<std::string>
116getSyntaxOnlyToolArgs(const std::vector<std::string> &ExtraArgs,
117 StringRef FileName) {
118 std::vector<std::string> Args;
119 Args.push_back("clang-tool");
120 Args.push_back("-fsyntax-only");
121 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
122 Args.push_back(FileName.str());
123 return Args;
124}
125
Nico Weber077a53e2012-08-30 02:02:19 +0000126bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
127 const std::vector<std::string> &Args,
128 const Twine &FileName) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000129 SmallString<16> FileNameStorage;
130 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000131 llvm::IntrusiveRefCntPtr<FileManager> Files(
132 new FileManager(FileSystemOptions()));
133 ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), ToolAction,
134 Files.getPtr());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000135
136 SmallString<1024> CodeStorage;
137 Invocation.mapVirtualFile(FileNameRef,
138 Code.toNullTerminatedStringRef(CodeStorage));
139 return Invocation.run();
140}
141
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000142std::string getAbsolutePath(StringRef File) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000143 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000144 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000145 if (RelativePath.startswith("./")) {
146 RelativePath = RelativePath.substr(strlen("./"));
147 }
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000148
149 SmallString<1024> AbsolutePath = RelativePath;
150 llvm::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
151 assert(!EC);
Rafael Espindola0b8e4a12013-08-10 04:25:53 +0000152 (void)EC;
Benjamin Kramer2d4d8cb2013-09-11 11:23:15 +0000153 llvm::sys::path::native(AbsolutePath);
154 return AbsolutePath.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000155}
156
Peter Collingbournec689ee72013-11-06 20:12:45 +0000157namespace {
158
159class SingleFrontendActionFactory : public FrontendActionFactory {
160 FrontendAction *Action;
161
162public:
163 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
164
Craig Topperfb6b25b2014-03-15 04:29:04 +0000165 FrontendAction *create() override { return Action; }
Peter Collingbournec689ee72013-11-06 20:12:45 +0000166};
167
168}
169
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000170ToolInvocation::ToolInvocation(std::vector<std::string> CommandLine,
Peter Collingbournec689ee72013-11-06 20:12:45 +0000171 ToolAction *Action, FileManager *Files)
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000172 : CommandLine(std::move(CommandLine)),
Manuel Klimek64083012013-11-07 23:18:05 +0000173 Action(Action),
174 OwnsAction(false),
175 Files(Files),
176 DiagConsumer(NULL) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000177
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000178ToolInvocation::ToolInvocation(std::vector<std::string> CommandLine,
Peter Collingbournec689ee72013-11-06 20:12:45 +0000179 FrontendAction *FAction, FileManager *Files)
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000180 : CommandLine(std::move(CommandLine)),
Manuel Klimek64083012013-11-07 23:18:05 +0000181 Action(new SingleFrontendActionFactory(FAction)),
182 OwnsAction(true),
183 Files(Files),
184 DiagConsumer(NULL) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000185
186ToolInvocation::~ToolInvocation() {
187 if (OwnsAction)
188 delete Action;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000189}
190
Manuel Klimek64083012013-11-07 23:18:05 +0000191void ToolInvocation::setDiagnosticConsumer(DiagnosticConsumer *D) {
192 DiagConsumer = D;
193}
194
Manuel Klimek47c245a2012-04-04 12:07:46 +0000195void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000196 SmallString<1024> PathStorage;
197 llvm::sys::path::native(FilePath, PathStorage);
198 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000199}
200
201bool ToolInvocation::run() {
202 std::vector<const char*> Argv;
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000203 for (const std::string &Str : CommandLine)
204 Argv.push_back(Str.c_str());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000205 const char *const BinaryName = Argv[0];
Douglas Gregor811db4e2012-10-23 22:26:28 +0000206 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000207 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000208 llvm::errs(), &*DiagOpts);
209 DiagnosticsEngine Diagnostics(
Manuel Klimek64083012013-11-07 23:18:05 +0000210 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
211 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000212
Ahmed Charlesb8984322014-03-07 20:03:18 +0000213 const std::unique_ptr<clang::driver::Driver> Driver(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000214 newDriver(&Diagnostics, BinaryName));
215 // Since the input might only be virtual, don't check whether it exists.
216 Driver->setCheckInputsExist(false);
Ahmed Charlesb8984322014-03-07 20:03:18 +0000217 const std::unique_ptr<clang::driver::Compilation> Compilation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000218 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Reid Kleckner898229a2013-06-14 17:17:23 +0000219 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000220 &Diagnostics, Compilation.get());
221 if (CC1Args == NULL) {
222 return false;
223 }
Ahmed Charlesb8984322014-03-07 20:03:18 +0000224 std::unique_ptr<clang::CompilerInvocation> Invocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000225 newInvocation(&Diagnostics, *CC1Args));
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000226 for (const auto &It : MappedFileContents) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000227 // Inject the code as the given file name into the preprocessor options.
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000228 auto *Input = llvm::MemoryBuffer::getMemBuffer(It.getValue());
229 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(), Input);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000230 }
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000231 return runInvocation(BinaryName, Compilation.get(), Invocation.release());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000232}
233
Manuel Klimek47c245a2012-04-04 12:07:46 +0000234bool ToolInvocation::runInvocation(
235 const char *BinaryName,
236 clang::driver::Compilation *Compilation,
Sean Silvaf1b49e22013-01-20 01:58:28 +0000237 clang::CompilerInvocation *Invocation) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000238 // Show the invocation, with -v.
239 if (Invocation->getHeaderSearchOpts().Verbose) {
240 llvm::errs() << "clang Invocation:\n";
Hans Wennborgb212b342013-09-12 18:23:34 +0000241 Compilation->getJobs().Print(llvm::errs(), "\n", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000242 llvm::errs() << "\n";
243 }
244
Manuel Klimek64083012013-11-07 23:18:05 +0000245 return Action->runInvocation(Invocation, Files, DiagConsumer);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000246}
247
248bool FrontendActionFactory::runInvocation(CompilerInvocation *Invocation,
Manuel Klimek64083012013-11-07 23:18:05 +0000249 FileManager *Files,
250 DiagnosticConsumer *DiagConsumer) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000251 // Create a compiler instance to handle the actual work.
252 clang::CompilerInstance Compiler;
253 Compiler.setInvocation(Invocation);
254 Compiler.setFileManager(Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000255
Peter Collingbournec689ee72013-11-06 20:12:45 +0000256 // The FrontendAction can have lifetime requirements for Compiler or its
257 // members, and we need to ensure it's deleted earlier than Compiler. So we
Ahmed Charlesb8984322014-03-07 20:03:18 +0000258 // pass it to an std::unique_ptr declared after the Compiler variable.
259 std::unique_ptr<FrontendAction> ScopedToolAction(create());
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000260
Manuel Klimek47c245a2012-04-04 12:07:46 +0000261 // Create the compilers actual diagnostics engine.
Manuel Klimek64083012013-11-07 23:18:05 +0000262 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000263 if (!Compiler.hasDiagnostics())
264 return false;
265
266 Compiler.createSourceManager(*Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000267
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000268 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000269
Manuel Klimek3aad8552012-07-31 13:56:54 +0000270 Files->clearStatCaches();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000271 return Success;
272}
273
Manuel Klimek47c245a2012-04-04 12:07:46 +0000274ClangTool::ClangTool(const CompilationDatabase &Compilations,
275 ArrayRef<std::string> SourcePaths)
Manuel Klimek64083012013-11-07 23:18:05 +0000276 : Files(new FileManager(FileSystemOptions())), DiagConsumer(NULL) {
Pavel Labathdee20c12013-06-06 11:52:19 +0000277 ArgsAdjusters.push_back(new ClangStripOutputAdjuster());
278 ArgsAdjusters.push_back(new ClangSyntaxOnlyAdjuster());
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000279 for (const auto &SourcePath : SourcePaths) {
280 std::string File(getAbsolutePath(SourcePath));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000281
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000282 std::vector<CompileCommand> CompileCommandsForFile =
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000283 Compilations.getCompileCommands(File);
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000284 if (!CompileCommandsForFile.empty()) {
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000285 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
286 CompileCommands.push_back(
287 std::make_pair(File, std::move(CompileCommand)));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000288 }
289 } else {
290 // FIXME: There are two use cases here: doing a fuzzy
291 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
292 // about the .cc files that were not found, and the use case where I
293 // specify all files I want to run over explicitly, where this should
294 // be an error. We'll want to add an option for this.
295 llvm::outs() << "Skipping " << File << ". Command line not found.\n";
296 }
297 }
298}
299
Manuel Klimek64083012013-11-07 23:18:05 +0000300void ClangTool::setDiagnosticConsumer(DiagnosticConsumer *D) {
301 DiagConsumer = D;
302}
303
Manuel Klimek47c245a2012-04-04 12:07:46 +0000304void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
305 MappedFileContents.push_back(std::make_pair(FilePath, Content));
306}
307
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000308void ClangTool::setArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
Manuel Klimekd91ac932013-06-04 14:44:44 +0000309 clearArgumentsAdjusters();
310 appendArgumentsAdjuster(Adjuster);
311}
312
313void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
314 ArgsAdjusters.push_back(Adjuster);
315}
316
317void ClangTool::clearArgumentsAdjusters() {
318 for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I)
319 delete ArgsAdjusters[I];
320 ArgsAdjusters.clear();
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000321}
322
Peter Collingbournec689ee72013-11-06 20:12:45 +0000323int ClangTool::run(ToolAction *Action) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000324 // Exists solely for the purpose of lookup of the resource path.
325 // This just needs to be some symbol in the binary.
326 static int StaticSymbol;
327 // The driver detects the builtin header path based on the path of the
328 // executable.
329 // FIXME: On linux, GetMainExecutable is independent of the value of the
330 // first argument, thus allowing ClangTool and runToolOnCode to just
331 // pass in made-up names here. Make sure this works on other platforms.
332 std::string MainExecutable =
Rafael Espindola9678d272013-06-26 05:03:40 +0000333 llvm::sys::fs::getMainExecutable("clang_tool", &StaticSymbol);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000334
Manuel Klimek47c245a2012-04-04 12:07:46 +0000335 bool ProcessingFailed = false;
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000336 for (const auto &Command : CompileCommands) {
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000337 // FIXME: chdir is thread hostile; on the other hand, creating the same
338 // behavior as chdir is complex: chdir resolves the path once, thus
339 // guaranteeing that all subsequent relative path operations work
340 // on the same path the original chdir resulted in. This makes a difference
Alexander Kornienko8388d242012-06-04 19:02:59 +0000341 // for example on network filesystems, where symlinks might be switched
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000342 // during runtime of the tool. Fixing this depends on having a file system
343 // abstraction that allows openat() style interactions.
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000344 if (chdir(Command.second.Directory.c_str()))
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000345 llvm::report_fatal_error("Cannot chdir into \"" +
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000346 Twine(Command.second.Directory) + "\n!");
347 std::vector<std::string> CommandLine = Command.second.CommandLine;
348 for (ArgumentsAdjuster *Adjuster : ArgsAdjusters)
349 CommandLine = Adjuster->Adjust(CommandLine);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000350 assert(!CommandLine.empty());
351 CommandLine[0] = MainExecutable;
Edwin Vane34794c52013-03-15 20:14:01 +0000352 // FIXME: We need a callback mechanism for the tool writer to output a
353 // customized message for each file.
354 DEBUG({
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000355 llvm::dbgs() << "Processing: " << Command.first << ".\n";
Edwin Vane34794c52013-03-15 20:14:01 +0000356 });
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000357 ToolInvocation Invocation(std::move(CommandLine), Action, Files.getPtr());
Manuel Klimek64083012013-11-07 23:18:05 +0000358 Invocation.setDiagnosticConsumer(DiagConsumer);
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000359 for (const auto &MappedFile : MappedFileContents) {
360 Invocation.mapVirtualFile(MappedFile.first, MappedFile.second);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000361 }
362 if (!Invocation.run()) {
Edwin Vane34794c52013-03-15 20:14:01 +0000363 // FIXME: Diagnostics should be used instead.
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000364 llvm::errs() << "Error while processing " << Command.first << ".\n";
Manuel Klimek47c245a2012-04-04 12:07:46 +0000365 ProcessingFailed = true;
366 }
367 }
368 return ProcessingFailed ? 1 : 0;
369}
370
Peter Collingbournec689ee72013-11-06 20:12:45 +0000371namespace {
372
373class ASTBuilderAction : public ToolAction {
David Blaikie39808ff2014-04-25 14:49:37 +0000374 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000375
376public:
David Blaikie39808ff2014-04-25 14:49:37 +0000377 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000378
Manuel Klimek64083012013-11-07 23:18:05 +0000379 bool runInvocation(CompilerInvocation *Invocation, FileManager *Files,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000380 DiagnosticConsumer *DiagConsumer) override {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000381 // FIXME: This should use the provided FileManager.
David Blaikie103a2de2014-04-25 17:01:33 +0000382 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
Manuel Klimek64083012013-11-07 23:18:05 +0000383 Invocation, CompilerInstance::createDiagnostics(
384 &Invocation->getDiagnosticOpts(), DiagConsumer,
David Blaikie103a2de2014-04-25 17:01:33 +0000385 /*ShouldOwnClient=*/false));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000386 if (!AST)
387 return false;
388
David Blaikie39808ff2014-04-25 14:49:37 +0000389 ASTs.push_back(std::move(AST));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000390 return true;
391 }
392};
393
394}
395
David Blaikie39808ff2014-04-25 14:49:37 +0000396int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000397 ASTBuilderAction Action(ASTs);
398 return run(&Action);
399}
400
David Blaikie103a2de2014-04-25 17:01:33 +0000401std::unique_ptr<ASTUnit> buildASTFromCode(const Twine &Code,
402 const Twine &FileName) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000403 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName);
404}
405
David Blaikie103a2de2014-04-25 17:01:33 +0000406std::unique_ptr<ASTUnit>
407buildASTFromCodeWithArgs(const Twine &Code,
408 const std::vector<std::string> &Args,
409 const Twine &FileName) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000410 SmallString<16> FileNameStorage;
411 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
412
David Blaikie39808ff2014-04-25 14:49:37 +0000413 std::vector<std::unique_ptr<ASTUnit>> ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000414 ASTBuilderAction Action(ASTs);
415 ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), &Action, 0);
416
417 SmallString<1024> CodeStorage;
418 Invocation.mapVirtualFile(FileNameRef,
419 Code.toNullTerminatedStringRef(CodeStorage));
420 if (!Invocation.run())
421 return 0;
422
423 assert(ASTs.size() == 1);
David Blaikie103a2de2014-04-25 17:01:33 +0000424 return std::move(ASTs[0]);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000425}
426
Manuel Klimek47c245a2012-04-04 12:07:46 +0000427} // end namespace tooling
428} // end namespace clang