JSONCompilationDatabase.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. //===- JSONCompilationDatabase.cpp ----------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains the implementation of the JSONCompilationDatabase.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Tooling/JSONCompilationDatabase.h"
  13. #include "clang/Basic/LLVM.h"
  14. #include "clang/Tooling/CompilationDatabase.h"
  15. #include "clang/Tooling/CompilationDatabasePluginRegistry.h"
  16. #include "clang/Tooling/Tooling.h"
  17. #include "llvm/ADT/Optional.h"
  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/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"
  33. #include <cassert>
  34. #include <memory>
  35. #include <string>
  36. #include <system_error>
  37. #include <tuple>
  38. #include <utility>
  39. #include <vector>
  40. using namespace clang;
  41. using namespace tooling;
  42. namespace {
  43. /// A parser for escaped strings of command line arguments.
  44. ///
  45. /// Assumes \-escaping for quoted arguments (see the documentation of
  46. /// unescapeCommandLine(...)).
  47. class CommandLineArgumentParser {
  48. public:
  49. CommandLineArgumentParser(StringRef CommandLine)
  50. : Input(CommandLine), Position(Input.begin()-1) {}
  51. std::vector<std::string> parse() {
  52. bool HasMoreInput = true;
  53. while (HasMoreInput && nextNonWhitespace()) {
  54. std::string Argument;
  55. HasMoreInput = parseStringInto(Argument);
  56. CommandLine.push_back(Argument);
  57. }
  58. return CommandLine;
  59. }
  60. private:
  61. // All private methods return true if there is more input available.
  62. bool parseStringInto(std::string &String) {
  63. do {
  64. if (*Position == '"') {
  65. if (!parseDoubleQuotedStringInto(String)) return false;
  66. } else if (*Position == '\'') {
  67. if (!parseSingleQuotedStringInto(String)) return false;
  68. } else {
  69. if (!parseFreeStringInto(String)) return false;
  70. }
  71. } while (*Position != ' ');
  72. return true;
  73. }
  74. bool parseDoubleQuotedStringInto(std::string &String) {
  75. if (!next()) return false;
  76. while (*Position != '"') {
  77. if (!skipEscapeCharacter()) return false;
  78. String.push_back(*Position);
  79. if (!next()) return false;
  80. }
  81. return next();
  82. }
  83. bool parseSingleQuotedStringInto(std::string &String) {
  84. if (!next()) return false;
  85. while (*Position != '\'') {
  86. String.push_back(*Position);
  87. if (!next()) return false;
  88. }
  89. return next();
  90. }
  91. bool parseFreeStringInto(std::string &String) {
  92. do {
  93. if (!skipEscapeCharacter()) return false;
  94. String.push_back(*Position);
  95. if (!next()) return false;
  96. } while (*Position != ' ' && *Position != '"' && *Position != '\'');
  97. return true;
  98. }
  99. bool skipEscapeCharacter() {
  100. if (*Position == '\\') {
  101. return next();
  102. }
  103. return true;
  104. }
  105. bool nextNonWhitespace() {
  106. do {
  107. if (!next()) return false;
  108. } while (*Position == ' ');
  109. return true;
  110. }
  111. bool next() {
  112. ++Position;
  113. return Position != Input.end();
  114. }
  115. const StringRef Input;
  116. StringRef::iterator Position;
  117. std::vector<std::string> CommandLine;
  118. };
  119. std::vector<std::string> unescapeCommandLine(JSONCommandLineSyntax Syntax,
  120. StringRef EscapedCommandLine) {
  121. if (Syntax == JSONCommandLineSyntax::AutoDetect) {
  122. Syntax = JSONCommandLineSyntax::Gnu;
  123. llvm::Triple Triple(llvm::sys::getProcessTriple());
  124. if (Triple.getOS() == llvm::Triple::OSType::Win32) {
  125. // Assume Windows command line parsing on Win32 unless the triple
  126. // explicitly tells us otherwise.
  127. if (!Triple.hasEnvironment() ||
  128. Triple.getEnvironment() == llvm::Triple::EnvironmentType::MSVC)
  129. Syntax = JSONCommandLineSyntax::Windows;
  130. }
  131. }
  132. if (Syntax == JSONCommandLineSyntax::Windows) {
  133. llvm::BumpPtrAllocator Alloc;
  134. llvm::StringSaver Saver(Alloc);
  135. llvm::SmallVector<const char *, 64> T;
  136. llvm::cl::TokenizeWindowsCommandLine(EscapedCommandLine, Saver, T);
  137. std::vector<std::string> Result(T.begin(), T.end());
  138. return Result;
  139. }
  140. assert(Syntax == JSONCommandLineSyntax::Gnu);
  141. CommandLineArgumentParser parser(EscapedCommandLine);
  142. return parser.parse();
  143. }
  144. // This plugin locates a nearby compile_command.json file, and also infers
  145. // compile commands for files not present in the database.
  146. class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin {
  147. std::unique_ptr<CompilationDatabase>
  148. loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
  149. SmallString<1024> JSONDatabasePath(Directory);
  150. llvm::sys::path::append(JSONDatabasePath, "compile_commands.json");
  151. auto Base = JSONCompilationDatabase::loadFromFile(
  152. JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);
  153. return Base ? inferTargetAndDriverMode(
  154. inferMissingCompileCommands(std::move(Base)))
  155. : nullptr;
  156. }
  157. };
  158. } // namespace
  159. // Register the JSONCompilationDatabasePlugin with the
  160. // CompilationDatabasePluginRegistry using this statically initialized variable.
  161. static CompilationDatabasePluginRegistry::Add<JSONCompilationDatabasePlugin>
  162. X("json-compilation-database", "Reads JSON formatted compilation databases");
  163. namespace clang {
  164. namespace tooling {
  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;
  168. } // namespace tooling
  169. } // namespace clang
  170. std::unique_ptr<JSONCompilationDatabase>
  171. JSONCompilationDatabase::loadFromFile(StringRef FilePath,
  172. std::string &ErrorMessage,
  173. JSONCommandLineSyntax Syntax) {
  174. // Don't mmap: if we're a long-lived process, the build system may overwrite.
  175. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer =
  176. llvm::MemoryBuffer::getFile(FilePath, /*FileSize=*/-1,
  177. /*RequiresNullTerminator=*/true,
  178. /*IsVolatile=*/true);
  179. if (std::error_code Result = DatabaseBuffer.getError()) {
  180. ErrorMessage = "Error while opening JSON database: " + Result.message();
  181. return nullptr;
  182. }
  183. std::unique_ptr<JSONCompilationDatabase> Database(
  184. new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
  185. if (!Database->parse(ErrorMessage))
  186. return nullptr;
  187. return Database;
  188. }
  189. std::unique_ptr<JSONCompilationDatabase>
  190. JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,
  191. std::string &ErrorMessage,
  192. JSONCommandLineSyntax Syntax) {
  193. std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
  194. llvm::MemoryBuffer::getMemBuffer(DatabaseString));
  195. std::unique_ptr<JSONCompilationDatabase> Database(
  196. new JSONCompilationDatabase(std::move(DatabaseBuffer), Syntax));
  197. if (!Database->parse(ErrorMessage))
  198. return nullptr;
  199. return Database;
  200. }
  201. std::vector<CompileCommand>
  202. JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const {
  203. SmallString<128> NativeFilePath;
  204. llvm::sys::path::native(FilePath, NativeFilePath);
  205. std::string Error;
  206. llvm::raw_string_ostream ES(Error);
  207. StringRef Match = MatchTrie.findEquivalent(NativeFilePath, ES);
  208. if (Match.empty())
  209. return {};
  210. const auto CommandsRefI = IndexByFile.find(Match);
  211. if (CommandsRefI == IndexByFile.end())
  212. return {};
  213. std::vector<CompileCommand> Commands;
  214. getCommands(CommandsRefI->getValue(), Commands);
  215. return Commands;
  216. }
  217. std::vector<std::string>
  218. JSONCompilationDatabase::getAllFiles() const {
  219. std::vector<std::string> Result;
  220. for (const auto &CommandRef : IndexByFile)
  221. Result.push_back(CommandRef.first().str());
  222. return Result;
  223. }
  224. std::vector<CompileCommand>
  225. JSONCompilationDatabase::getAllCompileCommands() const {
  226. std::vector<CompileCommand> Commands;
  227. getCommands(AllCommands, Commands);
  228. return Commands;
  229. }
  230. static std::vector<std::string>
  231. nodeToCommandLine(JSONCommandLineSyntax Syntax,
  232. const std::vector<llvm::yaml::ScalarNode *> &Nodes) {
  233. SmallString<1024> Storage;
  234. if (Nodes.size() == 1)
  235. return unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage));
  236. std::vector<std::string> Arguments;
  237. for (const auto *Node : Nodes)
  238. Arguments.push_back(Node->getValue(Storage));
  239. return Arguments;
  240. }
  241. void JSONCompilationDatabase::getCommands(
  242. ArrayRef<CompileCommandRef> CommandsRef,
  243. std::vector<CompileCommand> &Commands) const {
  244. for (const auto &CommandRef : CommandsRef) {
  245. SmallString<8> DirectoryStorage;
  246. SmallString<32> FilenameStorage;
  247. SmallString<32> OutputStorage;
  248. auto Output = std::get<3>(CommandRef);
  249. Commands.emplace_back(
  250. std::get<0>(CommandRef)->getValue(DirectoryStorage),
  251. std::get<1>(CommandRef)->getValue(FilenameStorage),
  252. nodeToCommandLine(Syntax, std::get<2>(CommandRef)),
  253. Output ? Output->getValue(OutputStorage) : "");
  254. }
  255. }
  256. bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
  257. llvm::yaml::document_iterator I = YAMLStream.begin();
  258. if (I == YAMLStream.end()) {
  259. ErrorMessage = "Error while parsing YAML.";
  260. return false;
  261. }
  262. llvm::yaml::Node *Root = I->getRoot();
  263. if (!Root) {
  264. ErrorMessage = "Error while parsing YAML.";
  265. return false;
  266. }
  267. auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
  268. if (!Array) {
  269. ErrorMessage = "Expected array.";
  270. return false;
  271. }
  272. for (auto &NextObject : *Array) {
  273. auto *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);
  274. if (!Object) {
  275. ErrorMessage = "Expected object.";
  276. return false;
  277. }
  278. llvm::yaml::ScalarNode *Directory = nullptr;
  279. llvm::Optional<std::vector<llvm::yaml::ScalarNode *>> Command;
  280. llvm::yaml::ScalarNode *File = nullptr;
  281. llvm::yaml::ScalarNode *Output = nullptr;
  282. for (auto& NextKeyValue : *Object) {
  283. auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
  284. if (!KeyString) {
  285. ErrorMessage = "Expected strings as key.";
  286. return false;
  287. }
  288. SmallString<10> KeyStorage;
  289. StringRef KeyValue = KeyString->getValue(KeyStorage);
  290. llvm::yaml::Node *Value = NextKeyValue.getValue();
  291. if (!Value) {
  292. ErrorMessage = "Expected value.";
  293. return false;
  294. }
  295. auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value);
  296. auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Value);
  297. if (KeyValue == "arguments" && !SequenceString) {
  298. ErrorMessage = "Expected sequence as value.";
  299. return false;
  300. } else if (KeyValue != "arguments" && !ValueString) {
  301. ErrorMessage = "Expected string as value.";
  302. return false;
  303. }
  304. if (KeyValue == "directory") {
  305. Directory = ValueString;
  306. } else if (KeyValue == "arguments") {
  307. Command = std::vector<llvm::yaml::ScalarNode *>();
  308. for (auto &Argument : *SequenceString) {
  309. auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);
  310. if (!Scalar) {
  311. ErrorMessage = "Only strings are allowed in 'arguments'.";
  312. return false;
  313. }
  314. Command->push_back(Scalar);
  315. }
  316. } else if (KeyValue == "command") {
  317. if (!Command)
  318. Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
  319. } else if (KeyValue == "file") {
  320. File = ValueString;
  321. } else if (KeyValue == "output") {
  322. Output = ValueString;
  323. } else {
  324. ErrorMessage = ("Unknown key: \"" +
  325. KeyString->getRawValue() + "\"").str();
  326. return false;
  327. }
  328. }
  329. if (!File) {
  330. ErrorMessage = "Missing key: \"file\".";
  331. return false;
  332. }
  333. if (!Command) {
  334. ErrorMessage = "Missing key: \"command\" or \"arguments\".";
  335. return false;
  336. }
  337. if (!Directory) {
  338. ErrorMessage = "Missing key: \"directory\".";
  339. return false;
  340. }
  341. SmallString<8> FileStorage;
  342. StringRef FileName = File->getValue(FileStorage);
  343. SmallString<128> NativeFilePath;
  344. if (llvm::sys::path::is_relative(FileName)) {
  345. SmallString<8> DirectoryStorage;
  346. SmallString<128> AbsolutePath(
  347. Directory->getValue(DirectoryStorage));
  348. llvm::sys::path::append(AbsolutePath, FileName);
  349. llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/ true);
  350. llvm::sys::path::native(AbsolutePath, NativeFilePath);
  351. } else {
  352. llvm::sys::path::native(FileName, NativeFilePath);
  353. }
  354. auto Cmd = CompileCommandRef(Directory, File, *Command, Output);
  355. IndexByFile[NativeFilePath].push_back(Cmd);
  356. AllCommands.push_back(Cmd);
  357. MatchTrie.insert(NativeFilePath);
  358. }
  359. return true;
  360. }