xref: /src/contrib/llvm-project/clang/lib/Tooling/JSONCompilationDatabase.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
148675466SDimitry Andric //===- JSONCompilationDatabase.cpp ----------------------------------------===//
213cc256eSDimitry Andric //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
613cc256eSDimitry Andric //
713cc256eSDimitry Andric //===----------------------------------------------------------------------===//
813cc256eSDimitry Andric //
913cc256eSDimitry Andric //  This file contains the implementation of the JSONCompilationDatabase.
1013cc256eSDimitry Andric //
1113cc256eSDimitry Andric //===----------------------------------------------------------------------===//
1213cc256eSDimitry Andric 
1313cc256eSDimitry Andric #include "clang/Tooling/JSONCompilationDatabase.h"
1448675466SDimitry Andric #include "clang/Basic/LLVM.h"
1513cc256eSDimitry Andric #include "clang/Tooling/CompilationDatabase.h"
1613cc256eSDimitry Andric #include "clang/Tooling/CompilationDatabasePluginRegistry.h"
1722989816SDimitry Andric #include "clang/Tooling/Tooling.h"
1822989816SDimitry Andric #include "llvm/ADT/STLExtras.h"
1913cc256eSDimitry Andric #include "llvm/ADT/SmallString.h"
2048675466SDimitry Andric #include "llvm/ADT/SmallVector.h"
2148675466SDimitry Andric #include "llvm/ADT/StringRef.h"
22bab175ecSDimitry Andric #include "llvm/Support/Allocator.h"
2348675466SDimitry Andric #include "llvm/Support/Casting.h"
24bab175ecSDimitry Andric #include "llvm/Support/CommandLine.h"
2548675466SDimitry Andric #include "llvm/Support/ErrorOr.h"
2648675466SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
2713cc256eSDimitry Andric #include "llvm/Support/Path.h"
28bab175ecSDimitry Andric #include "llvm/Support/StringSaver.h"
29706b4fc4SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
3048675466SDimitry Andric #include "llvm/Support/YAMLParser.h"
3148675466SDimitry Andric #include "llvm/Support/raw_ostream.h"
327fa27ce4SDimitry Andric #include "llvm/TargetParser/Host.h"
337fa27ce4SDimitry Andric #include "llvm/TargetParser/Triple.h"
3448675466SDimitry Andric #include <cassert>
3548675466SDimitry Andric #include <memory>
36e3b55780SDimitry Andric #include <optional>
3748675466SDimitry Andric #include <string>
389f4dbff6SDimitry Andric #include <system_error>
3948675466SDimitry Andric #include <tuple>
4048675466SDimitry Andric #include <utility>
4148675466SDimitry Andric #include <vector>
4213cc256eSDimitry Andric 
4348675466SDimitry Andric using namespace clang;
4448675466SDimitry Andric using namespace tooling;
4513cc256eSDimitry Andric 
4613cc256eSDimitry Andric namespace {
4713cc256eSDimitry Andric 
4848675466SDimitry Andric /// A parser for escaped strings of command line arguments.
4913cc256eSDimitry Andric ///
5013cc256eSDimitry Andric /// Assumes \-escaping for quoted arguments (see the documentation of
5113cc256eSDimitry Andric /// unescapeCommandLine(...)).
5213cc256eSDimitry Andric class CommandLineArgumentParser {
5313cc256eSDimitry Andric  public:
CommandLineArgumentParser(StringRef CommandLine)5413cc256eSDimitry Andric   CommandLineArgumentParser(StringRef CommandLine)
5513cc256eSDimitry Andric       : Input(CommandLine), Position(Input.begin()-1) {}
5613cc256eSDimitry Andric 
parse()5713cc256eSDimitry Andric   std::vector<std::string> parse() {
5813cc256eSDimitry Andric     bool HasMoreInput = true;
5913cc256eSDimitry Andric     while (HasMoreInput && nextNonWhitespace()) {
6013cc256eSDimitry Andric       std::string Argument;
6113cc256eSDimitry Andric       HasMoreInput = parseStringInto(Argument);
6213cc256eSDimitry Andric       CommandLine.push_back(Argument);
6313cc256eSDimitry Andric     }
6413cc256eSDimitry Andric     return CommandLine;
6513cc256eSDimitry Andric   }
6613cc256eSDimitry Andric 
6713cc256eSDimitry Andric  private:
6813cc256eSDimitry Andric   // All private methods return true if there is more input available.
6913cc256eSDimitry Andric 
parseStringInto(std::string & String)7013cc256eSDimitry Andric   bool parseStringInto(std::string &String) {
7113cc256eSDimitry Andric     do {
7213cc256eSDimitry Andric       if (*Position == '"') {
73809500fcSDimitry Andric         if (!parseDoubleQuotedStringInto(String)) return false;
74809500fcSDimitry Andric       } else if (*Position == '\'') {
75809500fcSDimitry Andric         if (!parseSingleQuotedStringInto(String)) return false;
7613cc256eSDimitry Andric       } else {
7713cc256eSDimitry Andric         if (!parseFreeStringInto(String)) return false;
7813cc256eSDimitry Andric       }
7913cc256eSDimitry Andric     } while (*Position != ' ');
8013cc256eSDimitry Andric     return true;
8113cc256eSDimitry Andric   }
8213cc256eSDimitry Andric 
parseDoubleQuotedStringInto(std::string & String)83809500fcSDimitry Andric   bool parseDoubleQuotedStringInto(std::string &String) {
8413cc256eSDimitry Andric     if (!next()) return false;
8513cc256eSDimitry Andric     while (*Position != '"') {
8613cc256eSDimitry Andric       if (!skipEscapeCharacter()) return false;
8713cc256eSDimitry Andric       String.push_back(*Position);
8813cc256eSDimitry Andric       if (!next()) return false;
8913cc256eSDimitry Andric     }
9013cc256eSDimitry Andric     return next();
9113cc256eSDimitry Andric   }
9213cc256eSDimitry Andric 
parseSingleQuotedStringInto(std::string & String)93809500fcSDimitry Andric   bool parseSingleQuotedStringInto(std::string &String) {
94809500fcSDimitry Andric     if (!next()) return false;
95809500fcSDimitry Andric     while (*Position != '\'') {
96809500fcSDimitry Andric       String.push_back(*Position);
97809500fcSDimitry Andric       if (!next()) return false;
98809500fcSDimitry Andric     }
99809500fcSDimitry Andric     return next();
100809500fcSDimitry Andric   }
101809500fcSDimitry Andric 
parseFreeStringInto(std::string & String)10213cc256eSDimitry Andric   bool parseFreeStringInto(std::string &String) {
10313cc256eSDimitry Andric     do {
10413cc256eSDimitry Andric       if (!skipEscapeCharacter()) return false;
10513cc256eSDimitry Andric       String.push_back(*Position);
10613cc256eSDimitry Andric       if (!next()) return false;
107809500fcSDimitry Andric     } while (*Position != ' ' && *Position != '"' && *Position != '\'');
10813cc256eSDimitry Andric     return true;
10913cc256eSDimitry Andric   }
11013cc256eSDimitry Andric 
skipEscapeCharacter()11113cc256eSDimitry Andric   bool skipEscapeCharacter() {
11213cc256eSDimitry Andric     if (*Position == '\\') {
11313cc256eSDimitry Andric       return next();
11413cc256eSDimitry Andric     }
11513cc256eSDimitry Andric     return true;
11613cc256eSDimitry Andric   }
11713cc256eSDimitry Andric 
nextNonWhitespace()11813cc256eSDimitry Andric   bool nextNonWhitespace() {
11913cc256eSDimitry Andric     do {
12013cc256eSDimitry Andric       if (!next()) return false;
12113cc256eSDimitry Andric     } while (*Position == ' ');
12213cc256eSDimitry Andric     return true;
12313cc256eSDimitry Andric   }
12413cc256eSDimitry Andric 
next()12513cc256eSDimitry Andric   bool next() {
12613cc256eSDimitry Andric     ++Position;
12713cc256eSDimitry Andric     return Position != Input.end();
12813cc256eSDimitry Andric   }
12913cc256eSDimitry Andric 
13013cc256eSDimitry Andric   const StringRef Input;
13113cc256eSDimitry Andric   StringRef::iterator Position;
13213cc256eSDimitry Andric   std::vector<std::string> CommandLine;
13313cc256eSDimitry Andric };
13413cc256eSDimitry Andric 
unescapeCommandLine(JSONCommandLineSyntax Syntax,StringRef EscapedCommandLine)135bab175ecSDimitry Andric std::vector<std::string> unescapeCommandLine(JSONCommandLineSyntax Syntax,
13613cc256eSDimitry Andric                                              StringRef EscapedCommandLine) {
137bab175ecSDimitry Andric   if (Syntax == JSONCommandLineSyntax::AutoDetect) {
138c0981da4SDimitry Andric #ifdef _WIN32
139c0981da4SDimitry Andric     // Assume Windows command line parsing on Win32
140bab175ecSDimitry Andric     Syntax = JSONCommandLineSyntax::Windows;
141c0981da4SDimitry Andric #else
142c0981da4SDimitry Andric     Syntax = JSONCommandLineSyntax::Gnu;
143c0981da4SDimitry Andric #endif
144bab175ecSDimitry Andric   }
145bab175ecSDimitry Andric 
146bab175ecSDimitry Andric   if (Syntax == JSONCommandLineSyntax::Windows) {
147bab175ecSDimitry Andric     llvm::BumpPtrAllocator Alloc;
148bab175ecSDimitry Andric     llvm::StringSaver Saver(Alloc);
149bab175ecSDimitry Andric     llvm::SmallVector<const char *, 64> T;
150bab175ecSDimitry Andric     llvm::cl::TokenizeWindowsCommandLine(EscapedCommandLine, Saver, T);
151bab175ecSDimitry Andric     std::vector<std::string> Result(T.begin(), T.end());
152bab175ecSDimitry Andric     return Result;
153bab175ecSDimitry Andric   }
154bab175ecSDimitry Andric   assert(Syntax == JSONCommandLineSyntax::Gnu);
15513cc256eSDimitry Andric   CommandLineArgumentParser parser(EscapedCommandLine);
15613cc256eSDimitry Andric   return parser.parse();
15713cc256eSDimitry Andric }
15813cc256eSDimitry Andric 
159676fbe81SDimitry Andric // This plugin locates a nearby compile_command.json file, and also infers
160676fbe81SDimitry Andric // compile commands for files not present in the database.
16113cc256eSDimitry Andric class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin {
16206d4ba38SDimitry Andric   std::unique_ptr<CompilationDatabase>
loadFromDirectory(StringRef Directory,std::string & ErrorMessage)16306d4ba38SDimitry Andric   loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
164809500fcSDimitry Andric     SmallString<1024> JSONDatabasePath(Directory);
16513cc256eSDimitry Andric     llvm::sys::path::append(JSONDatabasePath, "compile_commands.json");
166676fbe81SDimitry Andric     auto Base = JSONCompilationDatabase::loadFromFile(
1670a5fb09bSDimitry Andric         JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);
16822989816SDimitry Andric     return Base ? inferTargetAndDriverMode(
169706b4fc4SDimitry Andric                       inferMissingCompileCommands(expandResponseFiles(
170706b4fc4SDimitry Andric                           std::move(Base), llvm::vfs::getRealFileSystem())))
17122989816SDimitry Andric                 : nullptr;
17213cc256eSDimitry Andric   }
17313cc256eSDimitry Andric };
17413cc256eSDimitry Andric 
17548675466SDimitry Andric } // namespace
176bfef3995SDimitry Andric 
17713cc256eSDimitry Andric // Register the JSONCompilationDatabasePlugin with the
17813cc256eSDimitry Andric // CompilationDatabasePluginRegistry using this statically initialized variable.
17913cc256eSDimitry Andric static CompilationDatabasePluginRegistry::Add<JSONCompilationDatabasePlugin>
18013cc256eSDimitry Andric X("json-compilation-database", "Reads JSON formatted compilation databases");
18113cc256eSDimitry Andric 
18248675466SDimitry Andric namespace clang {
18348675466SDimitry Andric namespace tooling {
18448675466SDimitry Andric 
18513cc256eSDimitry Andric // This anchor is used to force the linker to link in the generated object file
18613cc256eSDimitry Andric // and thus register the JSONCompilationDatabasePlugin.
18713cc256eSDimitry Andric volatile int JSONAnchorSource = 0;
18813cc256eSDimitry Andric 
18948675466SDimitry Andric } // namespace tooling
19048675466SDimitry Andric } // namespace clang
19148675466SDimitry Andric 
19206d4ba38SDimitry Andric std::unique_ptr<JSONCompilationDatabase>
loadFromFile(StringRef FilePath,std::string & ErrorMessage,JSONCommandLineSyntax Syntax)19313cc256eSDimitry Andric JSONCompilationDatabase::loadFromFile(StringRef FilePath,
194bab175ecSDimitry Andric                                       std::string &ErrorMessage,
195bab175ecSDimitry Andric                                       JSONCommandLineSyntax Syntax) {
19622989816SDimitry Andric   // Don't mmap: if we're a long-lived process, the build system may overwrite.
1979f4dbff6SDimitry Andric   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer =
198344a3780SDimitry Andric       llvm::MemoryBuffer::getFile(FilePath, /*IsText=*/false,
19922989816SDimitry Andric                                   /*RequiresNullTerminator=*/true,
20022989816SDimitry Andric                                   /*IsVolatile=*/true);
2019f4dbff6SDimitry Andric   if (std::error_code Result = DatabaseBuffer.getError()) {
20213cc256eSDimitry Andric     ErrorMessage = "Error while opening JSON database: " + Result.message();
2039f4dbff6SDimitry Andric     return nullptr;
20413cc256eSDimitry Andric   }
2059f4dbff6SDimitry Andric   std::unique_ptr<JSONCompilationDatabase> Database(
206bab175ecSDimitry Andric       new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
20713cc256eSDimitry Andric   if (!Database->parse(ErrorMessage))
2089f4dbff6SDimitry Andric     return nullptr;
20906d4ba38SDimitry Andric   return Database;
21013cc256eSDimitry Andric }
21113cc256eSDimitry Andric 
21206d4ba38SDimitry Andric std::unique_ptr<JSONCompilationDatabase>
loadFromBuffer(StringRef DatabaseString,std::string & ErrorMessage,JSONCommandLineSyntax Syntax)21313cc256eSDimitry Andric JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,
214bab175ecSDimitry Andric                                         std::string &ErrorMessage,
215bab175ecSDimitry Andric                                         JSONCommandLineSyntax Syntax) {
2169f4dbff6SDimitry Andric   std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
217b60736ecSDimitry Andric       llvm::MemoryBuffer::getMemBufferCopy(DatabaseString));
2189f4dbff6SDimitry Andric   std::unique_ptr<JSONCompilationDatabase> Database(
219bab175ecSDimitry Andric       new JSONCompilationDatabase(std::move(DatabaseBuffer), Syntax));
22013cc256eSDimitry Andric   if (!Database->parse(ErrorMessage))
2219f4dbff6SDimitry Andric     return nullptr;
22206d4ba38SDimitry Andric   return Database;
22313cc256eSDimitry Andric }
22413cc256eSDimitry Andric 
22513cc256eSDimitry Andric std::vector<CompileCommand>
getCompileCommands(StringRef FilePath) const22613cc256eSDimitry Andric JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const {
227809500fcSDimitry Andric   SmallString<128> NativeFilePath;
22813cc256eSDimitry Andric   llvm::sys::path::native(FilePath, NativeFilePath);
2299f4dbff6SDimitry Andric 
23013cc256eSDimitry Andric   std::string Error;
23113cc256eSDimitry Andric   llvm::raw_string_ostream ES(Error);
2325e20cdd8SDimitry Andric   StringRef Match = MatchTrie.findEquivalent(NativeFilePath, ES);
233809500fcSDimitry Andric   if (Match.empty())
23448675466SDimitry Andric     return {};
23548675466SDimitry Andric   const auto CommandsRefI = IndexByFile.find(Match);
23613cc256eSDimitry Andric   if (CommandsRefI == IndexByFile.end())
23748675466SDimitry Andric     return {};
23813cc256eSDimitry Andric   std::vector<CompileCommand> Commands;
239809500fcSDimitry Andric   getCommands(CommandsRefI->getValue(), Commands);
24013cc256eSDimitry Andric   return Commands;
24113cc256eSDimitry Andric }
24213cc256eSDimitry Andric 
24313cc256eSDimitry Andric std::vector<std::string>
getAllFiles() const24413cc256eSDimitry Andric JSONCompilationDatabase::getAllFiles() const {
24513cc256eSDimitry Andric   std::vector<std::string> Result;
24648675466SDimitry Andric   for (const auto &CommandRef : IndexByFile)
24748675466SDimitry Andric     Result.push_back(CommandRef.first().str());
24813cc256eSDimitry Andric   return Result;
24913cc256eSDimitry Andric }
25013cc256eSDimitry Andric 
251809500fcSDimitry Andric std::vector<CompileCommand>
getAllCompileCommands() const252809500fcSDimitry Andric JSONCompilationDatabase::getAllCompileCommands() const {
253809500fcSDimitry Andric   std::vector<CompileCommand> Commands;
25445b53394SDimitry Andric   getCommands(AllCommands, Commands);
255809500fcSDimitry Andric   return Commands;
256809500fcSDimitry Andric }
257809500fcSDimitry Andric 
stripExecutableExtension(llvm::StringRef Name)25822989816SDimitry Andric static llvm::StringRef stripExecutableExtension(llvm::StringRef Name) {
25922989816SDimitry Andric   Name.consume_back(".exe");
26022989816SDimitry Andric   return Name;
26122989816SDimitry Andric }
26222989816SDimitry Andric 
263ac9a064cSDimitry Andric // There are compiler-wrappers (ccache, distcc) that take the "real"
26422989816SDimitry Andric // compiler as an argument, e.g. distcc gcc -O3 foo.c.
26522989816SDimitry Andric // These end up in compile_commands.json when people set CC="distcc gcc".
26622989816SDimitry Andric // Clang's driver doesn't understand this, so we need to unwrap.
unwrapCommand(std::vector<std::string> & Args)26722989816SDimitry Andric static bool unwrapCommand(std::vector<std::string> &Args) {
26822989816SDimitry Andric   if (Args.size() < 2)
26922989816SDimitry Andric     return false;
27022989816SDimitry Andric   StringRef Wrapper =
27122989816SDimitry Andric       stripExecutableExtension(llvm::sys::path::filename(Args.front()));
272ac9a064cSDimitry Andric   if (Wrapper == "distcc" || Wrapper == "ccache" || Wrapper == "sccache") {
27322989816SDimitry Andric     // Most of these wrappers support being invoked 3 ways:
27422989816SDimitry Andric     // `distcc g++ file.c` This is the mode we're trying to match.
27522989816SDimitry Andric     //                     We need to drop `distcc`.
27622989816SDimitry Andric     // `distcc file.c`     This acts like compiler is cc or similar.
27722989816SDimitry Andric     //                     Clang's driver can handle this, no change needed.
27822989816SDimitry Andric     // `g++ file.c`        g++ is a symlink to distcc.
27922989816SDimitry Andric     //                     We don't even notice this case, and all is well.
28022989816SDimitry Andric     //
28122989816SDimitry Andric     // We need to distinguish between the first and second case.
28222989816SDimitry Andric     // The wrappers themselves don't take flags, so Args[1] is a compiler flag,
28322989816SDimitry Andric     // an input file, or a compiler. Inputs have extensions, compilers don't.
28422989816SDimitry Andric     bool HasCompiler =
28522989816SDimitry Andric         (Args[1][0] != '-') &&
28622989816SDimitry Andric         !llvm::sys::path::has_extension(stripExecutableExtension(Args[1]));
28722989816SDimitry Andric     if (HasCompiler) {
28822989816SDimitry Andric       Args.erase(Args.begin());
28922989816SDimitry Andric       return true;
29022989816SDimitry Andric     }
29122989816SDimitry Andric     // If !HasCompiler, wrappers act like GCC. Fine: so do we.
29222989816SDimitry Andric   }
29322989816SDimitry Andric   return false;
29422989816SDimitry Andric }
29522989816SDimitry Andric 
29645b53394SDimitry Andric static std::vector<std::string>
nodeToCommandLine(JSONCommandLineSyntax Syntax,const std::vector<llvm::yaml::ScalarNode * > & Nodes)297bab175ecSDimitry Andric nodeToCommandLine(JSONCommandLineSyntax Syntax,
298bab175ecSDimitry Andric                   const std::vector<llvm::yaml::ScalarNode *> &Nodes) {
29945b53394SDimitry Andric   SmallString<1024> Storage;
30045b53394SDimitry Andric   std::vector<std::string> Arguments;
30122989816SDimitry Andric   if (Nodes.size() == 1)
30222989816SDimitry Andric     Arguments = unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage));
30322989816SDimitry Andric   else
30448675466SDimitry Andric     for (const auto *Node : Nodes)
305cfca06d7SDimitry Andric       Arguments.push_back(std::string(Node->getValue(Storage)));
30622989816SDimitry Andric   // There may be multiple wrappers: using distcc and ccache together is common.
30722989816SDimitry Andric   while (unwrapCommand(Arguments))
30822989816SDimitry Andric     ;
30945b53394SDimitry Andric   return Arguments;
31045b53394SDimitry Andric }
31145b53394SDimitry Andric 
getCommands(ArrayRef<CompileCommandRef> CommandsRef,std::vector<CompileCommand> & Commands) const312809500fcSDimitry Andric void JSONCompilationDatabase::getCommands(
313809500fcSDimitry Andric     ArrayRef<CompileCommandRef> CommandsRef,
314809500fcSDimitry Andric     std::vector<CompileCommand> &Commands) const {
31548675466SDimitry Andric   for (const auto &CommandRef : CommandsRef) {
316809500fcSDimitry Andric     SmallString<8> DirectoryStorage;
31745b53394SDimitry Andric     SmallString<32> FilenameStorage;
318bab175ecSDimitry Andric     SmallString<32> OutputStorage;
31948675466SDimitry Andric     auto Output = std::get<3>(CommandRef);
320798321d8SDimitry Andric     Commands.emplace_back(
32148675466SDimitry Andric         std::get<0>(CommandRef)->getValue(DirectoryStorage),
32248675466SDimitry Andric         std::get<1>(CommandRef)->getValue(FilenameStorage),
32348675466SDimitry Andric         nodeToCommandLine(Syntax, std::get<2>(CommandRef)),
324bab175ecSDimitry Andric         Output ? Output->getValue(OutputStorage) : "");
325809500fcSDimitry Andric   }
326809500fcSDimitry Andric }
327809500fcSDimitry Andric 
parse(std::string & ErrorMessage)32813cc256eSDimitry Andric bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
32913cc256eSDimitry Andric   llvm::yaml::document_iterator I = YAMLStream.begin();
33013cc256eSDimitry Andric   if (I == YAMLStream.end()) {
33113cc256eSDimitry Andric     ErrorMessage = "Error while parsing YAML.";
33213cc256eSDimitry Andric     return false;
33313cc256eSDimitry Andric   }
33413cc256eSDimitry Andric   llvm::yaml::Node *Root = I->getRoot();
3359f4dbff6SDimitry Andric   if (!Root) {
33613cc256eSDimitry Andric     ErrorMessage = "Error while parsing YAML.";
33713cc256eSDimitry Andric     return false;
33813cc256eSDimitry Andric   }
33948675466SDimitry Andric   auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
3409f4dbff6SDimitry Andric   if (!Array) {
34113cc256eSDimitry Andric     ErrorMessage = "Expected array.";
34213cc256eSDimitry Andric     return false;
34313cc256eSDimitry Andric   }
34445b53394SDimitry Andric   for (auto &NextObject : *Array) {
34548675466SDimitry Andric     auto *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);
3469f4dbff6SDimitry Andric     if (!Object) {
34713cc256eSDimitry Andric       ErrorMessage = "Expected object.";
34813cc256eSDimitry Andric       return false;
34913cc256eSDimitry Andric     }
3509f4dbff6SDimitry Andric     llvm::yaml::ScalarNode *Directory = nullptr;
351e3b55780SDimitry Andric     std::optional<std::vector<llvm::yaml::ScalarNode *>> Command;
3529f4dbff6SDimitry Andric     llvm::yaml::ScalarNode *File = nullptr;
353bab175ecSDimitry Andric     llvm::yaml::ScalarNode *Output = nullptr;
35445b53394SDimitry Andric     for (auto& NextKeyValue : *Object) {
35548675466SDimitry Andric       auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
35645b53394SDimitry Andric       if (!KeyString) {
35745b53394SDimitry Andric         ErrorMessage = "Expected strings as key.";
35845b53394SDimitry Andric         return false;
35945b53394SDimitry Andric       }
36045b53394SDimitry Andric       SmallString<10> KeyStorage;
36145b53394SDimitry Andric       StringRef KeyValue = KeyString->getValue(KeyStorage);
36245b53394SDimitry Andric       llvm::yaml::Node *Value = NextKeyValue.getValue();
3639f4dbff6SDimitry Andric       if (!Value) {
36413cc256eSDimitry Andric         ErrorMessage = "Expected value.";
36513cc256eSDimitry Andric         return false;
36613cc256eSDimitry Andric       }
36748675466SDimitry Andric       auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value);
36848675466SDimitry Andric       auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Value);
369b60736ecSDimitry Andric       if (KeyValue == "arguments") {
370b60736ecSDimitry Andric         if (!SequenceString) {
37145b53394SDimitry Andric           ErrorMessage = "Expected sequence as value.";
37245b53394SDimitry Andric           return false;
37313cc256eSDimitry Andric         }
37445b53394SDimitry Andric         Command = std::vector<llvm::yaml::ScalarNode *>();
37545b53394SDimitry Andric         for (auto &Argument : *SequenceString) {
37648675466SDimitry Andric           auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);
37745b53394SDimitry Andric           if (!Scalar) {
37845b53394SDimitry Andric             ErrorMessage = "Only strings are allowed in 'arguments'.";
37913cc256eSDimitry Andric             return false;
38013cc256eSDimitry Andric           }
38145b53394SDimitry Andric           Command->push_back(Scalar);
38245b53394SDimitry Andric         }
383b60736ecSDimitry Andric       } else {
384b60736ecSDimitry Andric         if (!ValueString) {
385b60736ecSDimitry Andric           ErrorMessage = "Expected string as value.";
386b60736ecSDimitry Andric           return false;
387b60736ecSDimitry Andric         }
388b60736ecSDimitry Andric         if (KeyValue == "directory") {
389b60736ecSDimitry Andric           Directory = ValueString;
39045b53394SDimitry Andric         } else if (KeyValue == "command") {
39145b53394SDimitry Andric           if (!Command)
39245b53394SDimitry Andric             Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
39345b53394SDimitry Andric         } else if (KeyValue == "file") {
39413cc256eSDimitry Andric           File = ValueString;
395bab175ecSDimitry Andric         } else if (KeyValue == "output") {
396bab175ecSDimitry Andric           Output = ValueString;
39713cc256eSDimitry Andric         } else {
398b60736ecSDimitry Andric           ErrorMessage =
399b60736ecSDimitry Andric               ("Unknown key: \"" + KeyString->getRawValue() + "\"").str();
40013cc256eSDimitry Andric           return false;
40113cc256eSDimitry Andric         }
40213cc256eSDimitry Andric       }
403b60736ecSDimitry Andric     }
40413cc256eSDimitry Andric     if (!File) {
40513cc256eSDimitry Andric       ErrorMessage = "Missing key: \"file\".";
40613cc256eSDimitry Andric       return false;
40713cc256eSDimitry Andric     }
40813cc256eSDimitry Andric     if (!Command) {
40945b53394SDimitry Andric       ErrorMessage = "Missing key: \"command\" or \"arguments\".";
41013cc256eSDimitry Andric       return false;
41113cc256eSDimitry Andric     }
41213cc256eSDimitry Andric     if (!Directory) {
41313cc256eSDimitry Andric       ErrorMessage = "Missing key: \"directory\".";
41413cc256eSDimitry Andric       return false;
41513cc256eSDimitry Andric     }
416809500fcSDimitry Andric     SmallString<8> FileStorage;
41713cc256eSDimitry Andric     StringRef FileName = File->getValue(FileStorage);
418809500fcSDimitry Andric     SmallString<128> NativeFilePath;
41913cc256eSDimitry Andric     if (llvm::sys::path::is_relative(FileName)) {
420809500fcSDimitry Andric       SmallString<8> DirectoryStorage;
421e3b55780SDimitry Andric       SmallString<128> AbsolutePath(Directory->getValue(DirectoryStorage));
42213cc256eSDimitry Andric       llvm::sys::path::append(AbsolutePath, FileName);
4235e20cdd8SDimitry Andric       llvm::sys::path::native(AbsolutePath, NativeFilePath);
42413cc256eSDimitry Andric     } else {
42513cc256eSDimitry Andric       llvm::sys::path::native(FileName, NativeFilePath);
42613cc256eSDimitry Andric     }
427e3b55780SDimitry Andric     llvm::sys::path::remove_dots(NativeFilePath, /*remove_dot_dot=*/true);
428bab175ecSDimitry Andric     auto Cmd = CompileCommandRef(Directory, File, *Command, Output);
42945b53394SDimitry Andric     IndexByFile[NativeFilePath].push_back(Cmd);
43045b53394SDimitry Andric     AllCommands.push_back(Cmd);
4315e20cdd8SDimitry Andric     MatchTrie.insert(NativeFilePath);
43213cc256eSDimitry Andric   }
43313cc256eSDimitry Andric   return true;
43413cc256eSDimitry Andric }
435