blob: 8b8bd293851f3713ed9f2d4e6c2f9223e81744d2 [file] [log] [blame]
Daniel Jasper7fd90b02012-08-24 05:50:27 +00001//===--- JSONCompilationDatabase.cpp - ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the JSONCompilationDatabase.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Tooling/JSONCompilationDatabase.h"
Daniel Jasper7fd90b02012-08-24 05:50:27 +000015#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/Path.h"
Stephen Hinesc568f1e2014-07-21 00:47:37 -070020#include <system_error>
Daniel Jasper7fd90b02012-08-24 05:50:27 +000021
22namespace clang {
23namespace tooling {
24
25namespace {
26
27/// \brief A parser for escaped strings of command line arguments.
28///
29/// Assumes \-escaping for quoted arguments (see the documentation of
30/// unescapeCommandLine(...)).
31class CommandLineArgumentParser {
32 public:
33 CommandLineArgumentParser(StringRef CommandLine)
34 : Input(CommandLine), Position(Input.begin()-1) {}
35
36 std::vector<std::string> parse() {
37 bool HasMoreInput = true;
38 while (HasMoreInput && nextNonWhitespace()) {
39 std::string Argument;
40 HasMoreInput = parseStringInto(Argument);
41 CommandLine.push_back(Argument);
42 }
43 return CommandLine;
44 }
45
46 private:
47 // All private methods return true if there is more input available.
48
49 bool parseStringInto(std::string &String) {
50 do {
51 if (*Position == '"') {
Peter Collingbourneb88d9482013-03-02 06:00:16 +000052 if (!parseDoubleQuotedStringInto(String)) return false;
53 } else if (*Position == '\'') {
54 if (!parseSingleQuotedStringInto(String)) return false;
Daniel Jasper7fd90b02012-08-24 05:50:27 +000055 } else {
56 if (!parseFreeStringInto(String)) return false;
57 }
58 } while (*Position != ' ');
59 return true;
60 }
61
Peter Collingbourneb88d9482013-03-02 06:00:16 +000062 bool parseDoubleQuotedStringInto(std::string &String) {
Daniel Jasper7fd90b02012-08-24 05:50:27 +000063 if (!next()) return false;
64 while (*Position != '"') {
65 if (!skipEscapeCharacter()) return false;
66 String.push_back(*Position);
67 if (!next()) return false;
68 }
69 return next();
70 }
71
Peter Collingbourneb88d9482013-03-02 06:00:16 +000072 bool parseSingleQuotedStringInto(std::string &String) {
73 if (!next()) return false;
74 while (*Position != '\'') {
75 String.push_back(*Position);
76 if (!next()) return false;
77 }
78 return next();
79 }
80
Daniel Jasper7fd90b02012-08-24 05:50:27 +000081 bool parseFreeStringInto(std::string &String) {
82 do {
83 if (!skipEscapeCharacter()) return false;
84 String.push_back(*Position);
85 if (!next()) return false;
Peter Collingbourneb88d9482013-03-02 06:00:16 +000086 } while (*Position != ' ' && *Position != '"' && *Position != '\'');
Daniel Jasper7fd90b02012-08-24 05:50:27 +000087 return true;
88 }
89
90 bool skipEscapeCharacter() {
91 if (*Position == '\\') {
92 return next();
93 }
94 return true;
95 }
96
97 bool nextNonWhitespace() {
98 do {
99 if (!next()) return false;
100 } while (*Position == ' ');
101 return true;
102 }
103
104 bool next() {
105 ++Position;
106 return Position != Input.end();
107 }
108
109 const StringRef Input;
110 StringRef::iterator Position;
111 std::vector<std::string> CommandLine;
112};
113
114std::vector<std::string> unescapeCommandLine(
115 StringRef EscapedCommandLine) {
116 CommandLineArgumentParser parser(EscapedCommandLine);
117 return parser.parse();
118}
119
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000120class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin {
Stephen Hines651f13c2014-04-23 16:59:28 -0700121 CompilationDatabase *loadFromDirectory(StringRef Directory,
122 std::string &ErrorMessage) override {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000123 SmallString<1024> JSONDatabasePath(Directory);
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000124 llvm::sys::path::append(JSONDatabasePath, "compile_commands.json");
Stephen Hines651f13c2014-04-23 16:59:28 -0700125 std::unique_ptr<CompilationDatabase> Database(
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000126 JSONCompilationDatabase::loadFromFile(JSONDatabasePath, ErrorMessage));
127 if (!Database)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700128 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700129 return Database.release();
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000130 }
131};
132
Craig Topperbc540252013-07-01 06:34:58 +0000133} // end namespace
134
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000135// Register the JSONCompilationDatabasePlugin with the
136// CompilationDatabasePluginRegistry using this statically initialized variable.
137static CompilationDatabasePluginRegistry::Add<JSONCompilationDatabasePlugin>
138X("json-compilation-database", "Reads JSON formatted compilation databases");
139
140// This anchor is used to force the linker to link in the generated object file
141// and thus register the JSONCompilationDatabasePlugin.
NAKAMURA Takumi916978a2012-08-24 10:39:28 +0000142volatile int JSONAnchorSource = 0;
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000143
144JSONCompilationDatabase *
145JSONCompilationDatabase::loadFromFile(StringRef FilePath,
146 std::string &ErrorMessage) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700147 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer =
148 llvm::MemoryBuffer::getFile(FilePath);
149 if (std::error_code Result = DatabaseBuffer.getError()) {
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000150 ErrorMessage = "Error while opening JSON database: " + Result.message();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700151 return nullptr;
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000152 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700153 std::unique_ptr<JSONCompilationDatabase> Database(
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700154 new JSONCompilationDatabase(DatabaseBuffer->release()));
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000155 if (!Database->parse(ErrorMessage))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700156 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700157 return Database.release();
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000158}
159
160JSONCompilationDatabase *
161JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,
162 std::string &ErrorMessage) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700163 std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000164 llvm::MemoryBuffer::getMemBuffer(DatabaseString));
Stephen Hines651f13c2014-04-23 16:59:28 -0700165 std::unique_ptr<JSONCompilationDatabase> Database(
166 new JSONCompilationDatabase(DatabaseBuffer.release()));
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000167 if (!Database->parse(ErrorMessage))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700168 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700169 return Database.release();
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000170}
171
172std::vector<CompileCommand>
173JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000174 SmallString<128> NativeFilePath;
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000175 llvm::sys::path::native(FilePath, NativeFilePath);
Stephen Hines651f13c2014-04-23 16:59:28 -0700176
Daniel Jasperd3420c92012-10-08 16:08:15 +0000177 std::string Error;
178 llvm::raw_string_ostream ES(Error);
179 StringRef Match = MatchTrie.findEquivalent(NativeFilePath.str(), ES);
Arnaud A. de Grandmaison9cd506b2013-01-12 18:37:52 +0000180 if (Match.empty())
Daniel Jasperd3420c92012-10-08 16:08:15 +0000181 return std::vector<CompileCommand>();
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000182 llvm::StringMap< std::vector<CompileCommandRef> >::const_iterator
Daniel Jasperd3420c92012-10-08 16:08:15 +0000183 CommandsRefI = IndexByFile.find(Match);
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000184 if (CommandsRefI == IndexByFile.end())
185 return std::vector<CompileCommand>();
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000186 std::vector<CompileCommand> Commands;
Argyrios Kyrtzidis7e96bfb2012-12-04 07:26:44 +0000187 getCommands(CommandsRefI->getValue(), Commands);
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000188 return Commands;
189}
190
191std::vector<std::string>
192JSONCompilationDatabase::getAllFiles() const {
193 std::vector<std::string> Result;
194
195 llvm::StringMap< std::vector<CompileCommandRef> >::const_iterator
196 CommandsRefI = IndexByFile.begin();
197 const llvm::StringMap< std::vector<CompileCommandRef> >::const_iterator
198 CommandsRefEnd = IndexByFile.end();
199 for (; CommandsRefI != CommandsRefEnd; ++CommandsRefI) {
200 Result.push_back(CommandsRefI->first().str());
201 }
202
203 return Result;
204}
205
Argyrios Kyrtzidis7e96bfb2012-12-04 07:26:44 +0000206std::vector<CompileCommand>
207JSONCompilationDatabase::getAllCompileCommands() const {
208 std::vector<CompileCommand> Commands;
209 for (llvm::StringMap< std::vector<CompileCommandRef> >::const_iterator
210 CommandsRefI = IndexByFile.begin(), CommandsRefEnd = IndexByFile.end();
211 CommandsRefI != CommandsRefEnd; ++CommandsRefI) {
212 getCommands(CommandsRefI->getValue(), Commands);
213 }
214 return Commands;
215}
216
217void JSONCompilationDatabase::getCommands(
218 ArrayRef<CompileCommandRef> CommandsRef,
219 std::vector<CompileCommand> &Commands) const {
220 for (int I = 0, E = CommandsRef.size(); I != E; ++I) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000221 SmallString<8> DirectoryStorage;
222 SmallString<1024> CommandStorage;
Argyrios Kyrtzidis7e96bfb2012-12-04 07:26:44 +0000223 Commands.push_back(CompileCommand(
224 // FIXME: Escape correctly:
225 CommandsRef[I].first->getValue(DirectoryStorage),
226 unescapeCommandLine(CommandsRef[I].second->getValue(CommandStorage))));
227 }
228}
229
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000230bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
231 llvm::yaml::document_iterator I = YAMLStream.begin();
232 if (I == YAMLStream.end()) {
233 ErrorMessage = "Error while parsing YAML.";
234 return false;
235 }
236 llvm::yaml::Node *Root = I->getRoot();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700237 if (!Root) {
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000238 ErrorMessage = "Error while parsing YAML.";
239 return false;
240 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000241 llvm::yaml::SequenceNode *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700242 if (!Array) {
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000243 ErrorMessage = "Expected array.";
244 return false;
245 }
246 for (llvm::yaml::SequenceNode::iterator AI = Array->begin(),
247 AE = Array->end();
248 AI != AE; ++AI) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000249 llvm::yaml::MappingNode *Object = dyn_cast<llvm::yaml::MappingNode>(&*AI);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700250 if (!Object) {
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000251 ErrorMessage = "Expected object.";
252 return false;
253 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700254 llvm::yaml::ScalarNode *Directory = nullptr;
255 llvm::yaml::ScalarNode *Command = nullptr;
256 llvm::yaml::ScalarNode *File = nullptr;
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000257 for (llvm::yaml::MappingNode::iterator KVI = Object->begin(),
258 KVE = Object->end();
259 KVI != KVE; ++KVI) {
260 llvm::yaml::Node *Value = (*KVI).getValue();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700261 if (!Value) {
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000262 ErrorMessage = "Expected value.";
263 return false;
264 }
265 llvm::yaml::ScalarNode *ValueString =
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000266 dyn_cast<llvm::yaml::ScalarNode>(Value);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700267 if (!ValueString) {
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000268 ErrorMessage = "Expected string as value.";
269 return false;
270 }
271 llvm::yaml::ScalarNode *KeyString =
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000272 dyn_cast<llvm::yaml::ScalarNode>((*KVI).getKey());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700273 if (!KeyString) {
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000274 ErrorMessage = "Expected strings as key.";
275 return false;
276 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000277 SmallString<8> KeyStorage;
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000278 if (KeyString->getValue(KeyStorage) == "directory") {
279 Directory = ValueString;
280 } else if (KeyString->getValue(KeyStorage) == "command") {
281 Command = ValueString;
282 } else if (KeyString->getValue(KeyStorage) == "file") {
283 File = ValueString;
284 } else {
285 ErrorMessage = ("Unknown key: \"" +
286 KeyString->getRawValue() + "\"").str();
287 return false;
288 }
289 }
290 if (!File) {
291 ErrorMessage = "Missing key: \"file\".";
292 return false;
293 }
294 if (!Command) {
295 ErrorMessage = "Missing key: \"command\".";
296 return false;
297 }
298 if (!Directory) {
299 ErrorMessage = "Missing key: \"directory\".";
300 return false;
301 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000302 SmallString<8> FileStorage;
Daniel Jasperd3420c92012-10-08 16:08:15 +0000303 StringRef FileName = File->getValue(FileStorage);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000304 SmallString<128> NativeFilePath;
Daniel Jasperd3420c92012-10-08 16:08:15 +0000305 if (llvm::sys::path::is_relative(FileName)) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000306 SmallString<8> DirectoryStorage;
307 SmallString<128> AbsolutePath(
Daniel Jasperd3420c92012-10-08 16:08:15 +0000308 Directory->getValue(DirectoryStorage));
309 llvm::sys::path::append(AbsolutePath, FileName);
310 llvm::sys::path::native(AbsolutePath.str(), NativeFilePath);
311 } else {
312 llvm::sys::path::native(FileName, NativeFilePath);
313 }
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000314 IndexByFile[NativeFilePath].push_back(
Daniel Jasperd3420c92012-10-08 16:08:15 +0000315 CompileCommandRef(Directory, Command));
316 MatchTrie.insert(NativeFilePath.str());
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000317 }
318 return true;
319}
320
321} // end namespace tooling
322} // end namespace clang