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 class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin {
161 std::unique_ptr<CompilationDatabase>
162 loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
163 SmallString<1024> JSONDatabasePath(Directory);
164 llvm::sys::path::append(JSONDatabasePath, "compile_commands.json");
165 return JSONCompilationDatabase::loadFromFile(
166 JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);
172 // Register the JSONCompilationDatabasePlugin with the
173 // CompilationDatabasePluginRegistry using this statically initialized variable.
174 static CompilationDatabasePluginRegistry::Add<JSONCompilationDatabasePlugin>
175 X("json-compilation-database", "Reads JSON formatted compilation databases");
180 // This anchor is used to force the linker to link in the generated object file
181 // and thus register the JSONCompilationDatabasePlugin.
182 volatile int JSONAnchorSource = 0;
184 } // namespace tooling
187 std::unique_ptr<JSONCompilationDatabase>
188 JSONCompilationDatabase::loadFromFile(StringRef FilePath,
189 std::string &ErrorMessage,
190 JSONCommandLineSyntax Syntax) {
191 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer =
192 llvm::MemoryBuffer::getFile(FilePath);
193 if (std::error_code Result = DatabaseBuffer.getError()) {
194 ErrorMessage = "Error while opening JSON database: " + Result.message();
197 std::unique_ptr<JSONCompilationDatabase> Database(
198 new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
199 if (!Database->parse(ErrorMessage))
204 std::unique_ptr<JSONCompilationDatabase>
205 JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,
206 std::string &ErrorMessage,
207 JSONCommandLineSyntax Syntax) {
208 std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
209 llvm::MemoryBuffer::getMemBuffer(DatabaseString));
210 std::unique_ptr<JSONCompilationDatabase> Database(
211 new JSONCompilationDatabase(std::move(DatabaseBuffer), Syntax));
212 if (!Database->parse(ErrorMessage))
217 std::vector<CompileCommand>
218 JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const {
219 SmallString<128> NativeFilePath;
220 llvm::sys::path::native(FilePath, NativeFilePath);
223 llvm::raw_string_ostream ES(Error);
224 StringRef Match = MatchTrie.findEquivalent(NativeFilePath, ES);
227 const auto CommandsRefI = IndexByFile.find(Match);
228 if (CommandsRefI == IndexByFile.end())
230 std::vector<CompileCommand> Commands;
231 getCommands(CommandsRefI->getValue(), Commands);
235 std::vector<std::string>
236 JSONCompilationDatabase::getAllFiles() const {
237 std::vector<std::string> Result;
238 for (const auto &CommandRef : IndexByFile)
239 Result.push_back(CommandRef.first().str());
243 std::vector<CompileCommand>
244 JSONCompilationDatabase::getAllCompileCommands() const {
245 std::vector<CompileCommand> Commands;
246 getCommands(AllCommands, Commands);
250 static std::vector<std::string>
251 nodeToCommandLine(JSONCommandLineSyntax Syntax,
252 const std::vector<llvm::yaml::ScalarNode *> &Nodes) {
253 SmallString<1024> Storage;
254 if (Nodes.size() == 1)
255 return unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage));
256 std::vector<std::string> Arguments;
257 for (const auto *Node : Nodes)
258 Arguments.push_back(Node->getValue(Storage));
262 void JSONCompilationDatabase::getCommands(
263 ArrayRef<CompileCommandRef> CommandsRef,
264 std::vector<CompileCommand> &Commands) const {
265 for (const auto &CommandRef : CommandsRef) {
266 SmallString<8> DirectoryStorage;
267 SmallString<32> FilenameStorage;
268 SmallString<32> OutputStorage;
269 auto Output = std::get<3>(CommandRef);
270 Commands.emplace_back(
271 std::get<0>(CommandRef)->getValue(DirectoryStorage),
272 std::get<1>(CommandRef)->getValue(FilenameStorage),
273 nodeToCommandLine(Syntax, std::get<2>(CommandRef)),
274 Output ? Output->getValue(OutputStorage) : "");
278 bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
279 llvm::yaml::document_iterator I = YAMLStream.begin();
280 if (I == YAMLStream.end()) {
281 ErrorMessage = "Error while parsing YAML.";
284 llvm::yaml::Node *Root = I->getRoot();
286 ErrorMessage = "Error while parsing YAML.";
289 auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
291 ErrorMessage = "Expected array.";
294 for (auto &NextObject : *Array) {
295 auto *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);
297 ErrorMessage = "Expected object.";
300 llvm::yaml::ScalarNode *Directory = nullptr;
301 llvm::Optional<std::vector<llvm::yaml::ScalarNode *>> Command;
302 llvm::yaml::ScalarNode *File = nullptr;
303 llvm::yaml::ScalarNode *Output = nullptr;
304 for (auto& NextKeyValue : *Object) {
305 auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
307 ErrorMessage = "Expected strings as key.";
310 SmallString<10> KeyStorage;
311 StringRef KeyValue = KeyString->getValue(KeyStorage);
312 llvm::yaml::Node *Value = NextKeyValue.getValue();
314 ErrorMessage = "Expected value.";
317 auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value);
318 auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Value);
319 if (KeyValue == "arguments" && !SequenceString) {
320 ErrorMessage = "Expected sequence as value.";
322 } else if (KeyValue != "arguments" && !ValueString) {
323 ErrorMessage = "Expected string as value.";
326 if (KeyValue == "directory") {
327 Directory = ValueString;
328 } else if (KeyValue == "arguments") {
329 Command = std::vector<llvm::yaml::ScalarNode *>();
330 for (auto &Argument : *SequenceString) {
331 auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);
333 ErrorMessage = "Only strings are allowed in 'arguments'.";
336 Command->push_back(Scalar);
338 } else if (KeyValue == "command") {
340 Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
341 } else if (KeyValue == "file") {
343 } else if (KeyValue == "output") {
344 Output = ValueString;
346 ErrorMessage = ("Unknown key: \"" +
347 KeyString->getRawValue() + "\"").str();
352 ErrorMessage = "Missing key: \"file\".";
356 ErrorMessage = "Missing key: \"command\" or \"arguments\".";
360 ErrorMessage = "Missing key: \"directory\".";
363 SmallString<8> FileStorage;
364 StringRef FileName = File->getValue(FileStorage);
365 SmallString<128> NativeFilePath;
366 if (llvm::sys::path::is_relative(FileName)) {
367 SmallString<8> DirectoryStorage;
368 SmallString<128> AbsolutePath(
369 Directory->getValue(DirectoryStorage));
370 llvm::sys::path::append(AbsolutePath, FileName);
371 llvm::sys::path::native(AbsolutePath, NativeFilePath);
373 llvm::sys::path::native(FileName, NativeFilePath);
375 auto Cmd = CompileCommandRef(Directory, File, *Command, Output);
376 IndexByFile[NativeFilePath].push_back(Cmd);
377 AllCommands.push_back(Cmd);
378 MatchTrie.insert(NativeFilePath);