PageRenderTime 25ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/contrib/llvm/tools/clang/lib/Tooling/JSONCompilationDatabase.cpp

https://bitbucket.org/freebsd/freebsd-base
C++ | 433 lines | 408 code | 9 blank | 16 comment | 19 complexity | 3911a6473fc774ef07c2cc6f7d81f6b6 MD5 | raw file
  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 llvm::StringRef stripExecutableExtension(llvm::StringRef Name) {
  231. Name.consume_back(".exe");
  232. return Name;
  233. }
  234. // There are compiler-wrappers (ccache, distcc, gomacc) that take the "real"
  235. // compiler as an argument, e.g. distcc gcc -O3 foo.c.
  236. // These end up in compile_commands.json when people set CC="distcc gcc".
  237. // Clang's driver doesn't understand this, so we need to unwrap.
  238. static bool unwrapCommand(std::vector<std::string> &Args) {
  239. if (Args.size() < 2)
  240. return false;
  241. StringRef Wrapper =
  242. stripExecutableExtension(llvm::sys::path::filename(Args.front()));
  243. if (Wrapper == "distcc" || Wrapper == "gomacc" || Wrapper == "ccache") {
  244. // Most of these wrappers support being invoked 3 ways:
  245. // `distcc g++ file.c` This is the mode we're trying to match.
  246. // We need to drop `distcc`.
  247. // `distcc file.c` This acts like compiler is cc or similar.
  248. // Clang's driver can handle this, no change needed.
  249. // `g++ file.c` g++ is a symlink to distcc.
  250. // We don't even notice this case, and all is well.
  251. //
  252. // We need to distinguish between the first and second case.
  253. // The wrappers themselves don't take flags, so Args[1] is a compiler flag,
  254. // an input file, or a compiler. Inputs have extensions, compilers don't.
  255. bool HasCompiler =
  256. (Args[1][0] != '-') &&
  257. !llvm::sys::path::has_extension(stripExecutableExtension(Args[1]));
  258. if (HasCompiler) {
  259. Args.erase(Args.begin());
  260. return true;
  261. }
  262. // If !HasCompiler, wrappers act like GCC. Fine: so do we.
  263. }
  264. return false;
  265. }
  266. static std::vector<std::string>
  267. nodeToCommandLine(JSONCommandLineSyntax Syntax,
  268. const std::vector<llvm::yaml::ScalarNode *> &Nodes) {
  269. SmallString<1024> Storage;
  270. std::vector<std::string> Arguments;
  271. if (Nodes.size() == 1)
  272. Arguments = unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage));
  273. else
  274. for (const auto *Node : Nodes)
  275. Arguments.push_back(Node->getValue(Storage));
  276. // There may be multiple wrappers: using distcc and ccache together is common.
  277. while (unwrapCommand(Arguments))
  278. ;
  279. return Arguments;
  280. }
  281. void JSONCompilationDatabase::getCommands(
  282. ArrayRef<CompileCommandRef> CommandsRef,
  283. std::vector<CompileCommand> &Commands) const {
  284. for (const auto &CommandRef : CommandsRef) {
  285. SmallString<8> DirectoryStorage;
  286. SmallString<32> FilenameStorage;
  287. SmallString<32> OutputStorage;
  288. auto Output = std::get<3>(CommandRef);
  289. Commands.emplace_back(
  290. std::get<0>(CommandRef)->getValue(DirectoryStorage),
  291. std::get<1>(CommandRef)->getValue(FilenameStorage),
  292. nodeToCommandLine(Syntax, std::get<2>(CommandRef)),
  293. Output ? Output->getValue(OutputStorage) : "");
  294. }
  295. }
  296. bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
  297. llvm::yaml::document_iterator I = YAMLStream.begin();
  298. if (I == YAMLStream.end()) {
  299. ErrorMessage = "Error while parsing YAML.";
  300. return false;
  301. }
  302. llvm::yaml::Node *Root = I->getRoot();
  303. if (!Root) {
  304. ErrorMessage = "Error while parsing YAML.";
  305. return false;
  306. }
  307. auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
  308. if (!Array) {
  309. ErrorMessage = "Expected array.";
  310. return false;
  311. }
  312. for (auto &NextObject : *Array) {
  313. auto *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);
  314. if (!Object) {
  315. ErrorMessage = "Expected object.";
  316. return false;
  317. }
  318. llvm::yaml::ScalarNode *Directory = nullptr;
  319. llvm::Optional<std::vector<llvm::yaml::ScalarNode *>> Command;
  320. llvm::yaml::ScalarNode *File = nullptr;
  321. llvm::yaml::ScalarNode *Output = nullptr;
  322. for (auto& NextKeyValue : *Object) {
  323. auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
  324. if (!KeyString) {
  325. ErrorMessage = "Expected strings as key.";
  326. return false;
  327. }
  328. SmallString<10> KeyStorage;
  329. StringRef KeyValue = KeyString->getValue(KeyStorage);
  330. llvm::yaml::Node *Value = NextKeyValue.getValue();
  331. if (!Value) {
  332. ErrorMessage = "Expected value.";
  333. return false;
  334. }
  335. auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value);
  336. auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Value);
  337. if (KeyValue == "arguments" && !SequenceString) {
  338. ErrorMessage = "Expected sequence as value.";
  339. return false;
  340. } else if (KeyValue != "arguments" && !ValueString) {
  341. ErrorMessage = "Expected string as value.";
  342. return false;
  343. }
  344. if (KeyValue == "directory") {
  345. Directory = ValueString;
  346. } else if (KeyValue == "arguments") {
  347. Command = std::vector<llvm::yaml::ScalarNode *>();
  348. for (auto &Argument : *SequenceString) {
  349. auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);
  350. if (!Scalar) {
  351. ErrorMessage = "Only strings are allowed in 'arguments'.";
  352. return false;
  353. }
  354. Command->push_back(Scalar);
  355. }
  356. } else if (KeyValue == "command") {
  357. if (!Command)
  358. Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
  359. } else if (KeyValue == "file") {
  360. File = ValueString;
  361. } else if (KeyValue == "output") {
  362. Output = ValueString;
  363. } else {
  364. ErrorMessage = ("Unknown key: \"" +
  365. KeyString->getRawValue() + "\"").str();
  366. return false;
  367. }
  368. }
  369. if (!File) {
  370. ErrorMessage = "Missing key: \"file\".";
  371. return false;
  372. }
  373. if (!Command) {
  374. ErrorMessage = "Missing key: \"command\" or \"arguments\".";
  375. return false;
  376. }
  377. if (!Directory) {
  378. ErrorMessage = "Missing key: \"directory\".";
  379. return false;
  380. }
  381. SmallString<8> FileStorage;
  382. StringRef FileName = File->getValue(FileStorage);
  383. SmallString<128> NativeFilePath;
  384. if (llvm::sys::path::is_relative(FileName)) {
  385. SmallString<8> DirectoryStorage;
  386. SmallString<128> AbsolutePath(
  387. Directory->getValue(DirectoryStorage));
  388. llvm::sys::path::append(AbsolutePath, FileName);
  389. llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/ true);
  390. llvm::sys::path::native(AbsolutePath, NativeFilePath);
  391. } else {
  392. llvm::sys::path::native(FileName, NativeFilePath);
  393. }
  394. auto Cmd = CompileCommandRef(Directory, File, *Command, Output);
  395. IndexByFile[NativeFilePath].push_back(Cmd);
  396. AllCommands.push_back(Cmd);
  397. MatchTrie.insert(NativeFilePath);
  398. }
  399. return true;
  400. }