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/Tooling/CompilationDatabase.h"
16 #include "clang/Tooling/CompilationDatabasePluginRegistry.h"
17 #include "clang/Tooling/Tooling.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/Support/Allocator.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/StringSaver.h"
23 #include <system_error>
30 /// \brief A parser for escaped strings of command line arguments.
32 /// Assumes \-escaping for quoted arguments (see the documentation of
33 /// unescapeCommandLine(...)).
34 class CommandLineArgumentParser {
36 CommandLineArgumentParser(StringRef CommandLine)
37 : Input(CommandLine), Position(Input.begin()-1) {}
39 std::vector<std::string> parse() {
40 bool HasMoreInput = true;
41 while (HasMoreInput && nextNonWhitespace()) {
43 HasMoreInput = parseStringInto(Argument);
44 CommandLine.push_back(Argument);
50 // All private methods return true if there is more input available.
52 bool parseStringInto(std::string &String) {
54 if (*Position == '"') {
55 if (!parseDoubleQuotedStringInto(String)) return false;
56 } else if (*Position == '\'') {
57 if (!parseSingleQuotedStringInto(String)) return false;
59 if (!parseFreeStringInto(String)) return false;
61 } while (*Position != ' ');
65 bool parseDoubleQuotedStringInto(std::string &String) {
66 if (!next()) return false;
67 while (*Position != '"') {
68 if (!skipEscapeCharacter()) return false;
69 String.push_back(*Position);
70 if (!next()) return false;
75 bool parseSingleQuotedStringInto(std::string &String) {
76 if (!next()) return false;
77 while (*Position != '\'') {
78 String.push_back(*Position);
79 if (!next()) return false;
84 bool parseFreeStringInto(std::string &String) {
86 if (!skipEscapeCharacter()) return false;
87 String.push_back(*Position);
88 if (!next()) return false;
89 } while (*Position != ' ' && *Position != '"' && *Position != '\'');
93 bool skipEscapeCharacter() {
94 if (*Position == '\\') {
100 bool nextNonWhitespace() {
102 if (!next()) return false;
103 } while (*Position == ' ');
109 return Position != Input.end();
112 const StringRef Input;
113 StringRef::iterator Position;
114 std::vector<std::string> CommandLine;
117 std::vector<std::string> unescapeCommandLine(JSONCommandLineSyntax Syntax,
118 StringRef EscapedCommandLine) {
119 if (Syntax == JSONCommandLineSyntax::AutoDetect) {
120 Syntax = JSONCommandLineSyntax::Gnu;
121 llvm::Triple Triple(llvm::sys::getProcessTriple());
122 if (Triple.getOS() == llvm::Triple::OSType::Win32) {
123 // Assume Windows command line parsing on Win32 unless the triple
124 // explicitly tells us otherwise.
125 if (!Triple.hasEnvironment() ||
126 Triple.getEnvironment() == llvm::Triple::EnvironmentType::MSVC)
127 Syntax = JSONCommandLineSyntax::Windows;
131 if (Syntax == JSONCommandLineSyntax::Windows) {
132 llvm::BumpPtrAllocator Alloc;
133 llvm::StringSaver Saver(Alloc);
134 llvm::SmallVector<const char *, 64> T;
135 llvm::cl::TokenizeWindowsCommandLine(EscapedCommandLine, Saver, T);
136 std::vector<std::string> Result(T.begin(), T.end());
139 assert(Syntax == JSONCommandLineSyntax::Gnu);
140 CommandLineArgumentParser parser(EscapedCommandLine);
141 return parser.parse();
144 class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin {
145 std::unique_ptr<CompilationDatabase>
146 loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
147 SmallString<1024> JSONDatabasePath(Directory);
148 llvm::sys::path::append(JSONDatabasePath, "compile_commands.json");
149 std::unique_ptr<CompilationDatabase> Database(
150 JSONCompilationDatabase::loadFromFile(
151 JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect));
160 // Register the JSONCompilationDatabasePlugin with the
161 // CompilationDatabasePluginRegistry using this statically initialized variable.
162 static CompilationDatabasePluginRegistry::Add<JSONCompilationDatabasePlugin>
163 X("json-compilation-database", "Reads JSON formatted compilation databases");
165 // This anchor is used to force the linker to link in the generated object file
166 // and thus register the JSONCompilationDatabasePlugin.
167 volatile int JSONAnchorSource = 0;
169 std::unique_ptr<JSONCompilationDatabase>
170 JSONCompilationDatabase::loadFromFile(StringRef FilePath,
171 std::string &ErrorMessage,
172 JSONCommandLineSyntax Syntax) {
173 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer =
174 llvm::MemoryBuffer::getFile(FilePath);
175 if (std::error_code Result = DatabaseBuffer.getError()) {
176 ErrorMessage = "Error while opening JSON database: " + Result.message();
179 std::unique_ptr<JSONCompilationDatabase> Database(
180 new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
181 if (!Database->parse(ErrorMessage))
186 std::unique_ptr<JSONCompilationDatabase>
187 JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,
188 std::string &ErrorMessage,
189 JSONCommandLineSyntax Syntax) {
190 std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
191 llvm::MemoryBuffer::getMemBuffer(DatabaseString));
192 std::unique_ptr<JSONCompilationDatabase> Database(
193 new JSONCompilationDatabase(std::move(DatabaseBuffer), Syntax));
194 if (!Database->parse(ErrorMessage))
199 std::vector<CompileCommand>
200 JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const {
201 SmallString<128> NativeFilePath;
202 llvm::sys::path::native(FilePath, NativeFilePath);
205 llvm::raw_string_ostream ES(Error);
206 StringRef Match = MatchTrie.findEquivalent(NativeFilePath, ES);
208 return std::vector<CompileCommand>();
209 llvm::StringMap< std::vector<CompileCommandRef> >::const_iterator
210 CommandsRefI = IndexByFile.find(Match);
211 if (CommandsRefI == IndexByFile.end())
212 return std::vector<CompileCommand>();
213 std::vector<CompileCommand> Commands;
214 getCommands(CommandsRefI->getValue(), Commands);
218 std::vector<std::string>
219 JSONCompilationDatabase::getAllFiles() const {
220 std::vector<std::string> Result;
222 llvm::StringMap< std::vector<CompileCommandRef> >::const_iterator
223 CommandsRefI = IndexByFile.begin();
224 const llvm::StringMap< std::vector<CompileCommandRef> >::const_iterator
225 CommandsRefEnd = IndexByFile.end();
226 for (; CommandsRefI != CommandsRefEnd; ++CommandsRefI) {
227 Result.push_back(CommandsRefI->first().str());
233 std::vector<CompileCommand>
234 JSONCompilationDatabase::getAllCompileCommands() const {
235 std::vector<CompileCommand> Commands;
236 getCommands(AllCommands, Commands);
240 static std::vector<std::string>
241 nodeToCommandLine(JSONCommandLineSyntax Syntax,
242 const std::vector<llvm::yaml::ScalarNode *> &Nodes) {
243 SmallString<1024> Storage;
244 if (Nodes.size() == 1) {
245 return unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage));
247 std::vector<std::string> Arguments;
248 for (auto *Node : Nodes) {
249 Arguments.push_back(Node->getValue(Storage));
254 void JSONCompilationDatabase::getCommands(
255 ArrayRef<CompileCommandRef> CommandsRef,
256 std::vector<CompileCommand> &Commands) const {
257 for (int I = 0, E = CommandsRef.size(); I != E; ++I) {
258 SmallString<8> DirectoryStorage;
259 SmallString<32> FilenameStorage;
260 SmallString<32> OutputStorage;
261 auto Output = std::get<3>(CommandsRef[I]);
262 Commands.emplace_back(
263 std::get<0>(CommandsRef[I])->getValue(DirectoryStorage),
264 std::get<1>(CommandsRef[I])->getValue(FilenameStorage),
265 nodeToCommandLine(Syntax, std::get<2>(CommandsRef[I])),
266 Output ? Output->getValue(OutputStorage) : "");
270 bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
271 llvm::yaml::document_iterator I = YAMLStream.begin();
272 if (I == YAMLStream.end()) {
273 ErrorMessage = "Error while parsing YAML.";
276 llvm::yaml::Node *Root = I->getRoot();
278 ErrorMessage = "Error while parsing YAML.";
281 llvm::yaml::SequenceNode *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
283 ErrorMessage = "Expected array.";
286 for (auto& NextObject : *Array) {
287 llvm::yaml::MappingNode *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);
289 ErrorMessage = "Expected object.";
292 llvm::yaml::ScalarNode *Directory = nullptr;
293 llvm::Optional<std::vector<llvm::yaml::ScalarNode *>> Command;
294 llvm::yaml::ScalarNode *File = nullptr;
295 llvm::yaml::ScalarNode *Output = nullptr;
296 for (auto& NextKeyValue : *Object) {
297 llvm::yaml::ScalarNode *KeyString =
298 dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
300 ErrorMessage = "Expected strings as key.";
303 SmallString<10> KeyStorage;
304 StringRef KeyValue = KeyString->getValue(KeyStorage);
305 llvm::yaml::Node *Value = NextKeyValue.getValue();
307 ErrorMessage = "Expected value.";
310 llvm::yaml::ScalarNode *ValueString =
311 dyn_cast<llvm::yaml::ScalarNode>(Value);
312 llvm::yaml::SequenceNode *SequenceString =
313 dyn_cast<llvm::yaml::SequenceNode>(Value);
314 if (KeyValue == "arguments" && !SequenceString) {
315 ErrorMessage = "Expected sequence as value.";
317 } else if (KeyValue != "arguments" && !ValueString) {
318 ErrorMessage = "Expected string as value.";
321 if (KeyValue == "directory") {
322 Directory = ValueString;
323 } else if (KeyValue == "arguments") {
324 Command = std::vector<llvm::yaml::ScalarNode *>();
325 for (auto &Argument : *SequenceString) {
326 auto Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);
328 ErrorMessage = "Only strings are allowed in 'arguments'.";
331 Command->push_back(Scalar);
333 } else if (KeyValue == "command") {
335 Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
336 } else if (KeyValue == "file") {
338 } else if (KeyValue == "output") {
339 Output = ValueString;
341 ErrorMessage = ("Unknown key: \"" +
342 KeyString->getRawValue() + "\"").str();
347 ErrorMessage = "Missing key: \"file\".";
351 ErrorMessage = "Missing key: \"command\" or \"arguments\".";
355 ErrorMessage = "Missing key: \"directory\".";
358 SmallString<8> FileStorage;
359 StringRef FileName = File->getValue(FileStorage);
360 SmallString<128> NativeFilePath;
361 if (llvm::sys::path::is_relative(FileName)) {
362 SmallString<8> DirectoryStorage;
363 SmallString<128> AbsolutePath(
364 Directory->getValue(DirectoryStorage));
365 llvm::sys::path::append(AbsolutePath, FileName);
366 llvm::sys::path::native(AbsolutePath, NativeFilePath);
368 llvm::sys::path::native(FileName, NativeFilePath);
370 auto Cmd = CompileCommandRef(Directory, File, *Command, Output);
371 IndexByFile[NativeFilePath].push_back(Cmd);
372 AllCommands.push_back(Cmd);
373 MatchTrie.insert(NativeFilePath);
378 } // end namespace tooling
379 } // end namespace clang