18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallString.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/Support/Allocator.h"
23#include "llvm/Support/Casting.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/ErrorOr.h"
26#include "llvm/Support/MemoryBuffer.h"
27#include "llvm/Support/Path.h"
28#include "llvm/Support/StringSaver.h"
29#include "llvm/Support/VirtualFileSystem.h"
30#include "llvm/Support/YAMLParser.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/TargetParser/Host.h"
33#include "llvm/TargetParser/Triple.h"
38#include <system_error>
44using namespace tooling;
52class CommandLineArgumentParser {
54 CommandLineArgumentParser(StringRef CommandLine)
55 : Input(CommandLine), Position(Input.begin()-1) {}
57 std::vector<std::string> parse() {
58 bool HasMoreInput =
true;
59 while (HasMoreInput && nextNonWhitespace()) {
61 HasMoreInput = parseStringInto(Argument);
62 CommandLine.push_back(Argument);
70 bool parseStringInto(std::string &String) {
72 if (*Position ==
'"') {
73 if (!parseDoubleQuotedStringInto(String))
return false;
74 }
else if (*Position ==
'\'') {
75 if (!parseSingleQuotedStringInto(String))
return false;
77 if (!parseFreeStringInto(String))
return false;
79 }
while (*Position !=
' ');
83 bool parseDoubleQuotedStringInto(std::string &String) {
84 if (!next())
return false;
85 while (*Position !=
'"') {
86 if (!skipEscapeCharacter())
return false;
87 String.push_back(*Position);
88 if (!next())
return false;
93 bool parseSingleQuotedStringInto(std::string &String) {
94 if (!next())
return false;
95 while (*Position !=
'\'') {
96 String.push_back(*Position);
97 if (!next())
return false;
102 bool parseFreeStringInto(std::string &String) {
104 if (!skipEscapeCharacter())
return false;
105 String.push_back(*Position);
106 if (!next())
return false;
107 }
while (*Position !=
' ' && *Position !=
'"' && *Position !=
'\'');
111 bool skipEscapeCharacter() {
112 if (*Position ==
'\\') {
118 bool nextNonWhitespace() {
120 if (!next())
return false;
121 }
while (*Position ==
' ');
127 return Position != Input.end();
130 const StringRef Input;
131 StringRef::iterator Position;
132 std::vector<std::string> CommandLine;
136 StringRef EscapedCommandLine) {
137 if (Syntax == JSONCommandLineSyntax::AutoDetect) {
140 Syntax = JSONCommandLineSyntax::Windows;
142 Syntax = JSONCommandLineSyntax::Gnu;
146 if (Syntax == JSONCommandLineSyntax::Windows) {
147 llvm::BumpPtrAllocator
Alloc;
148 llvm::StringSaver Saver(Alloc);
150 llvm::cl::TokenizeWindowsCommandLine(EscapedCommandLine, Saver,
T);
151 std::vector<std::string> Result(
T.begin(),
T.end());
154 assert(Syntax == JSONCommandLineSyntax::Gnu);
155 CommandLineArgumentParser parser(EscapedCommandLine);
156 return parser.parse();
162 std::unique_ptr<CompilationDatabase>
165 llvm::sys::path::append(JSONDatabasePath,
"compile_commands.json");
167 JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);
170 std::move(
Base), llvm::vfs::getRealFileSystem())))
179static CompilationDatabasePluginRegistry::Add<JSONCompilationDatabasePlugin>
180X(
"json-compilation-database",
"Reads JSON formatted compilation databases");
192std::unique_ptr<JSONCompilationDatabase>
194 std::string &ErrorMessage,
197 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer =
198 llvm::MemoryBuffer::getFile(FilePath,
false,
201 if (std::error_code
Result = DatabaseBuffer.getError()) {
202 ErrorMessage =
"Error while opening JSON database: " +
Result.message();
205 std::unique_ptr<JSONCompilationDatabase> Database(
207 if (!Database->parse(ErrorMessage))
212std::unique_ptr<JSONCompilationDatabase>
214 std::string &ErrorMessage,
216 std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
217 llvm::MemoryBuffer::getMemBufferCopy(DatabaseString));
218 std::unique_ptr<JSONCompilationDatabase> Database(
220 if (!Database->parse(ErrorMessage))
225std::vector<CompileCommand>
228 llvm::sys::path::native(FilePath, NativeFilePath);
231 llvm::raw_string_ostream ES(Error);
235 const auto CommandsRefI = IndexByFile.find(Match);
236 if (CommandsRefI == IndexByFile.end())
238 std::vector<CompileCommand> Commands;
239 getCommands(CommandsRefI->getValue(), Commands);
243std::vector<std::string>
245 std::vector<std::string>
Result;
246 for (
const auto &CommandRef : IndexByFile)
247 Result.push_back(CommandRef.first().str());
251std::vector<CompileCommand>
253 std::vector<CompileCommand> Commands;
254 getCommands(AllCommands, Commands);
259 Name.consume_back(
".exe");
272 if (Wrapper ==
"distcc" || Wrapper ==
"ccache" || Wrapper ==
"sccache") {
285 (Args[1][0] !=
'-') &&
288 Args.erase(Args.begin());
296static std::vector<std::string>
298 const std::vector<llvm::yaml::ScalarNode *> &
Nodes) {
300 std::vector<std::string> Arguments;
301 if (
Nodes.size() == 1)
302 Arguments = unescapeCommandLine(Syntax,
Nodes[0]->getValue(Storage));
305 Arguments.push_back(std::string(
Node->getValue(Storage)));
312void JSONCompilationDatabase::getCommands(
314 std::vector<CompileCommand> &Commands)
const {
315 for (
const auto &CommandRef : CommandsRef) {
319 auto Output = std::get<3>(CommandRef);
320 Commands.emplace_back(
321 std::get<0>(CommandRef)->getValue(DirectoryStorage),
322 std::get<1>(CommandRef)->getValue(FilenameStorage),
324 Output ? Output->getValue(OutputStorage) :
"");
328bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
329 llvm::yaml::document_iterator I = YAMLStream.begin();
330 if (I == YAMLStream.end()) {
331 ErrorMessage =
"Error while parsing YAML.";
334 llvm::yaml::Node *Root = I->getRoot();
336 ErrorMessage =
"Error while parsing YAML.";
339 auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
341 ErrorMessage =
"Expected array.";
344 for (
auto &NextObject : *Array) {
345 auto *
Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);
347 ErrorMessage =
"Expected object.";
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 = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
357 ErrorMessage =
"Expected strings as key.";
361 StringRef KeyValue = KeyString->getValue(KeyStorage);
362 llvm::yaml::Node *
Value = NextKeyValue.getValue();
364 ErrorMessage =
"Expected value.";
367 auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(
Value);
368 auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(
Value);
369 if (KeyValue ==
"arguments") {
370 if (!SequenceString) {
371 ErrorMessage =
"Expected sequence as value.";
374 Command = std::vector<llvm::yaml::ScalarNode *>();
375 for (
auto &Argument : *SequenceString) {
376 auto *
Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);
378 ErrorMessage =
"Only strings are allowed in 'arguments'.";
381 Command->push_back(Scalar);
385 ErrorMessage =
"Expected string as value.";
388 if (KeyValue ==
"directory") {
389 Directory = ValueString;
390 }
else if (KeyValue ==
"command") {
392 Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
393 }
else if (KeyValue ==
"file") {
395 }
else if (KeyValue ==
"output") {
396 Output = ValueString;
399 (
"Unknown key: \"" + KeyString->getRawValue() +
"\"").str();
405 ErrorMessage =
"Missing key: \"file\".";
409 ErrorMessage =
"Missing key: \"command\" or \"arguments\".";
413 ErrorMessage =
"Missing key: \"directory\".";
419 if (llvm::sys::path::is_relative(
FileName)) {
422 llvm::sys::path::append(AbsolutePath,
FileName);
423 llvm::sys::path::native(AbsolutePath, NativeFilePath);
425 llvm::sys::path::native(
FileName, NativeFilePath);
427 llvm::sys::path::remove_dots(NativeFilePath,
true);
428 auto Cmd = CompileCommandRef(Directory,
File, *Command, Output);
429 IndexByFile[NativeFilePath].push_back(
Cmd);
430 AllCommands.push_back(
Cmd);
431 MatchTrie.
insert(NativeFilePath);
BoundNodesTreeBuilder Nodes
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.
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
const FunctionProtoType * T