blob: 20284daaba9e0e6b67405878ede59fe79b19bee2 [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"
16#include "clang/Tooling/CompilationDatabase.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/Support/Host.h"
19#include "llvm/Support/raw_ostream.h"
20#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Tool.h"
23#include "clang/Frontend/CompilerInstance.h"
24#include "clang/Frontend/FrontendAction.h"
25#include "clang/Frontend/FrontendDiagnostic.h"
26#include "clang/Frontend/TextDiagnosticPrinter.h"
27
28namespace clang {
29namespace tooling {
30
31FrontendActionFactory::~FrontendActionFactory() {}
32
33// FIXME: This file contains structural duplication with other parts of the
34// code that sets up a compiler to run tools on it, and we should refactor
35// it to be based on the same framework.
36
37/// \brief Builds a clang driver initialized for running clang tools.
38static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics,
39 const char *BinaryName) {
40 const std::string DefaultOutputName = "a.out";
41 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
42 BinaryName, llvm::sys::getDefaultTargetTriple(),
43 DefaultOutputName, false, *Diagnostics);
44 CompilerDriver->setTitle("clang_based_tool");
45 return CompilerDriver;
46}
47
48/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
49///
50/// Returns NULL on error.
51static const clang::driver::ArgStringList *getCC1Arguments(
52 clang::DiagnosticsEngine *Diagnostics,
53 clang::driver::Compilation *Compilation) {
54 // We expect to get back exactly one Command job, if we didn't something
55 // failed. Extract that job from the Compilation.
56 const clang::driver::JobList &Jobs = Compilation->getJobs();
57 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
58 llvm::SmallString<256> error_msg;
59 llvm::raw_svector_ostream error_stream(error_msg);
60 Compilation->PrintJob(error_stream, Compilation->getJobs(), "; ", true);
61 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
62 << error_stream.str();
63 return NULL;
64 }
65
66 // The one job we find should be to invoke clang again.
67 const clang::driver::Command *Cmd =
68 cast<clang::driver::Command>(*Jobs.begin());
69 if (StringRef(Cmd->getCreator().getName()) != "clang") {
70 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
71 return NULL;
72 }
73
74 return &Cmd->getArguments();
75}
76
77/// \brief Returns a clang build invocation initialized from the CC1 flags.
78static clang::CompilerInvocation *newInvocation(
79 clang::DiagnosticsEngine *Diagnostics,
80 const clang::driver::ArgStringList &CC1Args) {
81 assert(!CC1Args.empty() && "Must at least contain the program name!");
82 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
83 clang::CompilerInvocation::CreateFromArgs(
84 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
85 *Diagnostics);
86 Invocation->getFrontendOpts().DisableFree = false;
87 return Invocation;
88}
89
90bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
91 const Twine &FileName) {
92 SmallString<16> FileNameStorage;
93 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
94 const char *const CommandLine[] = {
95 "clang-tool", "-fsyntax-only", FileNameRef.data()
96 };
97 FileManager Files((FileSystemOptions()));
98 ToolInvocation Invocation(
99 std::vector<std::string>(
100 CommandLine,
101 CommandLine + llvm::array_lengthof(CommandLine)),
102 ToolAction, &Files);
103
104 SmallString<1024> CodeStorage;
105 Invocation.mapVirtualFile(FileNameRef,
106 Code.toNullTerminatedStringRef(CodeStorage));
107 return Invocation.run();
108}
109
110/// \brief Returns the absolute path of 'File', by prepending it with
111/// 'BaseDirectory' if 'File' is not absolute.
112///
113/// Otherwise returns 'File'.
114/// If 'File' starts with "./", the returned path will not contain the "./".
115/// Otherwise, the returned path will contain the literal path-concatenation of
116/// 'BaseDirectory' and 'File'.
117///
118/// \param File Either an absolute or relative path.
119/// \param BaseDirectory An absolute path.
120static std::string getAbsolutePath(
121 StringRef File, StringRef BaseDirectory) {
122 assert(llvm::sys::path::is_absolute(BaseDirectory));
123 if (llvm::sys::path::is_absolute(File)) {
124 return File;
125 }
126 StringRef RelativePath(File);
127 if (RelativePath.startswith("./")) {
128 RelativePath = RelativePath.substr(strlen("./"));
129 }
130 llvm::SmallString<1024> AbsolutePath(BaseDirectory);
131 llvm::sys::path::append(AbsolutePath, RelativePath);
132 return AbsolutePath.str();
133}
134
135ToolInvocation::ToolInvocation(
136 ArrayRef<std::string> CommandLine, FrontendAction *ToolAction,
137 FileManager *Files)
138 : CommandLine(CommandLine.vec()), ToolAction(ToolAction), Files(Files) {
139}
140
141void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
142 MappedFileContents[FilePath] = Content;
143}
144
145bool ToolInvocation::run() {
146 std::vector<const char*> Argv;
147 for (int I = 0, E = CommandLine.size(); I != E; ++I)
148 Argv.push_back(CommandLine[I].c_str());
149 const char *const BinaryName = Argv[0];
150 DiagnosticOptions DefaultDiagnosticOptions;
151 TextDiagnosticPrinter DiagnosticPrinter(
152 llvm::errs(), DefaultDiagnosticOptions);
153 DiagnosticsEngine Diagnostics(llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>(
154 new DiagnosticIDs()), &DiagnosticPrinter, false);
155
156 const llvm::OwningPtr<clang::driver::Driver> Driver(
157 newDriver(&Diagnostics, BinaryName));
158 // Since the input might only be virtual, don't check whether it exists.
159 Driver->setCheckInputsExist(false);
160 const llvm::OwningPtr<clang::driver::Compilation> Compilation(
161 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
162 const clang::driver::ArgStringList *const CC1Args = getCC1Arguments(
163 &Diagnostics, Compilation.get());
164 if (CC1Args == NULL) {
165 return false;
166 }
167 llvm::OwningPtr<clang::CompilerInvocation> Invocation(
168 newInvocation(&Diagnostics, *CC1Args));
169 return runInvocation(BinaryName, Compilation.get(),
170 Invocation.take(), *CC1Args, ToolAction.take());
171}
172
173// Exists solely for the purpose of lookup of the resource path.
174static int StaticSymbol;
175
176bool ToolInvocation::runInvocation(
177 const char *BinaryName,
178 clang::driver::Compilation *Compilation,
179 clang::CompilerInvocation *Invocation,
180 const clang::driver::ArgStringList &CC1Args,
181 clang::FrontendAction *ToolAction) {
182 llvm::OwningPtr<clang::FrontendAction> ScopedToolAction(ToolAction);
183 // Show the invocation, with -v.
184 if (Invocation->getHeaderSearchOpts().Verbose) {
185 llvm::errs() << "clang Invocation:\n";
186 Compilation->PrintJob(llvm::errs(), Compilation->getJobs(), "\n", true);
187 llvm::errs() << "\n";
188 }
189
190 // Create a compiler instance to handle the actual work.
191 clang::CompilerInstance Compiler;
192 Compiler.setInvocation(Invocation);
193 Compiler.setFileManager(Files);
194 // FIXME: What about LangOpts?
195
196 // Create the compilers actual diagnostics engine.
197 Compiler.createDiagnostics(CC1Args.size(),
198 const_cast<char**>(CC1Args.data()));
199 if (!Compiler.hasDiagnostics())
200 return false;
201
202 Compiler.createSourceManager(*Files);
203 addFileMappingsTo(Compiler.getSourceManager());
204
205 // Infer the builtin include path if unspecified.
206 if (Compiler.getHeaderSearchOpts().UseBuiltinIncludes &&
207 Compiler.getHeaderSearchOpts().ResourceDir.empty()) {
208 // This just needs to be some symbol in the binary.
209 void *const SymbolAddr = &StaticSymbol;
210 Compiler.getHeaderSearchOpts().ResourceDir =
211 clang::CompilerInvocation::GetResourcesPath(BinaryName, SymbolAddr);
212 }
213
214 const bool Success = Compiler.ExecuteAction(*ToolAction);
215
216 Compiler.resetAndLeakFileManager();
217 return Success;
218}
219
220void ToolInvocation::addFileMappingsTo(SourceManager &Sources) {
221 for (llvm::StringMap<StringRef>::const_iterator
222 It = MappedFileContents.begin(), End = MappedFileContents.end();
223 It != End; ++It) {
224 // Inject the code as the given file name into the preprocessor options.
225 const llvm::MemoryBuffer *Input =
226 llvm::MemoryBuffer::getMemBuffer(It->getValue());
227 // FIXME: figure out what '0' stands for.
228 const FileEntry *FromFile = Files->getVirtualFile(
229 It->getKey(), Input->getBufferSize(), 0);
230 // FIXME: figure out memory management ('true').
231 Sources.overrideFileContents(FromFile, Input, true);
232 }
233}
234
235ClangTool::ClangTool(const CompilationDatabase &Compilations,
236 ArrayRef<std::string> SourcePaths)
237 : Files((FileSystemOptions())) {
238 StringRef BaseDirectory(::getenv("PWD"));
239 for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
240 llvm::SmallString<1024> File(getAbsolutePath(
241 SourcePaths[I], BaseDirectory));
242
243 std::vector<CompileCommand> CompileCommands =
244 Compilations.getCompileCommands(File.str());
245 if (!CompileCommands.empty()) {
246 for (int I = 0, E = CompileCommands.size(); I != E; ++I) {
247 CompileCommand &Command = CompileCommands[I];
248 if (!Command.Directory.empty()) {
249 // FIXME: What should happen if CommandLine includes -working-directory
250 // as well?
251 Command.CommandLine.push_back(
252 "-working-directory=" + Command.Directory);
253 }
254 CommandLines.push_back(std::make_pair(File.str(), Command.CommandLine));
255 }
256 } else {
257 // FIXME: There are two use cases here: doing a fuzzy
258 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
259 // about the .cc files that were not found, and the use case where I
260 // specify all files I want to run over explicitly, where this should
261 // be an error. We'll want to add an option for this.
262 llvm::outs() << "Skipping " << File << ". Command line not found.\n";
263 }
264 }
265}
266
267void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
268 MappedFileContents.push_back(std::make_pair(FilePath, Content));
269}
270
271int ClangTool::run(FrontendActionFactory *ActionFactory) {
272 bool ProcessingFailed = false;
273 for (unsigned I = 0; I < CommandLines.size(); ++I) {
274 std::string File = CommandLines[I].first;
275 std::vector<std::string> &CommandLine = CommandLines[I].second;
276 llvm::outs() << "Processing: " << File << ".\n";
277 ToolInvocation Invocation(CommandLine, ActionFactory->create(), &Files);
278 for (int I = 0, E = MappedFileContents.size(); I != E; ++I) {
279 Invocation.mapVirtualFile(MappedFileContents[I].first,
280 MappedFileContents[I].second);
281 }
282 if (!Invocation.run()) {
283 llvm::outs() << "Error while processing " << File << ".\n";
284 ProcessingFailed = true;
285 }
286 }
287 return ProcessingFailed ? 1 : 0;
288}
289
290} // end namespace tooling
291} // end namespace clang