blob: 95ef03eb561f82fce3c64c1f8368f1605be44621 [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"
Alp Toker1d257e12014-06-04 03:28:55 +000027#include "llvm/Config/llvm-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) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000057 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Alp Toker1761f112014-05-15 22:26:36 +000058 BinaryName, llvm::sys::getDefaultTargetTriple(), *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();
Justin Bogneraab97922014-10-03 01:04:53 +000072 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();
Craig Topperccbc35e2014-05-20 04:51:16 +000078 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000079 }
80
81 // The one job we find should be to invoke clang again.
David Blaikiec11bf802014-09-04 16:04:28 +000082 const clang::driver::Command &Cmd =
Justin Bogneraab97922014-10-03 01:04:53 +000083 cast<clang::driver::Command>(*Jobs.begin());
David Blaikiec11bf802014-09-04 16:04:28 +000084 if (StringRef(Cmd.getCreator().getName()) != "clang") {
Manuel Klimek47c245a2012-04-04 12:07:46 +000085 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
Craig Topperccbc35e2014-05-20 04:51:16 +000086 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000087 }
88
David Blaikiec11bf802014-09-04 16:04:28 +000089 return &Cmd.getArguments();
Manuel Klimek47c245a2012-04-04 12:07:46 +000090}
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,
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000126 const Twine &FileName,
127 const FileContentMappings &VirtualMappedFiles) {
128
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()));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000133 ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef),
134 ToolAction, Files.get());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000135
136 SmallString<1024> CodeStorage;
137 Invocation.mapVirtualFile(FileNameRef,
138 Code.toNullTerminatedStringRef(CodeStorage));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000139
140 for (auto &FilenameWithContent : VirtualMappedFiles) {
141 Invocation.mapVirtualFile(FilenameWithContent.first,
142 FilenameWithContent.second);
143 }
144
Manuel Klimek47c245a2012-04-04 12:07:46 +0000145 return Invocation.run();
146}
147
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000148std::string getAbsolutePath(StringRef File) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000149 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000150 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000151 if (RelativePath.startswith("./")) {
152 RelativePath = RelativePath.substr(strlen("./"));
153 }
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000154
155 SmallString<1024> AbsolutePath = RelativePath;
Rafael Espindolac0809172014-06-12 14:02:15 +0000156 std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000157 assert(!EC);
Rafael Espindola0b8e4a12013-08-10 04:25:53 +0000158 (void)EC;
Benjamin Kramer2d4d8cb2013-09-11 11:23:15 +0000159 llvm::sys::path::native(AbsolutePath);
160 return AbsolutePath.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000161}
162
Peter Collingbournec689ee72013-11-06 20:12:45 +0000163namespace {
164
165class SingleFrontendActionFactory : public FrontendActionFactory {
166 FrontendAction *Action;
167
168public:
169 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
170
Craig Topperfb6b25b2014-03-15 04:29:04 +0000171 FrontendAction *create() override { return Action; }
Peter Collingbournec689ee72013-11-06 20:12:45 +0000172};
173
174}
175
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000176ToolInvocation::ToolInvocation(std::vector<std::string> CommandLine,
Peter Collingbournec689ee72013-11-06 20:12:45 +0000177 ToolAction *Action, FileManager *Files)
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000178 : CommandLine(std::move(CommandLine)),
Manuel Klimek64083012013-11-07 23:18:05 +0000179 Action(Action),
180 OwnsAction(false),
181 Files(Files),
Craig Topperccbc35e2014-05-20 04:51:16 +0000182 DiagConsumer(nullptr) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000183
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000184ToolInvocation::ToolInvocation(std::vector<std::string> CommandLine,
Peter Collingbournec689ee72013-11-06 20:12:45 +0000185 FrontendAction *FAction, FileManager *Files)
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000186 : CommandLine(std::move(CommandLine)),
Manuel Klimek64083012013-11-07 23:18:05 +0000187 Action(new SingleFrontendActionFactory(FAction)),
188 OwnsAction(true),
189 Files(Files),
Craig Topperccbc35e2014-05-20 04:51:16 +0000190 DiagConsumer(nullptr) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000191
192ToolInvocation::~ToolInvocation() {
193 if (OwnsAction)
194 delete Action;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000195}
196
197void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000198 SmallString<1024> PathStorage;
199 llvm::sys::path::native(FilePath, PathStorage);
200 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000201}
202
203bool ToolInvocation::run() {
204 std::vector<const char*> Argv;
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000205 for (const std::string &Str : CommandLine)
206 Argv.push_back(Str.c_str());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000207 const char *const BinaryName = Argv[0];
Douglas Gregor811db4e2012-10-23 22:26:28 +0000208 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000209 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000210 llvm::errs(), &*DiagOpts);
211 DiagnosticsEngine Diagnostics(
Manuel Klimek64083012013-11-07 23:18:05 +0000212 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
213 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000214
Ahmed Charlesb8984322014-03-07 20:03:18 +0000215 const std::unique_ptr<clang::driver::Driver> Driver(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000216 newDriver(&Diagnostics, BinaryName));
217 // Since the input might only be virtual, don't check whether it exists.
218 Driver->setCheckInputsExist(false);
Ahmed Charlesb8984322014-03-07 20:03:18 +0000219 const std::unique_ptr<clang::driver::Compilation> Compilation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000220 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Reid Kleckner898229a2013-06-14 17:17:23 +0000221 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000222 &Diagnostics, Compilation.get());
Craig Topperccbc35e2014-05-20 04:51:16 +0000223 if (!CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000224 return false;
225 }
Ahmed Charlesb8984322014-03-07 20:03:18 +0000226 std::unique_ptr<clang::CompilerInvocation> Invocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000227 newInvocation(&Diagnostics, *CC1Args));
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000228 for (const auto &It : MappedFileContents) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000229 // Inject the code as the given file name into the preprocessor options.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000230 std::unique_ptr<llvm::MemoryBuffer> Input =
231 llvm::MemoryBuffer::getMemBuffer(It.getValue());
232 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
233 Input.release());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000234 }
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000235 return runInvocation(BinaryName, Compilation.get(), Invocation.release());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000236}
237
Manuel Klimek47c245a2012-04-04 12:07:46 +0000238bool ToolInvocation::runInvocation(
239 const char *BinaryName,
240 clang::driver::Compilation *Compilation,
Sean Silvaf1b49e22013-01-20 01:58:28 +0000241 clang::CompilerInvocation *Invocation) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000242 // Show the invocation, with -v.
243 if (Invocation->getHeaderSearchOpts().Verbose) {
244 llvm::errs() << "clang Invocation:\n";
Hans Wennborgb212b342013-09-12 18:23:34 +0000245 Compilation->getJobs().Print(llvm::errs(), "\n", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000246 llvm::errs() << "\n";
247 }
248
Manuel Klimek64083012013-11-07 23:18:05 +0000249 return Action->runInvocation(Invocation, Files, DiagConsumer);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000250}
251
252bool FrontendActionFactory::runInvocation(CompilerInvocation *Invocation,
Manuel Klimek64083012013-11-07 23:18:05 +0000253 FileManager *Files,
254 DiagnosticConsumer *DiagConsumer) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000255 // Create a compiler instance to handle the actual work.
256 clang::CompilerInstance Compiler;
257 Compiler.setInvocation(Invocation);
258 Compiler.setFileManager(Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000259
Peter Collingbournec689ee72013-11-06 20:12:45 +0000260 // The FrontendAction can have lifetime requirements for Compiler or its
261 // members, and we need to ensure it's deleted earlier than Compiler. So we
Ahmed Charlesb8984322014-03-07 20:03:18 +0000262 // pass it to an std::unique_ptr declared after the Compiler variable.
263 std::unique_ptr<FrontendAction> ScopedToolAction(create());
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000264
Alp Toker77273fc2014-05-16 13:45:29 +0000265 // Create the compiler's actual diagnostics engine.
Manuel Klimek64083012013-11-07 23:18:05 +0000266 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000267 if (!Compiler.hasDiagnostics())
268 return false;
269
270 Compiler.createSourceManager(*Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000271
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000272 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000273
Manuel Klimek3aad8552012-07-31 13:56:54 +0000274 Files->clearStatCaches();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000275 return Success;
276}
277
Manuel Klimek47c245a2012-04-04 12:07:46 +0000278ClangTool::ClangTool(const CompilationDatabase &Compilations,
279 ArrayRef<std::string> SourcePaths)
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000280 : Compilations(Compilations), SourcePaths(SourcePaths),
281 Files(new FileManager(FileSystemOptions())), DiagConsumer(nullptr) {
Benjamin Kramer90e0fd82014-09-24 11:47:42 +0000282 appendArgumentsAdjuster(new ClangStripOutputAdjuster());
283 appendArgumentsAdjuster(new ClangSyntaxOnlyAdjuster());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000284}
285
Benjamin Kramer90e0fd82014-09-24 11:47:42 +0000286ClangTool::~ClangTool() {}
Manuel Klimek64083012013-11-07 23:18:05 +0000287
Manuel Klimek47c245a2012-04-04 12:07:46 +0000288void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
289 MappedFileContents.push_back(std::make_pair(FilePath, Content));
290}
291
Manuel Klimekd91ac932013-06-04 14:44:44 +0000292void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
Benjamin Kramer90e0fd82014-09-24 11:47:42 +0000293 ArgsAdjusters.push_back(std::unique_ptr<ArgumentsAdjuster>(Adjuster));
Manuel Klimekd91ac932013-06-04 14:44:44 +0000294}
295
296void ClangTool::clearArgumentsAdjusters() {
Manuel Klimekd91ac932013-06-04 14:44:44 +0000297 ArgsAdjusters.clear();
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000298}
299
Peter Collingbournec689ee72013-11-06 20:12:45 +0000300int ClangTool::run(ToolAction *Action) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000301 // Exists solely for the purpose of lookup of the resource path.
302 // This just needs to be some symbol in the binary.
303 static int StaticSymbol;
304 // The driver detects the builtin header path based on the path of the
305 // executable.
306 // FIXME: On linux, GetMainExecutable is independent of the value of the
307 // first argument, thus allowing ClangTool and runToolOnCode to just
308 // pass in made-up names here. Make sure this works on other platforms.
309 std::string MainExecutable =
Rafael Espindola9678d272013-06-26 05:03:40 +0000310 llvm::sys::fs::getMainExecutable("clang_tool", &StaticSymbol);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000311
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000312 llvm::SmallString<128> InitialDirectory;
313 if (std::error_code EC = llvm::sys::fs::current_path(InitialDirectory))
314 llvm::report_fatal_error("Cannot detect current path: " +
315 Twine(EC.message()));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000316 bool ProcessingFailed = false;
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000317 for (const auto &SourcePath : SourcePaths) {
318 std::string File(getAbsolutePath(SourcePath));
319
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000320 // Currently implementations of CompilationDatabase::getCompileCommands can
321 // change the state of the file system (e.g. prepare generated headers), so
322 // this method needs to run right before we invoke the tool, as the next
323 // file may require a different (incompatible) state of the file system.
324 //
325 // FIXME: Make the compilation database interface more explicit about the
326 // requirements to the order of invocation of its members.
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000327 std::vector<CompileCommand> CompileCommandsForFile =
328 Compilations.getCompileCommands(File);
329 if (CompileCommandsForFile.empty()) {
330 // FIXME: There are two use cases here: doing a fuzzy
331 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
332 // about the .cc files that were not found, and the use case where I
333 // specify all files I want to run over explicitly, where this should
334 // be an error. We'll want to add an option for this.
335 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
336 continue;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000337 }
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000338 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
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
343 // difference for example on network filesystems, where symlinks might be
344 // switched during runtime of the tool. Fixing this depends on having a
345 // file system abstraction that allows openat() style interactions.
346 if (chdir(CompileCommand.Directory.c_str()))
347 llvm::report_fatal_error("Cannot chdir into \"" +
348 Twine(CompileCommand.Directory) + "\n!");
349 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
Benjamin Kramer90e0fd82014-09-24 11:47:42 +0000350 for (const auto &Adjuster : ArgsAdjusters)
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000351 CommandLine = Adjuster->Adjust(CommandLine);
352 assert(!CommandLine.empty());
353 CommandLine[0] = MainExecutable;
354 // FIXME: We need a callback mechanism for the tool writer to output a
355 // customized message for each file.
356 DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
357 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get());
358 Invocation.setDiagnosticConsumer(DiagConsumer);
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000359 for (const auto &MappedFile : MappedFileContents)
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000360 Invocation.mapVirtualFile(MappedFile.first, MappedFile.second);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000361 if (!Invocation.run()) {
362 // FIXME: Diagnostics should be used instead.
363 llvm::errs() << "Error while processing " << File << ".\n";
364 ProcessingFailed = true;
365 }
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000366 // Return to the initial directory to correctly resolve next file by
367 // relative path.
368 if (chdir(InitialDirectory.c_str()))
369 llvm::report_fatal_error("Cannot chdir into \"" +
370 Twine(InitialDirectory) + "\n!");
Manuel Klimek47c245a2012-04-04 12:07:46 +0000371 }
372 }
373 return ProcessingFailed ? 1 : 0;
374}
375
Peter Collingbournec689ee72013-11-06 20:12:45 +0000376namespace {
377
378class ASTBuilderAction : public ToolAction {
David Blaikie39808ff2014-04-25 14:49:37 +0000379 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000380
381public:
David Blaikie39808ff2014-04-25 14:49:37 +0000382 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000383
Manuel Klimek64083012013-11-07 23:18:05 +0000384 bool runInvocation(CompilerInvocation *Invocation, FileManager *Files,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000385 DiagnosticConsumer *DiagConsumer) override {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000386 // FIXME: This should use the provided FileManager.
David Blaikie103a2de2014-04-25 17:01:33 +0000387 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
Manuel Klimek64083012013-11-07 23:18:05 +0000388 Invocation, CompilerInstance::createDiagnostics(
389 &Invocation->getDiagnosticOpts(), DiagConsumer,
David Blaikie103a2de2014-04-25 17:01:33 +0000390 /*ShouldOwnClient=*/false));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000391 if (!AST)
392 return false;
393
David Blaikie39808ff2014-04-25 14:49:37 +0000394 ASTs.push_back(std::move(AST));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000395 return true;
396 }
397};
398
399}
400
David Blaikie39808ff2014-04-25 14:49:37 +0000401int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000402 ASTBuilderAction Action(ASTs);
403 return run(&Action);
404}
405
David Blaikie103a2de2014-04-25 17:01:33 +0000406std::unique_ptr<ASTUnit> buildASTFromCode(const Twine &Code,
407 const Twine &FileName) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000408 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName);
409}
410
David Blaikie103a2de2014-04-25 17:01:33 +0000411std::unique_ptr<ASTUnit>
412buildASTFromCodeWithArgs(const Twine &Code,
413 const std::vector<std::string> &Args,
414 const Twine &FileName) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000415 SmallString<16> FileNameStorage;
416 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
417
David Blaikie39808ff2014-04-25 14:49:37 +0000418 std::vector<std::unique_ptr<ASTUnit>> ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000419 ASTBuilderAction Action(ASTs);
Craig Topperccbc35e2014-05-20 04:51:16 +0000420 ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), &Action,
421 nullptr);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000422
423 SmallString<1024> CodeStorage;
424 Invocation.mapVirtualFile(FileNameRef,
425 Code.toNullTerminatedStringRef(CodeStorage));
426 if (!Invocation.run())
Craig Topperccbc35e2014-05-20 04:51:16 +0000427 return nullptr;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000428
429 assert(ASTs.size() == 1);
David Blaikie103a2de2014-04-25 17:01:33 +0000430 return std::move(ASTs[0]);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000431}
432
Manuel Klimek47c245a2012-04-04 12:07:46 +0000433} // end namespace tooling
434} // end namespace clang