xref: /openbsd-src/gnu/llvm/clang/lib/Tooling/JSONCompilationDatabase.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===- JSONCompilationDatabase.cpp ----------------------------------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick //  This file contains the implementation of the JSONCompilationDatabase.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "clang/Tooling/JSONCompilationDatabase.h"
14e5dd7070Spatrick #include "clang/Basic/LLVM.h"
15e5dd7070Spatrick #include "clang/Tooling/CompilationDatabase.h"
16e5dd7070Spatrick #include "clang/Tooling/CompilationDatabasePluginRegistry.h"
17e5dd7070Spatrick #include "clang/Tooling/Tooling.h"
18e5dd7070Spatrick #include "llvm/ADT/STLExtras.h"
19e5dd7070Spatrick #include "llvm/ADT/SmallString.h"
20e5dd7070Spatrick #include "llvm/ADT/SmallVector.h"
21e5dd7070Spatrick #include "llvm/ADT/StringRef.h"
22e5dd7070Spatrick #include "llvm/ADT/Triple.h"
23e5dd7070Spatrick #include "llvm/Support/Allocator.h"
24e5dd7070Spatrick #include "llvm/Support/Casting.h"
25e5dd7070Spatrick #include "llvm/Support/CommandLine.h"
26e5dd7070Spatrick #include "llvm/Support/ErrorOr.h"
27e5dd7070Spatrick #include "llvm/Support/Host.h"
28e5dd7070Spatrick #include "llvm/Support/MemoryBuffer.h"
29e5dd7070Spatrick #include "llvm/Support/Path.h"
30e5dd7070Spatrick #include "llvm/Support/StringSaver.h"
31e5dd7070Spatrick #include "llvm/Support/VirtualFileSystem.h"
32e5dd7070Spatrick #include "llvm/Support/YAMLParser.h"
33e5dd7070Spatrick #include "llvm/Support/raw_ostream.h"
34e5dd7070Spatrick #include <cassert>
35e5dd7070Spatrick #include <memory>
36*12c85518Srobert #include <optional>
37e5dd7070Spatrick #include <string>
38e5dd7070Spatrick #include <system_error>
39e5dd7070Spatrick #include <tuple>
40e5dd7070Spatrick #include <utility>
41e5dd7070Spatrick #include <vector>
42e5dd7070Spatrick 
43e5dd7070Spatrick using namespace clang;
44e5dd7070Spatrick using namespace tooling;
45e5dd7070Spatrick 
46e5dd7070Spatrick namespace {
47e5dd7070Spatrick 
48e5dd7070Spatrick /// A parser for escaped strings of command line arguments.
49e5dd7070Spatrick ///
50e5dd7070Spatrick /// Assumes \-escaping for quoted arguments (see the documentation of
51e5dd7070Spatrick /// unescapeCommandLine(...)).
52e5dd7070Spatrick class CommandLineArgumentParser {
53e5dd7070Spatrick  public:
CommandLineArgumentParser(StringRef CommandLine)54e5dd7070Spatrick   CommandLineArgumentParser(StringRef CommandLine)
55e5dd7070Spatrick       : Input(CommandLine), Position(Input.begin()-1) {}
56e5dd7070Spatrick 
parse()57e5dd7070Spatrick   std::vector<std::string> parse() {
58e5dd7070Spatrick     bool HasMoreInput = true;
59e5dd7070Spatrick     while (HasMoreInput && nextNonWhitespace()) {
60e5dd7070Spatrick       std::string Argument;
61e5dd7070Spatrick       HasMoreInput = parseStringInto(Argument);
62e5dd7070Spatrick       CommandLine.push_back(Argument);
63e5dd7070Spatrick     }
64e5dd7070Spatrick     return CommandLine;
65e5dd7070Spatrick   }
66e5dd7070Spatrick 
67e5dd7070Spatrick  private:
68e5dd7070Spatrick   // All private methods return true if there is more input available.
69e5dd7070Spatrick 
parseStringInto(std::string & String)70e5dd7070Spatrick   bool parseStringInto(std::string &String) {
71e5dd7070Spatrick     do {
72e5dd7070Spatrick       if (*Position == '"') {
73e5dd7070Spatrick         if (!parseDoubleQuotedStringInto(String)) return false;
74e5dd7070Spatrick       } else if (*Position == '\'') {
75e5dd7070Spatrick         if (!parseSingleQuotedStringInto(String)) return false;
76e5dd7070Spatrick       } else {
77e5dd7070Spatrick         if (!parseFreeStringInto(String)) return false;
78e5dd7070Spatrick       }
79e5dd7070Spatrick     } while (*Position != ' ');
80e5dd7070Spatrick     return true;
81e5dd7070Spatrick   }
82e5dd7070Spatrick 
parseDoubleQuotedStringInto(std::string & String)83e5dd7070Spatrick   bool parseDoubleQuotedStringInto(std::string &String) {
84e5dd7070Spatrick     if (!next()) return false;
85e5dd7070Spatrick     while (*Position != '"') {
86e5dd7070Spatrick       if (!skipEscapeCharacter()) return false;
87e5dd7070Spatrick       String.push_back(*Position);
88e5dd7070Spatrick       if (!next()) return false;
89e5dd7070Spatrick     }
90e5dd7070Spatrick     return next();
91e5dd7070Spatrick   }
92e5dd7070Spatrick 
parseSingleQuotedStringInto(std::string & String)93e5dd7070Spatrick   bool parseSingleQuotedStringInto(std::string &String) {
94e5dd7070Spatrick     if (!next()) return false;
95e5dd7070Spatrick     while (*Position != '\'') {
96e5dd7070Spatrick       String.push_back(*Position);
97e5dd7070Spatrick       if (!next()) return false;
98e5dd7070Spatrick     }
99e5dd7070Spatrick     return next();
100e5dd7070Spatrick   }
101e5dd7070Spatrick 
parseFreeStringInto(std::string & String)102e5dd7070Spatrick   bool parseFreeStringInto(std::string &String) {
103e5dd7070Spatrick     do {
104e5dd7070Spatrick       if (!skipEscapeCharacter()) return false;
105e5dd7070Spatrick       String.push_back(*Position);
106e5dd7070Spatrick       if (!next()) return false;
107e5dd7070Spatrick     } while (*Position != ' ' && *Position != '"' && *Position != '\'');
108e5dd7070Spatrick     return true;
109e5dd7070Spatrick   }
110e5dd7070Spatrick 
skipEscapeCharacter()111e5dd7070Spatrick   bool skipEscapeCharacter() {
112e5dd7070Spatrick     if (*Position == '\\') {
113e5dd7070Spatrick       return next();
114e5dd7070Spatrick     }
115e5dd7070Spatrick     return true;
116e5dd7070Spatrick   }
117e5dd7070Spatrick 
nextNonWhitespace()118e5dd7070Spatrick   bool nextNonWhitespace() {
119e5dd7070Spatrick     do {
120e5dd7070Spatrick       if (!next()) return false;
121e5dd7070Spatrick     } while (*Position == ' ');
122e5dd7070Spatrick     return true;
123e5dd7070Spatrick   }
124e5dd7070Spatrick 
next()125e5dd7070Spatrick   bool next() {
126e5dd7070Spatrick     ++Position;
127e5dd7070Spatrick     return Position != Input.end();
128e5dd7070Spatrick   }
129e5dd7070Spatrick 
130e5dd7070Spatrick   const StringRef Input;
131e5dd7070Spatrick   StringRef::iterator Position;
132e5dd7070Spatrick   std::vector<std::string> CommandLine;
133e5dd7070Spatrick };
134e5dd7070Spatrick 
unescapeCommandLine(JSONCommandLineSyntax Syntax,StringRef EscapedCommandLine)135e5dd7070Spatrick std::vector<std::string> unescapeCommandLine(JSONCommandLineSyntax Syntax,
136e5dd7070Spatrick                                              StringRef EscapedCommandLine) {
137e5dd7070Spatrick   if (Syntax == JSONCommandLineSyntax::AutoDetect) {
138*12c85518Srobert #ifdef _WIN32
139*12c85518Srobert     // Assume Windows command line parsing on Win32
140e5dd7070Spatrick     Syntax = JSONCommandLineSyntax::Windows;
141*12c85518Srobert #else
142*12c85518Srobert     Syntax = JSONCommandLineSyntax::Gnu;
143*12c85518Srobert #endif
144e5dd7070Spatrick   }
145e5dd7070Spatrick 
146e5dd7070Spatrick   if (Syntax == JSONCommandLineSyntax::Windows) {
147e5dd7070Spatrick     llvm::BumpPtrAllocator Alloc;
148e5dd7070Spatrick     llvm::StringSaver Saver(Alloc);
149e5dd7070Spatrick     llvm::SmallVector<const char *, 64> T;
150e5dd7070Spatrick     llvm::cl::TokenizeWindowsCommandLine(EscapedCommandLine, Saver, T);
151e5dd7070Spatrick     std::vector<std::string> Result(T.begin(), T.end());
152e5dd7070Spatrick     return Result;
153e5dd7070Spatrick   }
154e5dd7070Spatrick   assert(Syntax == JSONCommandLineSyntax::Gnu);
155e5dd7070Spatrick   CommandLineArgumentParser parser(EscapedCommandLine);
156e5dd7070Spatrick   return parser.parse();
157e5dd7070Spatrick }
158e5dd7070Spatrick 
159e5dd7070Spatrick // This plugin locates a nearby compile_command.json file, and also infers
160e5dd7070Spatrick // compile commands for files not present in the database.
161e5dd7070Spatrick class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin {
162e5dd7070Spatrick   std::unique_ptr<CompilationDatabase>
loadFromDirectory(StringRef Directory,std::string & ErrorMessage)163e5dd7070Spatrick   loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
164e5dd7070Spatrick     SmallString<1024> JSONDatabasePath(Directory);
165e5dd7070Spatrick     llvm::sys::path::append(JSONDatabasePath, "compile_commands.json");
166e5dd7070Spatrick     auto Base = JSONCompilationDatabase::loadFromFile(
167e5dd7070Spatrick         JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);
168e5dd7070Spatrick     return Base ? inferTargetAndDriverMode(
169e5dd7070Spatrick                       inferMissingCompileCommands(expandResponseFiles(
170e5dd7070Spatrick                           std::move(Base), llvm::vfs::getRealFileSystem())))
171e5dd7070Spatrick                 : nullptr;
172e5dd7070Spatrick   }
173e5dd7070Spatrick };
174e5dd7070Spatrick 
175e5dd7070Spatrick } // namespace
176e5dd7070Spatrick 
177e5dd7070Spatrick // Register the JSONCompilationDatabasePlugin with the
178e5dd7070Spatrick // CompilationDatabasePluginRegistry using this statically initialized variable.
179e5dd7070Spatrick static CompilationDatabasePluginRegistry::Add<JSONCompilationDatabasePlugin>
180e5dd7070Spatrick X("json-compilation-database", "Reads JSON formatted compilation databases");
181e5dd7070Spatrick 
182e5dd7070Spatrick namespace clang {
183e5dd7070Spatrick namespace tooling {
184e5dd7070Spatrick 
185e5dd7070Spatrick // This anchor is used to force the linker to link in the generated object file
186e5dd7070Spatrick // and thus register the JSONCompilationDatabasePlugin.
187e5dd7070Spatrick volatile int JSONAnchorSource = 0;
188e5dd7070Spatrick 
189e5dd7070Spatrick } // namespace tooling
190e5dd7070Spatrick } // namespace clang
191e5dd7070Spatrick 
192e5dd7070Spatrick std::unique_ptr<JSONCompilationDatabase>
loadFromFile(StringRef FilePath,std::string & ErrorMessage,JSONCommandLineSyntax Syntax)193e5dd7070Spatrick JSONCompilationDatabase::loadFromFile(StringRef FilePath,
194e5dd7070Spatrick                                       std::string &ErrorMessage,
195e5dd7070Spatrick                                       JSONCommandLineSyntax Syntax) {
196e5dd7070Spatrick   // Don't mmap: if we're a long-lived process, the build system may overwrite.
197e5dd7070Spatrick   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer =
198a9ac8606Spatrick       llvm::MemoryBuffer::getFile(FilePath, /*IsText=*/false,
199e5dd7070Spatrick                                   /*RequiresNullTerminator=*/true,
200e5dd7070Spatrick                                   /*IsVolatile=*/true);
201e5dd7070Spatrick   if (std::error_code Result = DatabaseBuffer.getError()) {
202e5dd7070Spatrick     ErrorMessage = "Error while opening JSON database: " + Result.message();
203e5dd7070Spatrick     return nullptr;
204e5dd7070Spatrick   }
205e5dd7070Spatrick   std::unique_ptr<JSONCompilationDatabase> Database(
206e5dd7070Spatrick       new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
207e5dd7070Spatrick   if (!Database->parse(ErrorMessage))
208e5dd7070Spatrick     return nullptr;
209e5dd7070Spatrick   return Database;
210e5dd7070Spatrick }
211e5dd7070Spatrick 
212e5dd7070Spatrick std::unique_ptr<JSONCompilationDatabase>
loadFromBuffer(StringRef DatabaseString,std::string & ErrorMessage,JSONCommandLineSyntax Syntax)213e5dd7070Spatrick JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString,
214e5dd7070Spatrick                                         std::string &ErrorMessage,
215e5dd7070Spatrick                                         JSONCommandLineSyntax Syntax) {
216e5dd7070Spatrick   std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer(
217a9ac8606Spatrick       llvm::MemoryBuffer::getMemBufferCopy(DatabaseString));
218e5dd7070Spatrick   std::unique_ptr<JSONCompilationDatabase> Database(
219e5dd7070Spatrick       new JSONCompilationDatabase(std::move(DatabaseBuffer), Syntax));
220e5dd7070Spatrick   if (!Database->parse(ErrorMessage))
221e5dd7070Spatrick     return nullptr;
222e5dd7070Spatrick   return Database;
223e5dd7070Spatrick }
224e5dd7070Spatrick 
225e5dd7070Spatrick std::vector<CompileCommand>
getCompileCommands(StringRef FilePath) const226e5dd7070Spatrick JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const {
227e5dd7070Spatrick   SmallString<128> NativeFilePath;
228e5dd7070Spatrick   llvm::sys::path::native(FilePath, NativeFilePath);
229e5dd7070Spatrick 
230e5dd7070Spatrick   std::string Error;
231e5dd7070Spatrick   llvm::raw_string_ostream ES(Error);
232e5dd7070Spatrick   StringRef Match = MatchTrie.findEquivalent(NativeFilePath, ES);
233e5dd7070Spatrick   if (Match.empty())
234e5dd7070Spatrick     return {};
235e5dd7070Spatrick   const auto CommandsRefI = IndexByFile.find(Match);
236e5dd7070Spatrick   if (CommandsRefI == IndexByFile.end())
237e5dd7070Spatrick     return {};
238e5dd7070Spatrick   std::vector<CompileCommand> Commands;
239e5dd7070Spatrick   getCommands(CommandsRefI->getValue(), Commands);
240e5dd7070Spatrick   return Commands;
241e5dd7070Spatrick }
242e5dd7070Spatrick 
243e5dd7070Spatrick std::vector<std::string>
getAllFiles() const244e5dd7070Spatrick JSONCompilationDatabase::getAllFiles() const {
245e5dd7070Spatrick   std::vector<std::string> Result;
246e5dd7070Spatrick   for (const auto &CommandRef : IndexByFile)
247e5dd7070Spatrick     Result.push_back(CommandRef.first().str());
248e5dd7070Spatrick   return Result;
249e5dd7070Spatrick }
250e5dd7070Spatrick 
251e5dd7070Spatrick std::vector<CompileCommand>
getAllCompileCommands() const252e5dd7070Spatrick JSONCompilationDatabase::getAllCompileCommands() const {
253e5dd7070Spatrick   std::vector<CompileCommand> Commands;
254e5dd7070Spatrick   getCommands(AllCommands, Commands);
255e5dd7070Spatrick   return Commands;
256e5dd7070Spatrick }
257e5dd7070Spatrick 
stripExecutableExtension(llvm::StringRef Name)258e5dd7070Spatrick static llvm::StringRef stripExecutableExtension(llvm::StringRef Name) {
259e5dd7070Spatrick   Name.consume_back(".exe");
260e5dd7070Spatrick   return Name;
261e5dd7070Spatrick }
262e5dd7070Spatrick 
263e5dd7070Spatrick // There are compiler-wrappers (ccache, distcc, gomacc) that take the "real"
264e5dd7070Spatrick // compiler as an argument, e.g. distcc gcc -O3 foo.c.
265e5dd7070Spatrick // These end up in compile_commands.json when people set CC="distcc gcc".
266e5dd7070Spatrick // Clang's driver doesn't understand this, so we need to unwrap.
unwrapCommand(std::vector<std::string> & Args)267e5dd7070Spatrick static bool unwrapCommand(std::vector<std::string> &Args) {
268e5dd7070Spatrick   if (Args.size() < 2)
269e5dd7070Spatrick     return false;
270e5dd7070Spatrick   StringRef Wrapper =
271e5dd7070Spatrick       stripExecutableExtension(llvm::sys::path::filename(Args.front()));
272a9ac8606Spatrick   if (Wrapper == "distcc" || Wrapper == "gomacc" || Wrapper == "ccache" ||
273a9ac8606Spatrick       Wrapper == "sccache") {
274e5dd7070Spatrick     // Most of these wrappers support being invoked 3 ways:
275e5dd7070Spatrick     // `distcc g++ file.c` This is the mode we're trying to match.
276e5dd7070Spatrick     //                     We need to drop `distcc`.
277e5dd7070Spatrick     // `distcc file.c`     This acts like compiler is cc or similar.
278e5dd7070Spatrick     //                     Clang's driver can handle this, no change needed.
279e5dd7070Spatrick     // `g++ file.c`        g++ is a symlink to distcc.
280e5dd7070Spatrick     //                     We don't even notice this case, and all is well.
281e5dd7070Spatrick     //
282e5dd7070Spatrick     // We need to distinguish between the first and second case.
283e5dd7070Spatrick     // The wrappers themselves don't take flags, so Args[1] is a compiler flag,
284e5dd7070Spatrick     // an input file, or a compiler. Inputs have extensions, compilers don't.
285e5dd7070Spatrick     bool HasCompiler =
286e5dd7070Spatrick         (Args[1][0] != '-') &&
287e5dd7070Spatrick         !llvm::sys::path::has_extension(stripExecutableExtension(Args[1]));
288e5dd7070Spatrick     if (HasCompiler) {
289e5dd7070Spatrick       Args.erase(Args.begin());
290e5dd7070Spatrick       return true;
291e5dd7070Spatrick     }
292e5dd7070Spatrick     // If !HasCompiler, wrappers act like GCC. Fine: so do we.
293e5dd7070Spatrick   }
294e5dd7070Spatrick   return false;
295e5dd7070Spatrick }
296e5dd7070Spatrick 
297e5dd7070Spatrick static std::vector<std::string>
nodeToCommandLine(JSONCommandLineSyntax Syntax,const std::vector<llvm::yaml::ScalarNode * > & Nodes)298e5dd7070Spatrick nodeToCommandLine(JSONCommandLineSyntax Syntax,
299e5dd7070Spatrick                   const std::vector<llvm::yaml::ScalarNode *> &Nodes) {
300e5dd7070Spatrick   SmallString<1024> Storage;
301e5dd7070Spatrick   std::vector<std::string> Arguments;
302e5dd7070Spatrick   if (Nodes.size() == 1)
303e5dd7070Spatrick     Arguments = unescapeCommandLine(Syntax, Nodes[0]->getValue(Storage));
304e5dd7070Spatrick   else
305e5dd7070Spatrick     for (const auto *Node : Nodes)
306ec727ea7Spatrick       Arguments.push_back(std::string(Node->getValue(Storage)));
307e5dd7070Spatrick   // There may be multiple wrappers: using distcc and ccache together is common.
308e5dd7070Spatrick   while (unwrapCommand(Arguments))
309e5dd7070Spatrick     ;
310e5dd7070Spatrick   return Arguments;
311e5dd7070Spatrick }
312e5dd7070Spatrick 
getCommands(ArrayRef<CompileCommandRef> CommandsRef,std::vector<CompileCommand> & Commands) const313e5dd7070Spatrick void JSONCompilationDatabase::getCommands(
314e5dd7070Spatrick     ArrayRef<CompileCommandRef> CommandsRef,
315e5dd7070Spatrick     std::vector<CompileCommand> &Commands) const {
316e5dd7070Spatrick   for (const auto &CommandRef : CommandsRef) {
317e5dd7070Spatrick     SmallString<8> DirectoryStorage;
318e5dd7070Spatrick     SmallString<32> FilenameStorage;
319e5dd7070Spatrick     SmallString<32> OutputStorage;
320e5dd7070Spatrick     auto Output = std::get<3>(CommandRef);
321e5dd7070Spatrick     Commands.emplace_back(
322e5dd7070Spatrick         std::get<0>(CommandRef)->getValue(DirectoryStorage),
323e5dd7070Spatrick         std::get<1>(CommandRef)->getValue(FilenameStorage),
324e5dd7070Spatrick         nodeToCommandLine(Syntax, std::get<2>(CommandRef)),
325e5dd7070Spatrick         Output ? Output->getValue(OutputStorage) : "");
326e5dd7070Spatrick   }
327e5dd7070Spatrick }
328e5dd7070Spatrick 
parse(std::string & ErrorMessage)329e5dd7070Spatrick bool JSONCompilationDatabase::parse(std::string &ErrorMessage) {
330e5dd7070Spatrick   llvm::yaml::document_iterator I = YAMLStream.begin();
331e5dd7070Spatrick   if (I == YAMLStream.end()) {
332e5dd7070Spatrick     ErrorMessage = "Error while parsing YAML.";
333e5dd7070Spatrick     return false;
334e5dd7070Spatrick   }
335e5dd7070Spatrick   llvm::yaml::Node *Root = I->getRoot();
336e5dd7070Spatrick   if (!Root) {
337e5dd7070Spatrick     ErrorMessage = "Error while parsing YAML.";
338e5dd7070Spatrick     return false;
339e5dd7070Spatrick   }
340e5dd7070Spatrick   auto *Array = dyn_cast<llvm::yaml::SequenceNode>(Root);
341e5dd7070Spatrick   if (!Array) {
342e5dd7070Spatrick     ErrorMessage = "Expected array.";
343e5dd7070Spatrick     return false;
344e5dd7070Spatrick   }
345e5dd7070Spatrick   for (auto &NextObject : *Array) {
346e5dd7070Spatrick     auto *Object = dyn_cast<llvm::yaml::MappingNode>(&NextObject);
347e5dd7070Spatrick     if (!Object) {
348e5dd7070Spatrick       ErrorMessage = "Expected object.";
349e5dd7070Spatrick       return false;
350e5dd7070Spatrick     }
351e5dd7070Spatrick     llvm::yaml::ScalarNode *Directory = nullptr;
352*12c85518Srobert     std::optional<std::vector<llvm::yaml::ScalarNode *>> Command;
353e5dd7070Spatrick     llvm::yaml::ScalarNode *File = nullptr;
354e5dd7070Spatrick     llvm::yaml::ScalarNode *Output = nullptr;
355e5dd7070Spatrick     for (auto& NextKeyValue : *Object) {
356e5dd7070Spatrick       auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
357e5dd7070Spatrick       if (!KeyString) {
358e5dd7070Spatrick         ErrorMessage = "Expected strings as key.";
359e5dd7070Spatrick         return false;
360e5dd7070Spatrick       }
361e5dd7070Spatrick       SmallString<10> KeyStorage;
362e5dd7070Spatrick       StringRef KeyValue = KeyString->getValue(KeyStorage);
363e5dd7070Spatrick       llvm::yaml::Node *Value = NextKeyValue.getValue();
364e5dd7070Spatrick       if (!Value) {
365e5dd7070Spatrick         ErrorMessage = "Expected value.";
366e5dd7070Spatrick         return false;
367e5dd7070Spatrick       }
368e5dd7070Spatrick       auto *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value);
369e5dd7070Spatrick       auto *SequenceString = dyn_cast<llvm::yaml::SequenceNode>(Value);
370a9ac8606Spatrick       if (KeyValue == "arguments") {
371a9ac8606Spatrick         if (!SequenceString) {
372e5dd7070Spatrick           ErrorMessage = "Expected sequence as value.";
373e5dd7070Spatrick           return false;
374e5dd7070Spatrick         }
375e5dd7070Spatrick         Command = std::vector<llvm::yaml::ScalarNode *>();
376e5dd7070Spatrick         for (auto &Argument : *SequenceString) {
377e5dd7070Spatrick           auto *Scalar = dyn_cast<llvm::yaml::ScalarNode>(&Argument);
378e5dd7070Spatrick           if (!Scalar) {
379e5dd7070Spatrick             ErrorMessage = "Only strings are allowed in 'arguments'.";
380e5dd7070Spatrick             return false;
381e5dd7070Spatrick           }
382e5dd7070Spatrick           Command->push_back(Scalar);
383e5dd7070Spatrick         }
384a9ac8606Spatrick       } else {
385a9ac8606Spatrick         if (!ValueString) {
386a9ac8606Spatrick           ErrorMessage = "Expected string as value.";
387a9ac8606Spatrick           return false;
388a9ac8606Spatrick         }
389a9ac8606Spatrick         if (KeyValue == "directory") {
390a9ac8606Spatrick           Directory = ValueString;
391e5dd7070Spatrick         } else if (KeyValue == "command") {
392e5dd7070Spatrick           if (!Command)
393e5dd7070Spatrick             Command = std::vector<llvm::yaml::ScalarNode *>(1, ValueString);
394e5dd7070Spatrick         } else if (KeyValue == "file") {
395e5dd7070Spatrick           File = ValueString;
396e5dd7070Spatrick         } else if (KeyValue == "output") {
397e5dd7070Spatrick           Output = ValueString;
398e5dd7070Spatrick         } else {
399a9ac8606Spatrick           ErrorMessage =
400a9ac8606Spatrick               ("Unknown key: \"" + KeyString->getRawValue() + "\"").str();
401e5dd7070Spatrick           return false;
402e5dd7070Spatrick         }
403e5dd7070Spatrick       }
404a9ac8606Spatrick     }
405e5dd7070Spatrick     if (!File) {
406e5dd7070Spatrick       ErrorMessage = "Missing key: \"file\".";
407e5dd7070Spatrick       return false;
408e5dd7070Spatrick     }
409e5dd7070Spatrick     if (!Command) {
410e5dd7070Spatrick       ErrorMessage = "Missing key: \"command\" or \"arguments\".";
411e5dd7070Spatrick       return false;
412e5dd7070Spatrick     }
413e5dd7070Spatrick     if (!Directory) {
414e5dd7070Spatrick       ErrorMessage = "Missing key: \"directory\".";
415e5dd7070Spatrick       return false;
416e5dd7070Spatrick     }
417e5dd7070Spatrick     SmallString<8> FileStorage;
418e5dd7070Spatrick     StringRef FileName = File->getValue(FileStorage);
419e5dd7070Spatrick     SmallString<128> NativeFilePath;
420e5dd7070Spatrick     if (llvm::sys::path::is_relative(FileName)) {
421e5dd7070Spatrick       SmallString<8> DirectoryStorage;
422*12c85518Srobert       SmallString<128> AbsolutePath(Directory->getValue(DirectoryStorage));
423e5dd7070Spatrick       llvm::sys::path::append(AbsolutePath, FileName);
424e5dd7070Spatrick       llvm::sys::path::native(AbsolutePath, NativeFilePath);
425e5dd7070Spatrick     } else {
426e5dd7070Spatrick       llvm::sys::path::native(FileName, NativeFilePath);
427e5dd7070Spatrick     }
428*12c85518Srobert     llvm::sys::path::remove_dots(NativeFilePath, /*remove_dot_dot=*/true);
429e5dd7070Spatrick     auto Cmd = CompileCommandRef(Directory, File, *Command, Output);
430e5dd7070Spatrick     IndexByFile[NativeFilePath].push_back(Cmd);
431e5dd7070Spatrick     AllCommands.push_back(Cmd);
432e5dd7070Spatrick     MatchTrie.insert(NativeFilePath);
433e5dd7070Spatrick   }
434e5dd7070Spatrick   return true;
435e5dd7070Spatrick }
436