1 //===- JSONCompilationDatabase.cpp ----------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the JSONCompilationDatabase.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Tooling/JSONCompilationDatabase.h"
15 #include "clang/Basic/LLVM.h"
16 #include "clang/Tooling/CompilationDatabase.h"
17 #include "clang/Tooling/CompilationDatabasePluginRegistry.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/Support/Allocator.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/ErrorOr.h"
27 #include "llvm/Support/Host.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/StringSaver.h"
31 #include "llvm/Support/YAMLParser.h"
32 #include "llvm/Support/raw_ostream.h"
36 #include <system_error>
41 using namespace clang;
42 using namespace tooling;
46 /// A parser for escaped strings of command line arguments.
48 /// Assumes \-escaping for quoted arguments (see the documentation of
49 /// unescapeCommandLine(...)).
50 class CommandLineArgumentParser {
52 CommandLineArgumentParser(StringRef CommandLine)
53 : Input(CommandLine), Position(Input.begin()-1) {}
55 std::vector<std::string> parse() {
56 bool HasMoreInput = true;
57 while (HasMoreInput && nextNonWhitespace()) {
59 HasMoreInput = parseStringInto(Argument);
60 CommandLine.push_back(Argument);
66 // All private methods return true if there is more input available.
68 bool parseStringInto(std::string &String) {
70 if (*Position == '"') {
71 if (!parseDoubleQuotedStringInto(String)) return false;
72 } else if (*Position == '\'') {
73 if (!parseSingleQuotedStringInto(String)) return false;
75 if (!parseFreeStringInto(String)) return false;
77 } while (*Position != ' ');
81 bool parseDoubleQuotedStringInto(std::string &String) {
82 if (!next()) return false;
83 while (*Position != '"') {
84 if (!skipEscapeCharacter()) return false;
85 String.push_back(*Position);
86 if (!next()) return false;
91 bool parseSingleQuotedStringInto(std::string &String) {
92 if (!next()) return false;
93 while (*Position != '\'') {
94 String.push_back(*Position);
95 if (!next()) return false;
100 bool parseFreeStringInto(std::string &String) {
102 if (!skipEscapeCharacter()) return false;
103 String.push_back(*Position);
104 if (!next()) return false;
105 } while (*Position != ' ' && *Position != '"' && *Position != '\'');
109 bool skipEscapeCharacter() {
110 if (*Position == '\\') {
116 bool nextNonWhitespace() {
118 if (!next()) return false;
119 } while (*Position == ' ');
125 return Position != Input.end();
128 const StringRef Input;
129 StringRef::iterator Position;
130 std::vector<std::string> CommandLine;
133 std::vector<std::string> unescapeCommandLine(JSONCommandLineSyntax Syntax,
134 StringRef EscapedCommandLine) {
135 if (Syntax == JSONCommandLineSyntax::AutoDetect) {
136 Syntax = JSONCommandLineSyntax::Gnu;
137 llvm::Triple Triple(llvm::sys::getProcessTriple());
138 if (Triple.getOS() == llvm::Triple::OSType::Win32) {
139 // Assume Windows command line parsing on Win32 unless the triple
140 // explicitly tells us otherwise.
141 if (!Triple.hasEnvironment() ||
142 Triple.getEnvironment() == llvm::Triple::EnvironmentType::MSVC)
143 Syntax = JSONCommandLineSyntax::Windows;
147 if (Syntax == JSONCommandLineSyntax::Windows) {
148 llvm::BumpPtrAllocator Alloc;
149 llvm::StringSaver Saver(Alloc);
150 llvm::SmallVector<const char *, 64> T;
151 llvm::cl::TokenizeWindowsCommandLine(EscapedCommandLine, Saver, T);
152 std::vector<std::string> Result(T.begin(), T.end());
155 assert(Syntax == JSONCommandLineSyntax::Gnu);
156 CommandLineArgumentParser parser(EscapedCommandLine);
157 return parser.parse();
160 // This plugin locates a nearby compile_command.json file, and also infers
161 // compile commands for files not present in the database.
162 class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin {
163 std::unique_ptr<CompilationDatabase>
164 loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
165 SmallString<1024> JSONDatabasePath(Directory);
166 llvm::sys::path::append(JSONDatabasePath, "compile_commands.json");
167 auto Base = JSONCompilationDatabase::loadFromFile(
168 JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);
169 return Base ? inferMissingCompileCommands(std::move(Base)) : nullptr;
175 // Register the JSONCompilationDatabasePlugin with the
176 // CompilationDatabasePluginRegistry using this statically initialized variable.
177 static CompilationDatabasePluginRegistry::Add<JSONCompilationDatabasePlugin>
178 X("json-compilation-database", "Reads JSON formatted compilation databases");
183 // This anchor is used to force the linker to link in the generated object file
184 // and thus register the JSONCompilationDatabasePlugin.
185 volatile int JSONAnchorSource = 0;
187 } // namespace tooling
190 std::unique_ptr<JSONCompilationDatabase>
191 JSONCompilationDatabase::loadFromFile(StringRef FilePath,
192 std::string &ErrorMessage,
193 JSONCommandLineSyntax Syntax) {
194 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer =
195 llvm::MemoryBuffer::getFile(FilePath);
196 if (std::error_code Result = DatabaseBuffer.getError()) {
197 ErrorMessage = "Error while opening JSON database: " + Result.message();
200 std::unique_ptr<JSONCompilationDatabase> Database(
201 new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
202 if (!Database->parse(ErrorMessage))
207 std::unique_ptr<JSONCompilationDatabase>
208 JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,
209 std::string &ErrorMessage,
210 JSONCommandLineSyntax Syntax) {
211 std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
212 llvm::MemoryBuffer::getMemBuffer(DatabaseString));
213 std::unique_ptr<JSONCompilationDatabase> Database(
214 new JSONCompilationDatabase(std::move(DatabaseBuffer), Syntax));
215 if (!Database->parse(ErrorMessage))
220 std::vector<CompileCommand>
221 JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const {
222 SmallString<128> NativeFilePath;
223 llvm::sys::path::native(FilePath, NativeFilePath);
226 llvm::raw_string_ostream ES(Error);
227 StringRef Match = MatchTrie.findEquivalent(NativeFilePath, ES);
230 const auto CommandsRefI = IndexByFile.find(Match);
231 if (CommandsRefI == IndexByFile.end())
233 std::vector<CompileCommand> Commands;
234 getCommands(CommandsRefI->getValue(), Commands);
238 std::vector<std::string>
239 JSONCompilationDatabase::getAllFiles() const {
240 std::vector<std::string> Result;
241 for (const auto &CommandRef : IndexByFile)
242 Result.push_back(CommandRef.first().str());
246 std::vector<CompileCommand>
247 JSONCompilationDatabase::getAllCompileCommands() const {
248 std::vector<CompileCommand> Commands;
249 getCommands(AllCommands, Commands);
253 static std::vector<std::string>
254 nodeToCommandLine(JSONCommandLineSyntax Syntax,
255 const std::vector<llvm::yaml::ScalarNode *> &Nodes) {
256 SmallString<1024> Storage;
257 if (Nodes.size() == 1)
258 return unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage));
259 std::vector<std::string> Arguments;
260 for (const auto *Node : Nodes)
261 Arguments.push_back(Node->getValue(Storage));
265 void JSONCompilationDatabase::getCommands(
266 ArrayRef<CompileCommandRef> CommandsRef,
267 std::vector<CompileCommand> &Commands) const {
268 for (const auto &CommandRef : CommandsRef) {
269 SmallString<8> DirectoryStorage;
270 SmallString<32> FilenameStorage;
271 SmallString<32> OutputStorage;
272 auto Output = std::get<3>(CommandRef);
273 Commands.emplace_back(
274 std::get<0>(CommandRef)->getValue(DirectoryStorage),
275 std::get<1>(CommandRef)->getValue(FilenameStorage),
276 nodeToCommandLine(Syntax, std::get<2>(CommandRef)),
277 Output ? Output->getValue(OutputStorage) : "");
281 bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
282 llvm::yaml::document_iterator I = YAMLStream.begin();
283 if (I == YAMLStream.end()) {
284 ErrorMessage = "Error while parsing YAML.";
287 llvm::yaml::Node *Root = I->getRoot();
289 ErrorMessage = "Error while parsing YAML.";
292 auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
294 ErrorMessage = "Expected array.";
297 for (auto &NextObject : *Array) {
298 auto *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);
300 ErrorMessage = "Expected object.";
303 llvm::yaml::ScalarNode *Directory = nullptr;
304 llvm::Optional<std::vector<llvm::yaml::ScalarNode *>> Command;
305 llvm::yaml::ScalarNode *File = nullptr;
306 llvm::yaml::ScalarNode *Output = nullptr;
307 for (auto& NextKeyValue : *Object) {
308 auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
310 ErrorMessage = "Expected strings as key.";
313 SmallString<10> KeyStorage;
314 StringRef KeyValue = KeyString->getValue(KeyStorage);
315 llvm::yaml::Node *Value = NextKeyValue.getValue();
317 ErrorMessage = "Expected value.";
320 auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value);
321 auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Value);
322 if (KeyValue == "arguments" && !SequenceString) {
323 ErrorMessage = "Expected sequence as value.";
325 } else if (KeyValue != "arguments" && !ValueString) {
326 ErrorMessage = "Expected string as value.";
329 if (KeyValue == "directory") {
330 Directory = ValueString;
331 } else if (KeyValue == "arguments") {
332 Command = std::vector<llvm::yaml::ScalarNode *>();
333 for (auto &Argument : *SequenceString) {
334 auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);
336 ErrorMessage = "Only strings are allowed in 'arguments'.";
339 Command->push_back(Scalar);
341 } else if (KeyValue == "command") {
343 Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
344 } else if (KeyValue == "file") {
346 } else if (KeyValue == "output") {
347 Output = ValueString;
349 ErrorMessage = ("Unknown key: \"" +
350 KeyString->getRawValue() + "\"").str();
355 ErrorMessage = "Missing key: \"file\".";
359 ErrorMessage = "Missing key: \"command\" or \"arguments\".";
363 ErrorMessage = "Missing key: \"directory\".";
366 SmallString<8> FileStorage;
367 StringRef FileName = File->getValue(FileStorage);
368 SmallString<128> NativeFilePath;
369 if (llvm::sys::path::is_relative(FileName)) {
370 SmallString<8> DirectoryStorage;
371 SmallString<128> AbsolutePath(
372 Directory->getValue(DirectoryStorage));
373 llvm::sys::path::append(AbsolutePath, FileName);
374 llvm::sys::path::native(AbsolutePath, NativeFilePath);
376 llvm::sys::path::native(FileName, NativeFilePath);
378 auto Cmd = CompileCommandRef(Directory, File, *Command, Output);
379 IndexByFile[NativeFilePath].push_back(Cmd);
380 AllCommands.push_back(Cmd);
381 MatchTrie.insert(NativeFilePath);