xref: /llvm-project/clang/unittests/Tooling/CompilationDatabaseTest.cpp (revision 2b3d49b610bd2a45884115edcb21110bfa325f51)
1 //===- unittest/Tooling/CompilationDatabaseTest.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 #include "clang/AST/DeclCXX.h"
10 #include "clang/AST/DeclGroup.h"
11 #include "clang/Frontend/FrontendAction.h"
12 #include "clang/Tooling/CompilationDatabase.h"
13 #include "clang/Tooling/FileMatchTrie.h"
14 #include "clang/Tooling/JSONCompilationDatabase.h"
15 #include "clang/Tooling/Tooling.h"
16 #include "llvm/Support/Path.h"
17 #include "llvm/Support/TargetSelect.h"
18 #include "gmock/gmock.h"
19 #include "gtest/gtest.h"
20 
21 namespace clang {
22 namespace tooling {
23 
24 using testing::ElementsAre;
25 using testing::EndsWith;
26 
27 static void expectFailure(StringRef JSONDatabase, StringRef Explanation) {
28   std::string ErrorMessage;
29   EXPECT_EQ(nullptr,
30             JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage,
31                                                     JSONCommandLineSyntax::Gnu))
32       << "Expected an error because of: " << Explanation.str();
33 }
34 
35 TEST(JSONCompilationDatabase, ErrsOnInvalidFormat) {
36   expectFailure("", "Empty database");
37   expectFailure("{", "Invalid JSON");
38   expectFailure("[[]]", "Array instead of object");
39   expectFailure("[{\"a\":[]}]", "Array instead of value");
40   expectFailure("[{\"a\":\"b\"}]", "Unknown key");
41   expectFailure("[{[]:\"\"}]", "Incorrectly typed entry");
42   expectFailure("[{}]", "Empty entry");
43   expectFailure("[{\"directory\":\"\",\"command\":\"\"}]", "Missing file");
44   expectFailure("[{\"directory\":\"\",\"file\":\"\"}]", "Missing command or arguments");
45   expectFailure("[{\"command\":\"\",\"file\":\"\"}]", "Missing directory");
46   expectFailure("[{\"directory\":\"\",\"arguments\":[]}]", "Missing file");
47   expectFailure("[{\"arguments\":\"\",\"file\":\"\"}]", "Missing directory");
48   expectFailure("[{\"directory\":\"\",\"arguments\":\"\",\"file\":\"\"}]", "Arguments not array");
49   expectFailure("[{\"directory\":\"\",\"command\":[],\"file\":\"\"}]", "Command not string");
50   expectFailure("[{\"directory\":\"\",\"arguments\":[[]],\"file\":\"\"}]",
51                 "Arguments contain non-string");
52   expectFailure("[{\"output\":[]}]", "Expected strings as value.");
53 }
54 
55 static std::vector<std::string> getAllFiles(StringRef JSONDatabase,
56                                             std::string &ErrorMessage,
57                                             JSONCommandLineSyntax Syntax) {
58   std::unique_ptr<CompilationDatabase> Database(
59       JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage,
60                                               Syntax));
61   if (!Database) {
62     ADD_FAILURE() << ErrorMessage;
63     return std::vector<std::string>();
64   }
65   return Database->getAllFiles();
66 }
67 
68 static std::vector<CompileCommand>
69 getAllCompileCommands(JSONCommandLineSyntax Syntax, StringRef JSONDatabase,
70                       std::string &ErrorMessage) {
71   std::unique_ptr<CompilationDatabase> Database(
72       JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage,
73                                               Syntax));
74   if (!Database) {
75     ADD_FAILURE() << ErrorMessage;
76     return std::vector<CompileCommand>();
77   }
78   return Database->getAllCompileCommands();
79 }
80 
81 TEST(JSONCompilationDatabase, GetAllFiles) {
82   std::string ErrorMessage;
83   EXPECT_EQ(std::vector<std::string>(),
84             getAllFiles("[]", ErrorMessage, JSONCommandLineSyntax::Gnu))
85       << ErrorMessage;
86 
87   std::vector<std::string> expected_files;
88   SmallString<16> PathStorage;
89   llvm::sys::path::native("//net/dir/file1", PathStorage);
90   expected_files.push_back(PathStorage.str());
91   llvm::sys::path::native("//net/dir/file2", PathStorage);
92   expected_files.push_back(PathStorage.str());
93   llvm::sys::path::native("//net/file1", PathStorage);
94   expected_files.push_back(PathStorage.str());
95   EXPECT_EQ(expected_files,
96             getAllFiles("[{\"directory\":\"//net/dir\","
97                         "\"command\":\"command\","
98                         "\"file\":\"file1\"},"
99                         " {\"directory\":\"//net/dir\","
100                         "\"command\":\"command\","
101                         "\"file\":\"../file1\"},"
102                         " {\"directory\":\"//net/dir\","
103                         "\"command\":\"command\","
104                         "\"file\":\"file2\"}]",
105                         ErrorMessage, JSONCommandLineSyntax::Gnu))
106       << ErrorMessage;
107 }
108 
109 TEST(JSONCompilationDatabase, GetAllCompileCommands) {
110   std::string ErrorMessage;
111   EXPECT_EQ(
112       0u, getAllCompileCommands(JSONCommandLineSyntax::Gnu, "[]", ErrorMessage)
113               .size())
114       << ErrorMessage;
115 
116   StringRef Directory1("//net/dir1");
117   StringRef FileName1("file1");
118   StringRef Command1("command1");
119   StringRef Output1("file1.o");
120   StringRef Directory2("//net/dir2");
121   StringRef FileName2("file2");
122   StringRef Command2("command2");
123   StringRef Output2("");
124 
125   std::vector<CompileCommand> Commands = getAllCompileCommands(
126       JSONCommandLineSyntax::Gnu,
127       ("[{\"directory\":\"" + Directory1 + "\"," + "\"command\":\"" + Command1 +
128        "\","
129        "\"file\":\"" +
130        FileName1 + "\", \"output\":\"" +
131        Output1 + "\"},"
132                    " {\"directory\":\"" +
133        Directory2 + "\"," + "\"command\":\"" + Command2 + "\","
134                                                           "\"file\":\"" +
135        FileName2 + "\"}]")
136           .str(),
137       ErrorMessage);
138   EXPECT_EQ(2U, Commands.size()) << ErrorMessage;
139   EXPECT_EQ(Directory1, Commands[0].Directory) << ErrorMessage;
140   EXPECT_EQ(FileName1, Commands[0].Filename) << ErrorMessage;
141   EXPECT_EQ(Output1, Commands[0].Output) << ErrorMessage;
142   ASSERT_EQ(1u, Commands[0].CommandLine.size());
143   EXPECT_EQ(Command1, Commands[0].CommandLine[0]) << ErrorMessage;
144   EXPECT_EQ(Directory2, Commands[1].Directory) << ErrorMessage;
145   EXPECT_EQ(FileName2, Commands[1].Filename) << ErrorMessage;
146   EXPECT_EQ(Output2, Commands[1].Output) << ErrorMessage;
147   ASSERT_EQ(1u, Commands[1].CommandLine.size());
148   EXPECT_EQ(Command2, Commands[1].CommandLine[0]) << ErrorMessage;
149 
150   // Check that order is preserved.
151   Commands = getAllCompileCommands(
152       JSONCommandLineSyntax::Gnu,
153       ("[{\"directory\":\"" + Directory2 + "\"," + "\"command\":\"" + Command2 +
154        "\","
155        "\"file\":\"" +
156        FileName2 + "\"},"
157                    " {\"directory\":\"" +
158        Directory1 + "\"," + "\"command\":\"" + Command1 + "\","
159                                                           "\"file\":\"" +
160        FileName1 + "\"}]")
161           .str(),
162       ErrorMessage);
163   EXPECT_EQ(2U, Commands.size()) << ErrorMessage;
164   EXPECT_EQ(Directory2, Commands[0].Directory) << ErrorMessage;
165   EXPECT_EQ(FileName2, Commands[0].Filename) << ErrorMessage;
166   ASSERT_EQ(1u, Commands[0].CommandLine.size());
167   EXPECT_EQ(Command2, Commands[0].CommandLine[0]) << ErrorMessage;
168   EXPECT_EQ(Directory1, Commands[1].Directory) << ErrorMessage;
169   EXPECT_EQ(FileName1, Commands[1].Filename) << ErrorMessage;
170   ASSERT_EQ(1u, Commands[1].CommandLine.size());
171   EXPECT_EQ(Command1, Commands[1].CommandLine[0]) << ErrorMessage;
172 }
173 
174 static CompileCommand findCompileArgsInJsonDatabase(StringRef FileName,
175                                                     StringRef JSONDatabase,
176                                                     std::string &ErrorMessage) {
177   std::unique_ptr<CompilationDatabase> Database(
178       JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage,
179                                               JSONCommandLineSyntax::Gnu));
180   if (!Database)
181     return CompileCommand();
182   std::vector<CompileCommand> Commands = Database->getCompileCommands(FileName);
183   EXPECT_LE(Commands.size(), 1u);
184   if (Commands.empty())
185     return CompileCommand();
186   return Commands[0];
187 }
188 
189 TEST(JSONCompilationDatabase, ArgumentsPreferredOverCommand) {
190    StringRef Directory("//net/dir");
191    StringRef FileName("//net/dir/filename");
192    StringRef Command("command");
193    StringRef Arguments = "arguments";
194    Twine ArgumentsAccumulate;
195    std::string ErrorMessage;
196    CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
197       FileName,
198       ("[{\"directory\":\"" + Directory + "\","
199          "\"arguments\":[\"" + Arguments + "\"],"
200          "\"command\":\"" + Command + "\","
201          "\"file\":\"" + FileName + "\"}]").str(),
202       ErrorMessage);
203    EXPECT_EQ(Directory, FoundCommand.Directory) << ErrorMessage;
204    EXPECT_EQ(1u, FoundCommand.CommandLine.size()) << ErrorMessage;
205    EXPECT_EQ(Arguments, FoundCommand.CommandLine[0]) << ErrorMessage;
206 }
207 
208 struct FakeComparator : public PathComparator {
209   ~FakeComparator() override {}
210   bool equivalent(StringRef FileA, StringRef FileB) const override {
211     return FileA.equals_lower(FileB);
212   }
213 };
214 
215 class FileMatchTrieTest : public ::testing::Test {
216 protected:
217   FileMatchTrieTest() : Trie(new FakeComparator()) {}
218 
219   StringRef find(StringRef Path) {
220     llvm::raw_string_ostream ES(Error);
221     return Trie.findEquivalent(Path, ES);
222   }
223 
224   FileMatchTrie Trie;
225   std::string Error;
226 };
227 
228 TEST_F(FileMatchTrieTest, InsertingRelativePath) {
229   Trie.insert("//net/path/file.cc");
230   Trie.insert("file.cc");
231   EXPECT_EQ("//net/path/file.cc", find("//net/path/file.cc"));
232 }
233 
234 TEST_F(FileMatchTrieTest, MatchingRelativePath) {
235   EXPECT_EQ("", find("file.cc"));
236 }
237 
238 TEST_F(FileMatchTrieTest, ReturnsBestResults) {
239   Trie.insert("//net/d/c/b.cc");
240   Trie.insert("//net/d/b/b.cc");
241   EXPECT_EQ("//net/d/b/b.cc", find("//net/d/b/b.cc"));
242 }
243 
244 TEST_F(FileMatchTrieTest, HandlesSymlinks) {
245   Trie.insert("//net/AA/file.cc");
246   EXPECT_EQ("//net/AA/file.cc", find("//net/aa/file.cc"));
247 }
248 
249 TEST_F(FileMatchTrieTest, ReportsSymlinkAmbiguity) {
250   Trie.insert("//net/Aa/file.cc");
251   Trie.insert("//net/aA/file.cc");
252   EXPECT_TRUE(find("//net/aa/file.cc").empty());
253   EXPECT_EQ("Path is ambiguous", Error);
254 }
255 
256 TEST_F(FileMatchTrieTest, LongerMatchingSuffixPreferred) {
257   Trie.insert("//net/src/Aa/file.cc");
258   Trie.insert("//net/src/aA/file.cc");
259   Trie.insert("//net/SRC/aa/file.cc");
260   EXPECT_EQ("//net/SRC/aa/file.cc", find("//net/src/aa/file.cc"));
261 }
262 
263 TEST_F(FileMatchTrieTest, EmptyTrie) {
264   EXPECT_TRUE(find("//net/some/path").empty());
265 }
266 
267 TEST_F(FileMatchTrieTest, NoResult) {
268   Trie.insert("//net/somepath/otherfile.cc");
269   Trie.insert("//net/otherpath/somefile.cc");
270   EXPECT_EQ("", find("//net/somepath/somefile.cc"));
271 }
272 
273 TEST_F(FileMatchTrieTest, RootElementDifferent) {
274   Trie.insert("//net/path/file.cc");
275   Trie.insert("//net/otherpath/file.cc");
276   EXPECT_EQ("//net/path/file.cc", find("//net/path/file.cc"));
277 }
278 
279 TEST_F(FileMatchTrieTest, CannotResolveRelativePath) {
280   EXPECT_EQ("", find("relative-path.cc"));
281   EXPECT_EQ("Cannot resolve relative paths", Error);
282 }
283 
284 TEST(findCompileArgsInJsonDatabase, FindsNothingIfEmpty) {
285   std::string ErrorMessage;
286   CompileCommand NotFound = findCompileArgsInJsonDatabase(
287     "a-file.cpp", "", ErrorMessage);
288   EXPECT_TRUE(NotFound.CommandLine.empty()) << ErrorMessage;
289   EXPECT_TRUE(NotFound.Directory.empty()) << ErrorMessage;
290 }
291 
292 TEST(findCompileArgsInJsonDatabase, ReadsSingleEntry) {
293   StringRef Directory("//net/some/directory");
294   StringRef FileName("//net/path/to/a-file.cpp");
295   StringRef Command("//net/path/to/compiler and some arguments");
296   std::string ErrorMessage;
297   CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
298     FileName,
299     ("[{\"directory\":\"" + Directory + "\"," +
300        "\"command\":\"" + Command + "\","
301        "\"file\":\"" + FileName + "\"}]").str(),
302     ErrorMessage);
303   EXPECT_EQ(Directory, FoundCommand.Directory) << ErrorMessage;
304   ASSERT_EQ(4u, FoundCommand.CommandLine.size()) << ErrorMessage;
305   EXPECT_EQ("//net/path/to/compiler",
306             FoundCommand.CommandLine[0]) << ErrorMessage;
307   EXPECT_EQ("and", FoundCommand.CommandLine[1]) << ErrorMessage;
308   EXPECT_EQ("some", FoundCommand.CommandLine[2]) << ErrorMessage;
309   EXPECT_EQ("arguments", FoundCommand.CommandLine[3]) << ErrorMessage;
310 
311   CompileCommand NotFound = findCompileArgsInJsonDatabase(
312     "a-file.cpp",
313     ("[{\"directory\":\"" + Directory + "\"," +
314        "\"command\":\"" + Command + "\","
315        "\"file\":\"" + FileName + "\"}]").str(),
316     ErrorMessage);
317   EXPECT_TRUE(NotFound.Directory.empty()) << ErrorMessage;
318   EXPECT_TRUE(NotFound.CommandLine.empty()) << ErrorMessage;
319 }
320 
321 TEST(findCompileArgsInJsonDatabase, ReadsCompileCommandLinesWithSpaces) {
322   StringRef Directory("//net/some/directory");
323   StringRef FileName("//net/path/to/a-file.cpp");
324   StringRef Command("\\\"//net/path to compiler\\\" \\\"and an argument\\\"");
325   std::string ErrorMessage;
326   CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
327     FileName,
328     ("[{\"directory\":\"" + Directory + "\"," +
329        "\"command\":\"" + Command + "\","
330        "\"file\":\"" + FileName + "\"}]").str(),
331     ErrorMessage);
332   ASSERT_EQ(2u, FoundCommand.CommandLine.size());
333   EXPECT_EQ("//net/path to compiler",
334             FoundCommand.CommandLine[0]) << ErrorMessage;
335   EXPECT_EQ("and an argument", FoundCommand.CommandLine[1]) << ErrorMessage;
336 }
337 
338 TEST(findCompileArgsInJsonDatabase, ReadsDirectoryWithSpaces) {
339   StringRef Directory("//net/some directory / with spaces");
340   StringRef FileName("//net/path/to/a-file.cpp");
341   StringRef Command("a command");
342   std::string ErrorMessage;
343   CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
344     FileName,
345     ("[{\"directory\":\"" + Directory + "\"," +
346        "\"command\":\"" + Command + "\","
347        "\"file\":\"" + FileName + "\"}]").str(),
348     ErrorMessage);
349   EXPECT_EQ(Directory, FoundCommand.Directory) << ErrorMessage;
350 }
351 
352 TEST(findCompileArgsInJsonDatabase, FindsEntry) {
353   StringRef Directory("//net/directory");
354   StringRef FileName("file");
355   StringRef Command("command");
356   std::string JsonDatabase = "[";
357   for (int I = 0; I < 10; ++I) {
358     if (I > 0) JsonDatabase += ",";
359     JsonDatabase +=
360       ("{\"directory\":\"" + Directory + Twine(I) + "\"," +
361         "\"command\":\"" + Command + Twine(I) + "\","
362         "\"file\":\"" + FileName + Twine(I) + "\"}").str();
363   }
364   JsonDatabase += "]";
365   std::string ErrorMessage;
366   CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
367     "//net/directory4/file4", JsonDatabase, ErrorMessage);
368   EXPECT_EQ("//net/directory4", FoundCommand.Directory) << ErrorMessage;
369   ASSERT_EQ(1u, FoundCommand.CommandLine.size()) << ErrorMessage;
370   EXPECT_EQ("command4", FoundCommand.CommandLine[0]) << ErrorMessage;
371 }
372 
373 TEST(findCompileArgsInJsonDatabase, ParsesCompilerWrappers) {
374   StringRef Directory("//net/dir");
375   StringRef FileName("//net/dir/filename");
376   std::vector<std::pair<std::string, std::string>> Cases = {
377       {"distcc gcc foo.c", "gcc foo.c"},
378       {"gomacc clang++ foo.c", "clang++ foo.c"},
379       {"ccache gcc foo.c", "gcc foo.c"},
380       {"ccache.exe gcc foo.c", "gcc foo.c"},
381       {"ccache g++.exe foo.c", "g++.exe foo.c"},
382       {"ccache distcc gcc foo.c", "gcc foo.c"},
383 
384       {"distcc foo.c", "distcc foo.c"},
385       {"distcc -I/foo/bar foo.c", "distcc -I/foo/bar foo.c"},
386   };
387   std::string ErrorMessage;
388 
389   for (const auto &Case : Cases) {
390     std::string DB =
391         R"([{"directory":"//net/dir", "file":"//net/dir/foo.c", "command":")" +
392         Case.first + "\"}]";
393     CompileCommand FoundCommand =
394         findCompileArgsInJsonDatabase("//net/dir/foo.c", DB, ErrorMessage);
395     EXPECT_EQ(Case.second, llvm::join(FoundCommand.CommandLine, " "))
396         << Case.first;
397   }
398 }
399 
400 static std::vector<std::string> unescapeJsonCommandLine(StringRef Command) {
401   std::string JsonDatabase =
402     ("[{\"directory\":\"//net/root\", \"file\":\"test\", \"command\": \"" +
403      Command + "\"}]").str();
404   std::string ErrorMessage;
405   CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
406     "//net/root/test", JsonDatabase, ErrorMessage);
407   EXPECT_TRUE(ErrorMessage.empty()) << ErrorMessage;
408   return FoundCommand.CommandLine;
409 }
410 
411 TEST(unescapeJsonCommandLine, ReturnsEmptyArrayOnEmptyString) {
412   std::vector<std::string> Result = unescapeJsonCommandLine("");
413   EXPECT_TRUE(Result.empty());
414 }
415 
416 TEST(unescapeJsonCommandLine, SplitsOnSpaces) {
417   std::vector<std::string> Result = unescapeJsonCommandLine("a b c");
418   ASSERT_EQ(3ul, Result.size());
419   EXPECT_EQ("a", Result[0]);
420   EXPECT_EQ("b", Result[1]);
421   EXPECT_EQ("c", Result[2]);
422 }
423 
424 TEST(unescapeJsonCommandLine, MungesMultipleSpaces) {
425   std::vector<std::string> Result = unescapeJsonCommandLine("   a   b   ");
426   ASSERT_EQ(2ul, Result.size());
427   EXPECT_EQ("a", Result[0]);
428   EXPECT_EQ("b", Result[1]);
429 }
430 
431 TEST(unescapeJsonCommandLine, UnescapesBackslashCharacters) {
432   std::vector<std::string> Backslash = unescapeJsonCommandLine("a\\\\\\\\");
433   ASSERT_EQ(1ul, Backslash.size());
434   EXPECT_EQ("a\\", Backslash[0]);
435   std::vector<std::string> Quote = unescapeJsonCommandLine("a\\\\\\\"");
436   ASSERT_EQ(1ul, Quote.size());
437   EXPECT_EQ("a\"", Quote[0]);
438 }
439 
440 TEST(unescapeJsonCommandLine, DoesNotMungeSpacesBetweenQuotes) {
441   std::vector<std::string> Result = unescapeJsonCommandLine("\\\"  a  b  \\\"");
442   ASSERT_EQ(1ul, Result.size());
443   EXPECT_EQ("  a  b  ", Result[0]);
444 }
445 
446 TEST(unescapeJsonCommandLine, AllowsMultipleQuotedArguments) {
447   std::vector<std::string> Result = unescapeJsonCommandLine(
448       "  \\\" a \\\"  \\\" b \\\"  ");
449   ASSERT_EQ(2ul, Result.size());
450   EXPECT_EQ(" a ", Result[0]);
451   EXPECT_EQ(" b ", Result[1]);
452 }
453 
454 TEST(unescapeJsonCommandLine, AllowsEmptyArgumentsInQuotes) {
455   std::vector<std::string> Result = unescapeJsonCommandLine(
456       "\\\"\\\"\\\"\\\"");
457   ASSERT_EQ(1ul, Result.size());
458   EXPECT_TRUE(Result[0].empty()) << Result[0];
459 }
460 
461 TEST(unescapeJsonCommandLine, ParsesEscapedQuotesInQuotedStrings) {
462   std::vector<std::string> Result = unescapeJsonCommandLine(
463       "\\\"\\\\\\\"\\\"");
464   ASSERT_EQ(1ul, Result.size());
465   EXPECT_EQ("\"", Result[0]);
466 }
467 
468 TEST(unescapeJsonCommandLine, ParsesMultipleArgumentsWithEscapedCharacters) {
469   std::vector<std::string> Result = unescapeJsonCommandLine(
470       "  \\\\\\\"  \\\"a \\\\\\\" b \\\"     \\\"and\\\\\\\\c\\\"   \\\\\\\"");
471   ASSERT_EQ(4ul, Result.size());
472   EXPECT_EQ("\"", Result[0]);
473   EXPECT_EQ("a \" b ", Result[1]);
474   EXPECT_EQ("and\\c", Result[2]);
475   EXPECT_EQ("\"", Result[3]);
476 }
477 
478 TEST(unescapeJsonCommandLine, ParsesStringsWithoutSpacesIntoSingleArgument) {
479   std::vector<std::string> QuotedNoSpaces = unescapeJsonCommandLine(
480       "\\\"a\\\"\\\"b\\\"");
481   ASSERT_EQ(1ul, QuotedNoSpaces.size());
482   EXPECT_EQ("ab", QuotedNoSpaces[0]);
483 
484   std::vector<std::string> MixedNoSpaces = unescapeJsonCommandLine(
485       "\\\"a\\\"bcd\\\"ef\\\"\\\"\\\"\\\"g\\\"");
486   ASSERT_EQ(1ul, MixedNoSpaces.size());
487   EXPECT_EQ("abcdefg", MixedNoSpaces[0]);
488 }
489 
490 TEST(unescapeJsonCommandLine, ParsesQuotedStringWithoutClosingQuote) {
491   std::vector<std::string> Unclosed = unescapeJsonCommandLine("\\\"abc");
492   ASSERT_EQ(1ul, Unclosed.size());
493   EXPECT_EQ("abc", Unclosed[0]);
494 
495   std::vector<std::string> Empty = unescapeJsonCommandLine("\\\"");
496   ASSERT_EQ(1ul, Empty.size());
497   EXPECT_EQ("", Empty[0]);
498 }
499 
500 TEST(unescapeJsonCommandLine, ParsesSingleQuotedString) {
501   std::vector<std::string> Args = unescapeJsonCommandLine("a'\\\\b \\\"c\\\"'");
502   ASSERT_EQ(1ul, Args.size());
503   EXPECT_EQ("a\\b \"c\"", Args[0]);
504 }
505 
506 TEST(FixedCompilationDatabase, ReturnsFixedCommandLine) {
507   FixedCompilationDatabase Database(".", /*CommandLine*/ {"one", "two"});
508   StringRef FileName("source");
509   std::vector<CompileCommand> Result =
510     Database.getCompileCommands(FileName);
511   ASSERT_EQ(1ul, Result.size());
512   EXPECT_EQ(".", Result[0].Directory);
513   EXPECT_EQ(FileName, Result[0].Filename);
514   EXPECT_THAT(Result[0].CommandLine,
515               ElementsAre(EndsWith("clang-tool"), "one", "two", "source"));
516 }
517 
518 TEST(FixedCompilationDatabase, GetAllFiles) {
519   std::vector<std::string> CommandLine;
520   CommandLine.push_back("one");
521   CommandLine.push_back("two");
522   FixedCompilationDatabase Database(".", CommandLine);
523 
524   EXPECT_EQ(0ul, Database.getAllFiles().size());
525 }
526 
527 TEST(FixedCompilationDatabase, GetAllCompileCommands) {
528   std::vector<std::string> CommandLine;
529   CommandLine.push_back("one");
530   CommandLine.push_back("two");
531   FixedCompilationDatabase Database(".", CommandLine);
532 
533   EXPECT_EQ(0ul, Database.getAllCompileCommands().size());
534 }
535 
536 TEST(ParseFixedCompilationDatabase, ReturnsNullOnEmptyArgumentList) {
537   int Argc = 0;
538   std::string ErrorMsg;
539   std::unique_ptr<FixedCompilationDatabase> Database =
540       FixedCompilationDatabase::loadFromCommandLine(Argc, nullptr, ErrorMsg);
541   EXPECT_FALSE(Database);
542   EXPECT_TRUE(ErrorMsg.empty());
543   EXPECT_EQ(0, Argc);
544 }
545 
546 TEST(ParseFixedCompilationDatabase, ReturnsNullWithoutDoubleDash) {
547   int Argc = 2;
548   const char *Argv[] = { "1", "2" };
549   std::string ErrorMsg;
550   std::unique_ptr<FixedCompilationDatabase> Database(
551       FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg));
552   EXPECT_FALSE(Database);
553   EXPECT_TRUE(ErrorMsg.empty());
554   EXPECT_EQ(2, Argc);
555 }
556 
557 TEST(ParseFixedCompilationDatabase, ReturnsArgumentsAfterDoubleDash) {
558   int Argc = 5;
559   const char *Argv[] = {
560     "1", "2", "--\0no-constant-folding", "-DDEF3", "-DDEF4"
561   };
562   std::string ErrorMsg;
563   std::unique_ptr<FixedCompilationDatabase> Database(
564       FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg));
565   ASSERT_TRUE((bool)Database);
566   ASSERT_TRUE(ErrorMsg.empty());
567   std::vector<CompileCommand> Result =
568     Database->getCompileCommands("source");
569   ASSERT_EQ(1ul, Result.size());
570   ASSERT_EQ(".", Result[0].Directory);
571   ASSERT_THAT(Result[0].CommandLine, ElementsAre(EndsWith("clang-tool"),
572                                                  "-DDEF3", "-DDEF4", "source"));
573   EXPECT_EQ(2, Argc);
574 }
575 
576 TEST(ParseFixedCompilationDatabase, ReturnsEmptyCommandLine) {
577   int Argc = 3;
578   const char *Argv[] = { "1", "2", "--\0no-constant-folding" };
579   std::string ErrorMsg;
580   std::unique_ptr<FixedCompilationDatabase> Database =
581       FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg);
582   ASSERT_TRUE((bool)Database);
583   ASSERT_TRUE(ErrorMsg.empty());
584   std::vector<CompileCommand> Result =
585     Database->getCompileCommands("source");
586   ASSERT_EQ(1ul, Result.size());
587   ASSERT_EQ(".", Result[0].Directory);
588   ASSERT_THAT(Result[0].CommandLine,
589               ElementsAre(EndsWith("clang-tool"), "source"));
590   EXPECT_EQ(2, Argc);
591 }
592 
593 TEST(ParseFixedCompilationDatabase, HandlesPositionalArgs) {
594   const char *Argv[] = {"1", "2", "--", "-c", "somefile.cpp", "-DDEF3"};
595   int Argc = sizeof(Argv) / sizeof(char*);
596   std::string ErrorMsg;
597   std::unique_ptr<FixedCompilationDatabase> Database =
598       FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg);
599   ASSERT_TRUE((bool)Database);
600   ASSERT_TRUE(ErrorMsg.empty());
601   std::vector<CompileCommand> Result =
602     Database->getCompileCommands("source");
603   ASSERT_EQ(1ul, Result.size());
604   ASSERT_EQ(".", Result[0].Directory);
605   ASSERT_THAT(Result[0].CommandLine,
606               ElementsAre(EndsWith("clang-tool"), "-c", "-DDEF3", "source"));
607   EXPECT_EQ(2, Argc);
608 }
609 
610 TEST(ParseFixedCompilationDatabase, HandlesPositionalArgsSyntaxOnly) {
611   // Adjust the given command line arguments to ensure that any positional
612   // arguments in them are stripped.
613   const char *Argv[] = {"--", "somefile.cpp", "-fsyntax-only", "-DDEF3"};
614   int Argc = llvm::array_lengthof(Argv);
615   std::string ErrorMessage;
616   std::unique_ptr<CompilationDatabase> Database =
617       FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMessage);
618   ASSERT_TRUE((bool)Database);
619   ASSERT_TRUE(ErrorMessage.empty());
620   std::vector<CompileCommand> Result = Database->getCompileCommands("source");
621   ASSERT_EQ(1ul, Result.size());
622   ASSERT_EQ(".", Result[0].Directory);
623   ASSERT_THAT(
624       Result[0].CommandLine,
625       ElementsAre(EndsWith("clang-tool"), "-fsyntax-only", "-DDEF3", "source"));
626 }
627 
628 TEST(ParseFixedCompilationDatabase, HandlesArgv0) {
629   const char *Argv[] = {"1", "2", "--", "mytool", "somefile.cpp"};
630   int Argc = sizeof(Argv) / sizeof(char*);
631   std::string ErrorMsg;
632   std::unique_ptr<FixedCompilationDatabase> Database =
633       FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg);
634   ASSERT_TRUE((bool)Database);
635   ASSERT_TRUE(ErrorMsg.empty());
636   std::vector<CompileCommand> Result =
637     Database->getCompileCommands("source");
638   ASSERT_EQ(1ul, Result.size());
639   ASSERT_EQ(".", Result[0].Directory);
640   std::vector<std::string> Expected;
641   ASSERT_THAT(Result[0].CommandLine,
642               ElementsAre(EndsWith("clang-tool"), "source"));
643   EXPECT_EQ(2, Argc);
644 }
645 
646 struct MemCDB : public CompilationDatabase {
647   using EntryMap = llvm::StringMap<SmallVector<CompileCommand, 1>>;
648   EntryMap Entries;
649   MemCDB(const EntryMap &E) : Entries(E) {}
650 
651   std::vector<CompileCommand> getCompileCommands(StringRef F) const override {
652     auto Ret = Entries.lookup(F);
653     return {Ret.begin(), Ret.end()};
654   }
655 
656   std::vector<std::string> getAllFiles() const override {
657     std::vector<std::string> Result;
658     for (const auto &Entry : Entries)
659       Result.push_back(Entry.first());
660     return Result;
661   }
662 };
663 
664 class MemDBTest : public ::testing::Test {
665 protected:
666   // Adds an entry to the underlying compilation database.
667   // A flag is injected: -D <File>, so the command used can be identified.
668   void add(StringRef File, StringRef Clang, StringRef Flags) {
669     SmallVector<StringRef, 8> Argv = {Clang, File, "-D", File};
670     llvm::SplitString(Flags, Argv);
671 
672     SmallString<32> Dir;
673     llvm::sys::path::system_temp_directory(false, Dir);
674 
675     Entries[path(File)].push_back(
676         {Dir, path(File), {Argv.begin(), Argv.end()}, "foo.o"});
677   }
678   void add(StringRef File, StringRef Flags = "") { add(File, "clang", Flags); }
679 
680   // Turn a unix path fragment (foo/bar.h) into a native path (C:\tmp\foo\bar.h)
681   std::string path(llvm::SmallString<32> File) {
682     llvm::SmallString<32> Dir;
683     llvm::sys::path::system_temp_directory(false, Dir);
684     llvm::sys::path::native(File);
685     llvm::SmallString<64> Result;
686     llvm::sys::path::append(Result, Dir, File);
687     return Result.str();
688   }
689 
690   MemCDB::EntryMap Entries;
691 };
692 
693 class InterpolateTest : public MemDBTest {
694 protected:
695   // Look up the command from a relative path, and return it in string form.
696   // The input file is not included in the returned command.
697   std::string getCommand(llvm::StringRef F) {
698     auto Results =
699         inferMissingCompileCommands(std::make_unique<MemCDB>(Entries))
700             ->getCompileCommands(path(F));
701     if (Results.empty())
702       return "none";
703     // drop the input file argument, so tests don't have to deal with path().
704     EXPECT_EQ(Results[0].CommandLine.back(), path(F))
705         << "Last arg should be the file";
706     Results[0].CommandLine.pop_back();
707     return llvm::join(Results[0].CommandLine, " ");
708   }
709 
710   // Parse the file whose command was used out of the Heuristic string.
711   std::string getProxy(llvm::StringRef F) {
712     auto Results =
713         inferMissingCompileCommands(std::make_unique<MemCDB>(Entries))
714             ->getCompileCommands(path(F));
715     if (Results.empty())
716       return "none";
717     StringRef Proxy = Results.front().Heuristic;
718     if (!Proxy.consume_front("inferred from "))
719       return "";
720     // We have a proxy file, convert back to a unix relative path.
721     // This is a bit messy, but we do need to test these strings somehow...
722     llvm::SmallString<32> TempDir;
723     llvm::sys::path::system_temp_directory(false, TempDir);
724     Proxy.consume_front(TempDir);
725     Proxy.consume_front(llvm::sys::path::get_separator());
726     llvm::SmallString<32> Result = Proxy;
727     llvm::sys::path::native(Result, llvm::sys::path::Style::posix);
728     return Result.str();
729   }
730 };
731 
732 TEST_F(InterpolateTest, Nearby) {
733   add("dir/foo.cpp");
734   add("dir/bar.cpp");
735   add("an/other/foo.cpp");
736 
737   // great: dir and name both match (prefix or full, case insensitive)
738   EXPECT_EQ(getProxy("dir/f.cpp"), "dir/foo.cpp");
739   EXPECT_EQ(getProxy("dir/FOO.cpp"), "dir/foo.cpp");
740   // no name match. prefer matching dir, break ties by alpha
741   EXPECT_EQ(getProxy("dir/a.cpp"), "dir/bar.cpp");
742   // an exact name match beats one segment of directory match
743   EXPECT_EQ(getProxy("some/other/bar.h"), "dir/bar.cpp");
744   // two segments of directory match beat a prefix name match
745   EXPECT_EQ(getProxy("an/other/b.cpp"), "an/other/foo.cpp");
746   // if nothing matches at all, we still get the closest alpha match
747   EXPECT_EQ(getProxy("below/some/obscure/path.cpp"), "an/other/foo.cpp");
748 }
749 
750 TEST_F(InterpolateTest, Language) {
751   add("dir/foo.cpp", "-std=c++17");
752   add("dir/bar.c", "");
753   add("dir/baz.cee", "-x c");
754 
755   // .h is ambiguous, so we add explicit language flags
756   EXPECT_EQ(getCommand("foo.h"),
757             "clang -D dir/foo.cpp -x c++-header -std=c++17");
758   // Same thing if we have no extension. (again, we treat as header).
759   EXPECT_EQ(getCommand("foo"), "clang -D dir/foo.cpp -x c++-header -std=c++17");
760   // and invalid extensions.
761   EXPECT_EQ(getCommand("foo.cce"),
762             "clang -D dir/foo.cpp -x c++-header -std=c++17");
763   // and don't add -x if the inferred language is correct.
764   EXPECT_EQ(getCommand("foo.hpp"), "clang -D dir/foo.cpp -std=c++17");
765   // respect -x if it's already there.
766   EXPECT_EQ(getCommand("baz.h"), "clang -D dir/baz.cee -x c-header");
767   // prefer a worse match with the right extension.
768   EXPECT_EQ(getCommand("foo.c"), "clang -D dir/bar.c");
769   Entries.erase(path(StringRef("dir/bar.c")));
770   // Now we transfer across languages, so drop -std too.
771   EXPECT_EQ(getCommand("foo.c"), "clang -D dir/foo.cpp");
772 }
773 
774 TEST_F(InterpolateTest, Strip) {
775   add("dir/foo.cpp", "-o foo.o -Wall");
776   // the -o option and the input file are removed, but -Wall is preserved.
777   EXPECT_EQ(getCommand("dir/bar.cpp"), "clang -D dir/foo.cpp -Wall");
778 }
779 
780 TEST_F(InterpolateTest, Case) {
781   add("FOO/BAR/BAZ/SHOUT.cc");
782   add("foo/bar/baz/quiet.cc");
783   // Case mismatches are completely ignored, so we choose the name match.
784   EXPECT_EQ(getProxy("foo/bar/baz/shout.C"), "FOO/BAR/BAZ/SHOUT.cc");
785 }
786 
787 TEST_F(InterpolateTest, Aliasing) {
788   add("foo.cpp", "-faligned-new");
789 
790   // The interpolated command should keep the given flag as written, even though
791   // the flag is internally represented as an alias.
792   EXPECT_EQ(getCommand("foo.hpp"), "clang -D foo.cpp -faligned-new");
793 }
794 
795 TEST_F(InterpolateTest, ClangCL) {
796   add("foo.cpp", "clang-cl", "/W4");
797 
798   // Language flags should be added with CL syntax.
799   EXPECT_EQ(getCommand("foo.h"), "clang-cl -D foo.cpp /W4 /TP");
800 }
801 
802 TEST_F(InterpolateTest, DriverModes) {
803   add("foo.cpp", "clang-cl", "--driver-mode=gcc");
804   add("bar.cpp", "clang", "--driver-mode=cl");
805 
806   // --driver-mode overrides should be respected.
807   EXPECT_EQ(getCommand("foo.h"), "clang-cl -D foo.cpp --driver-mode=gcc -x c++-header");
808   EXPECT_EQ(getCommand("bar.h"), "clang -D bar.cpp --driver-mode=cl /TP");
809 }
810 
811 TEST(CompileCommandTest, EqualityOperator) {
812   CompileCommand CCRef("/foo/bar", "hello.c", {"a", "b"}, "hello.o");
813   CompileCommand CCTest = CCRef;
814 
815   EXPECT_TRUE(CCRef == CCTest);
816   EXPECT_FALSE(CCRef != CCTest);
817 
818   CCTest = CCRef;
819   CCTest.Directory = "/foo/baz";
820   EXPECT_FALSE(CCRef == CCTest);
821   EXPECT_TRUE(CCRef != CCTest);
822 
823   CCTest = CCRef;
824   CCTest.Filename = "bonjour.c";
825   EXPECT_FALSE(CCRef == CCTest);
826   EXPECT_TRUE(CCRef != CCTest);
827 
828   CCTest = CCRef;
829   CCTest.CommandLine.push_back("c");
830   EXPECT_FALSE(CCRef == CCTest);
831   EXPECT_TRUE(CCRef != CCTest);
832 
833   CCTest = CCRef;
834   CCTest.Output = "bonjour.o";
835   EXPECT_FALSE(CCRef == CCTest);
836   EXPECT_TRUE(CCRef != CCTest);
837 }
838 
839 class TargetAndModeTest : public MemDBTest {
840 public:
841   TargetAndModeTest() { llvm::InitializeAllTargetInfos(); }
842 
843 protected:
844   // Look up the command from a relative path, and return it in string form.
845   std::string getCommand(llvm::StringRef F) {
846     auto Results = inferTargetAndDriverMode(std::make_unique<MemCDB>(Entries))
847                        ->getCompileCommands(path(F));
848     if (Results.empty())
849       return "none";
850     return llvm::join(Results[0].CommandLine, " ");
851   }
852 };
853 
854 TEST_F(TargetAndModeTest, TargetAndMode) {
855   add("foo.cpp", "clang-cl", "");
856   add("bar.cpp", "clang++", "");
857 
858   EXPECT_EQ(getCommand("foo.cpp"),
859             "clang-cl --driver-mode=cl foo.cpp -D foo.cpp");
860   EXPECT_EQ(getCommand("bar.cpp"),
861             "clang++ --driver-mode=g++ bar.cpp -D bar.cpp");
862 }
863 
864 } // end namespace tooling
865 } // end namespace clang
866