clang 24.0.0git
JSONCompilationDatabase.cpp
Go to the documentation of this file.
1//===- JSONCompilationDatabase.cpp ----------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the JSONCompilationDatabase.
10//
11//===----------------------------------------------------------------------===//
12
14#include "clang/Basic/LLVM.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/Support/Allocator.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/ErrorOr.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/Path.h"
25#include "llvm/Support/StringSaver.h"
26#include "llvm/Support/VirtualFileSystem.h"
27#include "llvm/Support/YAMLParser.h"
28#include "llvm/Support/raw_ostream.h"
29#include "llvm/TargetParser/Host.h"
30#include <cassert>
31#include <memory>
32#include <optional>
33#include <string>
34#include <system_error>
35#include <utility>
36#include <vector>
37
38using namespace clang;
39using namespace tooling;
40
41namespace {
42
43/// A parser for escaped strings of command line arguments.
44///
45/// Assumes \-escaping for quoted arguments (see the documentation of
46/// unescapeCommandLine(...)).
47class CommandLineArgumentParser {
48 public:
49 CommandLineArgumentParser(StringRef CommandLine)
50 : Input(CommandLine), Position(Input.begin()-1) {}
51
52 std::vector<std::string> parse() {
53 bool HasMoreInput = true;
54 while (HasMoreInput && nextNonWhitespace()) {
55 std::string Argument;
56 HasMoreInput = parseStringInto(Argument);
57 CommandLine.push_back(Argument);
58 }
59 return CommandLine;
60 }
61
62 private:
63 // All private methods return true if there is more input available.
64
65 bool parseStringInto(std::string &String) {
66 do {
67 if (*Position == '"') {
68 if (!parseDoubleQuotedStringInto(String)) return false;
69 } else if (*Position == '\'') {
70 if (!parseSingleQuotedStringInto(String)) return false;
71 } else {
72 if (!parseFreeStringInto(String)) return false;
73 }
74 } while (*Position != ' ');
75 return true;
76 }
77
78 bool parseDoubleQuotedStringInto(std::string &String) {
79 if (!next()) return false;
80 while (*Position != '"') {
81 if (!skipEscapeCharacter()) return false;
82 String.push_back(*Position);
83 if (!next()) return false;
84 }
85 return next();
86 }
87
88 bool parseSingleQuotedStringInto(std::string &String) {
89 if (!next()) return false;
90 while (*Position != '\'') {
91 String.push_back(*Position);
92 if (!next()) return false;
93 }
94 return next();
95 }
96
97 bool parseFreeStringInto(std::string &String) {
98 do {
99 if (!skipEscapeCharacter()) return false;
100 String.push_back(*Position);
101 if (!next()) return false;
102 } while (*Position != ' ' && *Position != '"' && *Position != '\'');
103 return true;
104 }
105
106 bool skipEscapeCharacter() {
107 if (*Position == '\\') {
108 return next();
109 }
110 return true;
111 }
112
113 bool nextNonWhitespace() {
114 do {
115 if (!next()) return false;
116 } while (*Position == ' ');
117 return true;
118 }
119
120 bool next() {
121 ++Position;
122 return Position != Input.end();
123 }
124
125 const StringRef Input;
126 StringRef::iterator Position;
127 std::vector<std::string> CommandLine;
128};
129
130std::vector<std::string> unescapeCommandLine(JSONCommandLineSyntax Syntax,
131 StringRef EscapedCommandLine) {
132 if (Syntax == JSONCommandLineSyntax::AutoDetect) {
133#ifdef _WIN32
134 // Assume Windows command line parsing on Win32
135 Syntax = JSONCommandLineSyntax::Windows;
136#else
137 Syntax = JSONCommandLineSyntax::Gnu;
138#endif
139 }
140
141 if (Syntax == JSONCommandLineSyntax::Windows) {
142 llvm::BumpPtrAllocator Alloc;
143 llvm::StringSaver Saver(Alloc);
145 llvm::cl::TokenizeWindowsCommandLine(EscapedCommandLine, Saver, T);
146 std::vector<std::string> Result(T.begin(), T.end());
147 return Result;
148 }
149 assert(Syntax == JSONCommandLineSyntax::Gnu);
150 CommandLineArgumentParser parser(EscapedCommandLine);
151 return parser.parse();
152}
153
154// This plugin locates a nearby compile_command.json file, and also infers
155// compile commands for files not present in the database.
156class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin {
157 std::unique_ptr<CompilationDatabase>
158 loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
159 SmallString<1024> JSONDatabasePath(Directory);
160 llvm::sys::path::append(JSONDatabasePath, "compile_commands.json");
162 JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);
165 std::move(Base), llvm::vfs::getRealFileSystem())))
166 : nullptr;
167 }
168};
169
170} // namespace
171
172// Register the JSONCompilationDatabasePlugin with the
173// CompilationDatabasePluginRegistry using this statically initialized variable.
174static CompilationDatabasePluginRegistry::Add<JSONCompilationDatabasePlugin>
175X("json-compilation-database", "Reads JSON formatted compilation databases");
176
177namespace clang {
178namespace tooling {
179
180// This anchor is used to force the linker to link in the generated object file
181// and thus register the JSONCompilationDatabasePlugin.
182volatile int JSONAnchorSource = 0;
183
184} // namespace tooling
185} // namespace clang
186
187std::unique_ptr<JSONCompilationDatabase>
189 std::string &ErrorMessage,
190 JSONCommandLineSyntax Syntax) {
191 // Don't mmap: if we're a long-lived process, the build system may overwrite.
192 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer =
193 llvm::MemoryBuffer::getFile(FilePath, /*IsText=*/false,
194 /*RequiresNullTerminator=*/true,
195 /*IsVolatile=*/true);
196 if (std::error_code Result = DatabaseBuffer.getError()) {
197 ErrorMessage = "Error while opening JSON database: " + Result.message();
198 return nullptr;
199 }
200 SmallString<128> BaseDirectory(FilePath);
201 llvm::sys::fs::make_absolute(BaseDirectory);
202 llvm::sys::path::remove_filename(BaseDirectory);
203 std::unique_ptr<JSONCompilationDatabase> Database(
204 new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
205 if (!Database->parse(BaseDirectory, ErrorMessage))
206 return nullptr;
207 return Database;
208}
209
210std::unique_ptr<JSONCompilationDatabase>
212 StringRef DatabaseString,
213 std::string &ErrorMessage,
214 JSONCommandLineSyntax Syntax) {
215 std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
216 llvm::MemoryBuffer::getMemBufferCopy(DatabaseString));
217 std::unique_ptr<JSONCompilationDatabase> Database(
218 new JSONCompilationDatabase(std::move(DatabaseBuffer), Syntax));
219 if (!Database->parse(BaseDirectory, ErrorMessage))
220 return nullptr;
221 return Database;
222}
223
224std::vector<CompileCommand>
226 SmallString<128> NativeFilePath;
227 llvm::sys::path::native(FilePath, NativeFilePath);
228
229 std::string Error;
230 llvm::raw_string_ostream ES(Error);
231 StringRef Match = MatchTrie.findEquivalent(NativeFilePath, ES);
232 if (Match.empty())
233 return {};
234 const auto CommandsRefI = IndexByFile.find(Match);
235 if (CommandsRefI == IndexByFile.end())
236 return {};
237 std::vector<CompileCommand> Commands;
238 getCommands(CommandsRefI->getValue(), Commands);
239 return Commands;
240}
241
242std::vector<std::string>
244 std::vector<std::string> Result;
245 for (const auto &CommandRef : IndexByFile)
246 Result.push_back(CommandRef.first().str());
247 return Result;
248}
249
250std::vector<CompileCommand>
252 std::vector<CompileCommand> Commands;
253 getCommands(AllCommands, Commands);
254 return Commands;
255}
256
257static llvm::StringRef stripExecutableExtension(llvm::StringRef Name) {
258 Name.consume_back(".exe");
259 return Name;
260}
261
262// There are compiler-wrappers (ccache, distcc) that take the "real"
263// compiler as an argument, e.g. distcc gcc -O3 foo.c.
264// These end up in compile_commands.json when people set CC="distcc gcc".
265// Clang's driver doesn't understand this, so we need to unwrap.
266static bool unwrapCommand(std::vector<std::string> &Args) {
267 if (Args.size() < 2)
268 return false;
269 StringRef Wrapper =
270 stripExecutableExtension(llvm::sys::path::filename(Args.front()));
271 if (Wrapper == "distcc" || Wrapper == "ccache" || Wrapper == "sccache") {
272 // Most of these wrappers support being invoked 3 ways:
273 // `distcc g++ file.c` This is the mode we're trying to match.
274 // We need to drop `distcc`.
275 // `distcc file.c` This acts like compiler is cc or similar.
276 // Clang's driver can handle this, no change needed.
277 // `g++ file.c` g++ is a symlink to distcc.
278 // We don't even notice this case, and all is well.
279 //
280 // We need to distinguish between the first and second case.
281 // The wrappers themselves don't take flags, so Args[1] is a compiler flag,
282 // an input file, or a compiler. Inputs have extensions, compilers don't.
283 bool HasCompiler =
284 (Args[1][0] != '-') &&
285 !llvm::sys::path::has_extension(stripExecutableExtension(Args[1]));
286 if (HasCompiler) {
287 Args.erase(Args.begin());
288 return true;
289 }
290 // If !HasCompiler, wrappers act like GCC. Fine: so do we.
291 }
292 return false;
293}
294
295static std::vector<std::string>
297 const std::vector<llvm::yaml::ScalarNode *> &Nodes) {
298 SmallString<1024> Storage;
299 std::vector<std::string> Arguments;
300 if (Nodes.size() == 1)
301 Arguments = unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage));
302 else
303 for (const auto *Node : Nodes)
304 Arguments.push_back(std::string(Node->getValue(Storage)));
305 // There may be multiple wrappers: using distcc and ccache together is common.
306 while (unwrapCommand(Arguments))
307 ;
308 return Arguments;
309}
310
311void JSONCompilationDatabase::getCommands(
312 ArrayRef<CompileCommandRef> CommandsRef,
313 std::vector<CompileCommand> &Commands) const {
314 for (const auto &CommandRef : CommandsRef) {
315 SmallString<32> FilenameStorage;
316 SmallString<32> OutputStorage;
317 auto Output = std::get<3>(CommandRef);
318 Commands.emplace_back(std::get<0>(CommandRef),
319 std::get<1>(CommandRef)->getValue(FilenameStorage),
320 nodeToCommandLine(Syntax, std::get<2>(CommandRef)),
321 Output ? Output->getValue(OutputStorage) : "");
322 }
323}
324
325bool JSONCompilationDatabase::parse(StringRef BaseDirectory,
326 std::string &ErrorMessage) {
327 llvm::yaml::document_iterator I = YAMLStream.begin();
328 if (I == YAMLStream.end()) {
329 ErrorMessage = "Error while parsing YAML.";
330 return false;
331 }
332 llvm::yaml::Node *Root = I->getRoot();
333 if (!Root) {
334 ErrorMessage = "Error while parsing YAML.";
335 return false;
336 }
337 auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
338 if (!Array) {
339 ErrorMessage = "Expected array.";
340 return false;
341 }
342 // Most entries share a directory, so avoid recomputing it for each one.
343 StringRef PrevRawDirectory, DirectoryName;
344 for (auto &NextObject : *Array) {
345 auto *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);
346 if (!Object) {
347 ErrorMessage = "Expected object.";
348 return false;
349 }
350 llvm::yaml::ScalarNode *Directory = nullptr;
351 std::optional<std::vector<llvm::yaml::ScalarNode *>> Command;
352 llvm::yaml::ScalarNode *File = nullptr;
353 llvm::yaml::ScalarNode *Output = nullptr;
354 for (auto& NextKeyValue : *Object) {
355 auto *KeyString =
356 dyn_cast_if_present<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
357 if (!KeyString) {
358 ErrorMessage = "Expected strings as key.";
359 return false;
360 }
361 SmallString<10> KeyStorage;
362 StringRef KeyValue = KeyString->getValue(KeyStorage);
363 llvm::yaml::Node *Value = NextKeyValue.getValue();
364 if (!Value) {
365 ErrorMessage = "Expected value.";
366 return false;
367 }
368 auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value);
369 auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Value);
370 if (KeyValue == "arguments") {
371 if (!SequenceString) {
372 ErrorMessage = "Expected sequence as value.";
373 return false;
374 }
375 Command = std::vector<llvm::yaml::ScalarNode *>();
376 for (auto &Argument : *SequenceString) {
377 auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);
378 if (!Scalar) {
379 ErrorMessage = "Only strings are allowed in 'arguments'.";
380 return false;
381 }
382 Command->push_back(Scalar);
383 }
384 } else {
385 if (!ValueString) {
386 ErrorMessage = "Expected string as value.";
387 return false;
388 }
389 if (KeyValue == "directory") {
390 Directory = ValueString;
391 } else if (KeyValue == "command") {
392 if (!Command)
393 Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
394 } else if (KeyValue == "file") {
395 File = ValueString;
396 } else if (KeyValue == "output") {
397 Output = ValueString;
398 } else {
399 ErrorMessage =
400 ("Unknown key: \"" + KeyString->getRawValue() + "\"").str();
401 return false;
402 }
403 }
404 }
405 if (!File) {
406 ErrorMessage = "Missing key: \"file\".";
407 return false;
408 }
409 if (!Command) {
410 ErrorMessage = "Missing key: \"command\" or \"arguments\".";
411 return false;
412 }
413 if (!Directory) {
414 ErrorMessage = "Missing key: \"directory\".";
415 return false;
416 }
417 if (Directory->getRawValue() != PrevRawDirectory) {
418 PrevRawDirectory = Directory->getRawValue();
419 SmallString<8> DirectoryStorage;
420 SmallString<128> DirectoryPath(Directory->getValue(DirectoryStorage));
421 if (!BaseDirectory.empty() && !DirectoryPath.empty() &&
422 !llvm::sys::path::is_absolute(DirectoryPath)) {
423 llvm::sys::path::make_absolute(BaseDirectory, DirectoryPath);
424 llvm::sys::path::remove_dots(DirectoryPath);
425 }
426 DirectoryName = Directories.insert(DirectoryPath).first->getKey();
427 }
428 SmallString<8> FileStorage;
429 StringRef FileName = File->getValue(FileStorage);
430 SmallString<128> NativeFilePath;
431 if (llvm::sys::path::is_relative(FileName)) {
432 SmallString<128> AbsolutePath(DirectoryName);
433 llvm::sys::path::append(AbsolutePath, FileName);
434 llvm::sys::path::native(AbsolutePath, NativeFilePath);
435 } else {
436 llvm::sys::path::native(FileName, NativeFilePath);
437 }
438 llvm::sys::path::remove_dots(NativeFilePath, /*remove_dot_dot=*/true);
439 auto Cmd = CompileCommandRef(DirectoryName, File, *Command, Output);
440 IndexByFile[NativeFilePath].push_back(Cmd);
441 AllCommands.push_back(Cmd);
442 MatchTrie.insert(NativeFilePath);
443 }
444 return true;
445}
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
static std::vector< std::string > nodeToCommandLine(JSONCommandLineSyntax Syntax, const std::vector< llvm::yaml::ScalarNode * > &Nodes)
static bool unwrapCommand(std::vector< std::string > &Args)
static llvm::StringRef stripExecutableExtension(llvm::StringRef Name)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
llvm::json::Object Object
llvm::json::Array Array
Interface for compilation database plugins.
std::vector< CompileCommand > getCompileCommands(StringRef FilePath) const override
Returns all compile commands in which the specified file was compiled.
std::vector< std::string > getAllFiles() const override
Returns the list of all files available in the compilation database.
static std::unique_ptr< JSONCompilationDatabase > loadFromFile(StringRef FilePath, std::string &ErrorMessage, JSONCommandLineSyntax Syntax)
Loads a JSON compilation database from the specified file.
static std::unique_ptr< JSONCompilationDatabase > loadFromBuffer(StringRef BaseDirectory, StringRef DatabaseString, std::string &ErrorMessage, JSONCommandLineSyntax Syntax)
Loads a JSON compilation database from a data buffer.
std::vector< CompileCommand > getAllCompileCommands() const override
Returns all compile commands for all the files in the compilation database.
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition Interp.h:3920
JSONCommandLineSyntax
A JSON based compilation database.
std::unique_ptr< CompilationDatabase > expandResponseFiles(std::unique_ptr< CompilationDatabase > Base, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS)
Returns a wrapped CompilationDatabase that will expand all rsp(response) files on commandline returne...
std::unique_ptr< CompilationDatabase > inferTargetAndDriverMode(std::unique_ptr< CompilationDatabase > Base)
Returns a wrapped CompilationDatabase that will add -target and -mode flags to commandline when they ...
std::unique_ptr< CompilationDatabase > inferMissingCompileCommands(std::unique_ptr< CompilationDatabase >)
Returns a wrapped CompilationDatabase that defers to the provided one, but getCompileCommands() will ...
Top level wrappers for InstallAPI frontend operations.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:823
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T