xref: /llvm-project/clang/unittests/Tooling/CompilationDatabaseTest.cpp (revision 9c0391b36a76f8e3949588de3f44b7314c2318bf)
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   std::vector<std::pair<std::string, std::string>> Cases = {
375       {"distcc gcc foo.c", "gcc foo.c"},
376       {"gomacc clang++ foo.c", "clang++ foo.c"},
377       {"ccache gcc foo.c", "gcc foo.c"},
378       {"ccache.exe gcc foo.c", "gcc foo.c"},
379       {"ccache g++.exe foo.c", "g++.exe foo.c"},
380       {"ccache distcc gcc foo.c", "gcc foo.c"},
381 
382       {"distcc foo.c", "distcc foo.c"},
383       {"distcc -I/foo/bar foo.c", "distcc -I/foo/bar foo.c"},
384   };
385   std::string ErrorMessage;
386 
387   for (const auto &Case : Cases) {
388     std::string DB = R"([{"directory":".", "file":"/foo.c", "command":")" +
389                      Case.first + "\"}]";
390     CompileCommand FoundCommand =
391         findCompileArgsInJsonDatabase("/foo.c", DB, ErrorMessage);
392     EXPECT_EQ(Case.second, llvm::join(FoundCommand.CommandLine, " "))
393         << Case.first;
394   }
395 }
396 
397 static std::vector<std::string> unescapeJsonCommandLine(StringRef Command) {
398   std::string JsonDatabase =
399     ("[{\"directory\":\"//net/root\", \"file\":\"test\", \"command\": \"" +
400      Command + "\"}]").str();
401   std::string ErrorMessage;
402   CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
403     "//net/root/test", JsonDatabase, ErrorMessage);
404   EXPECT_TRUE(ErrorMessage.empty()) << ErrorMessage;
405   return FoundCommand.CommandLine;
406 }
407 
408 TEST(unescapeJsonCommandLine, ReturnsEmptyArrayOnEmptyString) {
409   std::vector<std::string> Result = unescapeJsonCommandLine("");
410   EXPECT_TRUE(Result.empty());
411 }
412 
413 TEST(unescapeJsonCommandLine, SplitsOnSpaces) {
414   std::vector<std::string> Result = unescapeJsonCommandLine("a b c");
415   ASSERT_EQ(3ul, Result.size());
416   EXPECT_EQ("a", Result[0]);
417   EXPECT_EQ("b", Result[1]);
418   EXPECT_EQ("c", Result[2]);
419 }
420 
421 TEST(unescapeJsonCommandLine, MungesMultipleSpaces) {
422   std::vector<std::string> Result = unescapeJsonCommandLine("   a   b   ");
423   ASSERT_EQ(2ul, Result.size());
424   EXPECT_EQ("a", Result[0]);
425   EXPECT_EQ("b", Result[1]);
426 }
427 
428 TEST(unescapeJsonCommandLine, UnescapesBackslashCharacters) {
429   std::vector<std::string> Backslash = unescapeJsonCommandLine("a\\\\\\\\");
430   ASSERT_EQ(1ul, Backslash.size());
431   EXPECT_EQ("a\\", Backslash[0]);
432   std::vector<std::string> Quote = unescapeJsonCommandLine("a\\\\\\\"");
433   ASSERT_EQ(1ul, Quote.size());
434   EXPECT_EQ("a\"", Quote[0]);
435 }
436 
437 TEST(unescapeJsonCommandLine, DoesNotMungeSpacesBetweenQuotes) {
438   std::vector<std::string> Result = unescapeJsonCommandLine("\\\"  a  b  \\\"");
439   ASSERT_EQ(1ul, Result.size());
440   EXPECT_EQ("  a  b  ", Result[0]);
441 }
442 
443 TEST(unescapeJsonCommandLine, AllowsMultipleQuotedArguments) {
444   std::vector<std::string> Result = unescapeJsonCommandLine(
445       "  \\\" a \\\"  \\\" b \\\"  ");
446   ASSERT_EQ(2ul, Result.size());
447   EXPECT_EQ(" a ", Result[0]);
448   EXPECT_EQ(" b ", Result[1]);
449 }
450 
451 TEST(unescapeJsonCommandLine, AllowsEmptyArgumentsInQuotes) {
452   std::vector<std::string> Result = unescapeJsonCommandLine(
453       "\\\"\\\"\\\"\\\"");
454   ASSERT_EQ(1ul, Result.size());
455   EXPECT_TRUE(Result[0].empty()) << Result[0];
456 }
457 
458 TEST(unescapeJsonCommandLine, ParsesEscapedQuotesInQuotedStrings) {
459   std::vector<std::string> Result = unescapeJsonCommandLine(
460       "\\\"\\\\\\\"\\\"");
461   ASSERT_EQ(1ul, Result.size());
462   EXPECT_EQ("\"", Result[0]);
463 }
464 
465 TEST(unescapeJsonCommandLine, ParsesMultipleArgumentsWithEscapedCharacters) {
466   std::vector<std::string> Result = unescapeJsonCommandLine(
467       "  \\\\\\\"  \\\"a \\\\\\\" b \\\"     \\\"and\\\\\\\\c\\\"   \\\\\\\"");
468   ASSERT_EQ(4ul, Result.size());
469   EXPECT_EQ("\"", Result[0]);
470   EXPECT_EQ("a \" b ", Result[1]);
471   EXPECT_EQ("and\\c", Result[2]);
472   EXPECT_EQ("\"", Result[3]);
473 }
474 
475 TEST(unescapeJsonCommandLine, ParsesStringsWithoutSpacesIntoSingleArgument) {
476   std::vector<std::string> QuotedNoSpaces = unescapeJsonCommandLine(
477       "\\\"a\\\"\\\"b\\\"");
478   ASSERT_EQ(1ul, QuotedNoSpaces.size());
479   EXPECT_EQ("ab", QuotedNoSpaces[0]);
480 
481   std::vector<std::string> MixedNoSpaces = unescapeJsonCommandLine(
482       "\\\"a\\\"bcd\\\"ef\\\"\\\"\\\"\\\"g\\\"");
483   ASSERT_EQ(1ul, MixedNoSpaces.size());
484   EXPECT_EQ("abcdefg", MixedNoSpaces[0]);
485 }
486 
487 TEST(unescapeJsonCommandLine, ParsesQuotedStringWithoutClosingQuote) {
488   std::vector<std::string> Unclosed = unescapeJsonCommandLine("\\\"abc");
489   ASSERT_EQ(1ul, Unclosed.size());
490   EXPECT_EQ("abc", Unclosed[0]);
491 
492   std::vector<std::string> Empty = unescapeJsonCommandLine("\\\"");
493   ASSERT_EQ(1ul, Empty.size());
494   EXPECT_EQ("", Empty[0]);
495 }
496 
497 TEST(unescapeJsonCommandLine, ParsesSingleQuotedString) {
498   std::vector<std::string> Args = unescapeJsonCommandLine("a'\\\\b \\\"c\\\"'");
499   ASSERT_EQ(1ul, Args.size());
500   EXPECT_EQ("a\\b \"c\"", Args[0]);
501 }
502 
503 TEST(FixedCompilationDatabase, ReturnsFixedCommandLine) {
504   FixedCompilationDatabase Database(".", /*CommandLine*/ {"one", "two"});
505   StringRef FileName("source");
506   std::vector<CompileCommand> Result =
507     Database.getCompileCommands(FileName);
508   ASSERT_EQ(1ul, Result.size());
509   EXPECT_EQ(".", Result[0].Directory);
510   EXPECT_EQ(FileName, Result[0].Filename);
511   EXPECT_THAT(Result[0].CommandLine,
512               ElementsAre(EndsWith("clang-tool"), "one", "two", "source"));
513 }
514 
515 TEST(FixedCompilationDatabase, GetAllFiles) {
516   std::vector<std::string> CommandLine;
517   CommandLine.push_back("one");
518   CommandLine.push_back("two");
519   FixedCompilationDatabase Database(".", CommandLine);
520 
521   EXPECT_EQ(0ul, Database.getAllFiles().size());
522 }
523 
524 TEST(FixedCompilationDatabase, GetAllCompileCommands) {
525   std::vector<std::string> CommandLine;
526   CommandLine.push_back("one");
527   CommandLine.push_back("two");
528   FixedCompilationDatabase Database(".", CommandLine);
529 
530   EXPECT_EQ(0ul, Database.getAllCompileCommands().size());
531 }
532 
533 TEST(ParseFixedCompilationDatabase, ReturnsNullOnEmptyArgumentList) {
534   int Argc = 0;
535   std::string ErrorMsg;
536   std::unique_ptr<FixedCompilationDatabase> Database =
537       FixedCompilationDatabase::loadFromCommandLine(Argc, nullptr, ErrorMsg);
538   EXPECT_FALSE(Database);
539   EXPECT_TRUE(ErrorMsg.empty());
540   EXPECT_EQ(0, Argc);
541 }
542 
543 TEST(ParseFixedCompilationDatabase, ReturnsNullWithoutDoubleDash) {
544   int Argc = 2;
545   const char *Argv[] = { "1", "2" };
546   std::string ErrorMsg;
547   std::unique_ptr<FixedCompilationDatabase> Database(
548       FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg));
549   EXPECT_FALSE(Database);
550   EXPECT_TRUE(ErrorMsg.empty());
551   EXPECT_EQ(2, Argc);
552 }
553 
554 TEST(ParseFixedCompilationDatabase, ReturnsArgumentsAfterDoubleDash) {
555   int Argc = 5;
556   const char *Argv[] = {
557     "1", "2", "--\0no-constant-folding", "-DDEF3", "-DDEF4"
558   };
559   std::string ErrorMsg;
560   std::unique_ptr<FixedCompilationDatabase> Database(
561       FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg));
562   ASSERT_TRUE((bool)Database);
563   ASSERT_TRUE(ErrorMsg.empty());
564   std::vector<CompileCommand> Result =
565     Database->getCompileCommands("source");
566   ASSERT_EQ(1ul, Result.size());
567   ASSERT_EQ(".", Result[0].Directory);
568   ASSERT_THAT(Result[0].CommandLine, ElementsAre(EndsWith("clang-tool"),
569                                                  "-DDEF3", "-DDEF4", "source"));
570   EXPECT_EQ(2, Argc);
571 }
572 
573 TEST(ParseFixedCompilationDatabase, ReturnsEmptyCommandLine) {
574   int Argc = 3;
575   const char *Argv[] = { "1", "2", "--\0no-constant-folding" };
576   std::string ErrorMsg;
577   std::unique_ptr<FixedCompilationDatabase> Database =
578       FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg);
579   ASSERT_TRUE((bool)Database);
580   ASSERT_TRUE(ErrorMsg.empty());
581   std::vector<CompileCommand> Result =
582     Database->getCompileCommands("source");
583   ASSERT_EQ(1ul, Result.size());
584   ASSERT_EQ(".", Result[0].Directory);
585   ASSERT_THAT(Result[0].CommandLine,
586               ElementsAre(EndsWith("clang-tool"), "source"));
587   EXPECT_EQ(2, Argc);
588 }
589 
590 TEST(ParseFixedCompilationDatabase, HandlesPositionalArgs) {
591   const char *Argv[] = {"1", "2", "--", "-c", "somefile.cpp", "-DDEF3"};
592   int Argc = sizeof(Argv) / sizeof(char*);
593   std::string ErrorMsg;
594   std::unique_ptr<FixedCompilationDatabase> Database =
595       FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg);
596   ASSERT_TRUE((bool)Database);
597   ASSERT_TRUE(ErrorMsg.empty());
598   std::vector<CompileCommand> Result =
599     Database->getCompileCommands("source");
600   ASSERT_EQ(1ul, Result.size());
601   ASSERT_EQ(".", Result[0].Directory);
602   ASSERT_THAT(Result[0].CommandLine,
603               ElementsAre(EndsWith("clang-tool"), "-c", "-DDEF3", "source"));
604   EXPECT_EQ(2, Argc);
605 }
606 
607 TEST(ParseFixedCompilationDatabase, HandlesPositionalArgsSyntaxOnly) {
608   // Adjust the given command line arguments to ensure that any positional
609   // arguments in them are stripped.
610   const char *Argv[] = {"--", "somefile.cpp", "-fsyntax-only", "-DDEF3"};
611   int Argc = llvm::array_lengthof(Argv);
612   std::string ErrorMessage;
613   std::unique_ptr<CompilationDatabase> Database =
614       FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMessage);
615   ASSERT_TRUE((bool)Database);
616   ASSERT_TRUE(ErrorMessage.empty());
617   std::vector<CompileCommand> Result = Database->getCompileCommands("source");
618   ASSERT_EQ(1ul, Result.size());
619   ASSERT_EQ(".", Result[0].Directory);
620   ASSERT_THAT(
621       Result[0].CommandLine,
622       ElementsAre(EndsWith("clang-tool"), "-fsyntax-only", "-DDEF3", "source"));
623 }
624 
625 TEST(ParseFixedCompilationDatabase, HandlesArgv0) {
626   const char *Argv[] = {"1", "2", "--", "mytool", "somefile.cpp"};
627   int Argc = sizeof(Argv) / sizeof(char*);
628   std::string ErrorMsg;
629   std::unique_ptr<FixedCompilationDatabase> Database =
630       FixedCompilationDatabase::loadFromCommandLine(Argc, Argv, ErrorMsg);
631   ASSERT_TRUE((bool)Database);
632   ASSERT_TRUE(ErrorMsg.empty());
633   std::vector<CompileCommand> Result =
634     Database->getCompileCommands("source");
635   ASSERT_EQ(1ul, Result.size());
636   ASSERT_EQ(".", Result[0].Directory);
637   std::vector<std::string> Expected;
638   ASSERT_THAT(Result[0].CommandLine,
639               ElementsAre(EndsWith("clang-tool"), "source"));
640   EXPECT_EQ(2, Argc);
641 }
642 
643 struct MemCDB : public CompilationDatabase {
644   using EntryMap = llvm::StringMap<SmallVector<CompileCommand, 1>>;
645   EntryMap Entries;
646   MemCDB(const EntryMap &E) : Entries(E) {}
647 
648   std::vector<CompileCommand> getCompileCommands(StringRef F) const override {
649     auto Ret = Entries.lookup(F);
650     return {Ret.begin(), Ret.end()};
651   }
652 
653   std::vector<std::string> getAllFiles() const override {
654     std::vector<std::string> Result;
655     for (const auto &Entry : Entries)
656       Result.push_back(Entry.first());
657     return Result;
658   }
659 };
660 
661 class MemDBTest : public ::testing::Test {
662 protected:
663   // Adds an entry to the underlying compilation database.
664   // A flag is injected: -D <File>, so the command used can be identified.
665   void add(StringRef File, StringRef Clang, StringRef Flags) {
666     SmallVector<StringRef, 8> Argv = {Clang, File, "-D", File};
667     llvm::SplitString(Flags, Argv);
668 
669     SmallString<32> Dir;
670     llvm::sys::path::system_temp_directory(false, Dir);
671 
672     Entries[path(File)].push_back(
673         {Dir, path(File), {Argv.begin(), Argv.end()}, "foo.o"});
674   }
675   void add(StringRef File, StringRef Flags = "") { add(File, "clang", Flags); }
676 
677   // Turn a unix path fragment (foo/bar.h) into a native path (C:\tmp\foo\bar.h)
678   std::string path(llvm::SmallString<32> File) {
679     llvm::SmallString<32> Dir;
680     llvm::sys::path::system_temp_directory(false, Dir);
681     llvm::sys::path::native(File);
682     llvm::SmallString<64> Result;
683     llvm::sys::path::append(Result, Dir, File);
684     return Result.str();
685   }
686 
687   MemCDB::EntryMap Entries;
688 };
689 
690 class InterpolateTest : public MemDBTest {
691 protected:
692   // Look up the command from a relative path, and return it in string form.
693   // The input file is not included in the returned command.
694   std::string getCommand(llvm::StringRef F) {
695     auto Results =
696         inferMissingCompileCommands(llvm::make_unique<MemCDB>(Entries))
697             ->getCompileCommands(path(F));
698     if (Results.empty())
699       return "none";
700     // drop the input file argument, so tests don't have to deal with path().
701     EXPECT_EQ(Results[0].CommandLine.back(), path(F))
702         << "Last arg should be the file";
703     Results[0].CommandLine.pop_back();
704     return llvm::join(Results[0].CommandLine, " ");
705   }
706 
707   // Parse the file whose command was used out of the Heuristic string.
708   std::string getProxy(llvm::StringRef F) {
709     auto Results =
710         inferMissingCompileCommands(llvm::make_unique<MemCDB>(Entries))
711             ->getCompileCommands(path(F));
712     if (Results.empty())
713       return "none";
714     StringRef Proxy = Results.front().Heuristic;
715     if (!Proxy.consume_front("inferred from "))
716       return "";
717     // We have a proxy file, convert back to a unix relative path.
718     // This is a bit messy, but we do need to test these strings somehow...
719     llvm::SmallString<32> TempDir;
720     llvm::sys::path::system_temp_directory(false, TempDir);
721     Proxy.consume_front(TempDir);
722     Proxy.consume_front(llvm::sys::path::get_separator());
723     llvm::SmallString<32> Result = Proxy;
724     llvm::sys::path::native(Result, llvm::sys::path::Style::posix);
725     return Result.str();
726   }
727 };
728 
729 TEST_F(InterpolateTest, Nearby) {
730   add("dir/foo.cpp");
731   add("dir/bar.cpp");
732   add("an/other/foo.cpp");
733 
734   // great: dir and name both match (prefix or full, case insensitive)
735   EXPECT_EQ(getProxy("dir/f.cpp"), "dir/foo.cpp");
736   EXPECT_EQ(getProxy("dir/FOO.cpp"), "dir/foo.cpp");
737   // no name match. prefer matching dir, break ties by alpha
738   EXPECT_EQ(getProxy("dir/a.cpp"), "dir/bar.cpp");
739   // an exact name match beats one segment of directory match
740   EXPECT_EQ(getProxy("some/other/bar.h"), "dir/bar.cpp");
741   // two segments of directory match beat a prefix name match
742   EXPECT_EQ(getProxy("an/other/b.cpp"), "an/other/foo.cpp");
743   // if nothing matches at all, we still get the closest alpha match
744   EXPECT_EQ(getProxy("below/some/obscure/path.cpp"), "an/other/foo.cpp");
745 }
746 
747 TEST_F(InterpolateTest, Language) {
748   add("dir/foo.cpp", "-std=c++17");
749   add("dir/bar.c", "");
750   add("dir/baz.cee", "-x c");
751 
752   // .h is ambiguous, so we add explicit language flags
753   EXPECT_EQ(getCommand("foo.h"),
754             "clang -D dir/foo.cpp -x c++-header -std=c++17");
755   // Same thing if we have no extension. (again, we treat as header).
756   EXPECT_EQ(getCommand("foo"), "clang -D dir/foo.cpp -x c++-header -std=c++17");
757   // and invalid extensions.
758   EXPECT_EQ(getCommand("foo.cce"),
759             "clang -D dir/foo.cpp -x c++-header -std=c++17");
760   // and don't add -x if the inferred language is correct.
761   EXPECT_EQ(getCommand("foo.hpp"), "clang -D dir/foo.cpp -std=c++17");
762   // respect -x if it's already there.
763   EXPECT_EQ(getCommand("baz.h"), "clang -D dir/baz.cee -x c-header");
764   // prefer a worse match with the right extension.
765   EXPECT_EQ(getCommand("foo.c"), "clang -D dir/bar.c");
766   Entries.erase(path(StringRef("dir/bar.c")));
767   // Now we transfer across languages, so drop -std too.
768   EXPECT_EQ(getCommand("foo.c"), "clang -D dir/foo.cpp");
769 }
770 
771 TEST_F(InterpolateTest, Strip) {
772   add("dir/foo.cpp", "-o foo.o -Wall");
773   // the -o option and the input file are removed, but -Wall is preserved.
774   EXPECT_EQ(getCommand("dir/bar.cpp"), "clang -D dir/foo.cpp -Wall");
775 }
776 
777 TEST_F(InterpolateTest, Case) {
778   add("FOO/BAR/BAZ/SHOUT.cc");
779   add("foo/bar/baz/quiet.cc");
780   // Case mismatches are completely ignored, so we choose the name match.
781   EXPECT_EQ(getProxy("foo/bar/baz/shout.C"), "FOO/BAR/BAZ/SHOUT.cc");
782 }
783 
784 TEST_F(InterpolateTest, Aliasing) {
785   add("foo.cpp", "-faligned-new");
786 
787   // The interpolated command should keep the given flag as written, even though
788   // the flag is internally represented as an alias.
789   EXPECT_EQ(getCommand("foo.hpp"), "clang -D foo.cpp -faligned-new");
790 }
791 
792 TEST_F(InterpolateTest, ClangCL) {
793   add("foo.cpp", "clang-cl", "/W4");
794 
795   // Language flags should be added with CL syntax.
796   EXPECT_EQ(getCommand("foo.h"), "clang-cl -D foo.cpp /W4 /TP");
797 }
798 
799 TEST_F(InterpolateTest, DriverModes) {
800   add("foo.cpp", "clang-cl", "--driver-mode=gcc");
801   add("bar.cpp", "clang", "--driver-mode=cl");
802 
803   // --driver-mode overrides should be respected.
804   EXPECT_EQ(getCommand("foo.h"), "clang-cl -D foo.cpp --driver-mode=gcc -x c++-header");
805   EXPECT_EQ(getCommand("bar.h"), "clang -D bar.cpp --driver-mode=cl /TP");
806 }
807 
808 TEST(CompileCommandTest, EqualityOperator) {
809   CompileCommand CCRef("/foo/bar", "hello.c", {"a", "b"}, "hello.o");
810   CompileCommand CCTest = CCRef;
811 
812   EXPECT_TRUE(CCRef == CCTest);
813   EXPECT_FALSE(CCRef != CCTest);
814 
815   CCTest = CCRef;
816   CCTest.Directory = "/foo/baz";
817   EXPECT_FALSE(CCRef == CCTest);
818   EXPECT_TRUE(CCRef != CCTest);
819 
820   CCTest = CCRef;
821   CCTest.Filename = "bonjour.c";
822   EXPECT_FALSE(CCRef == CCTest);
823   EXPECT_TRUE(CCRef != CCTest);
824 
825   CCTest = CCRef;
826   CCTest.CommandLine.push_back("c");
827   EXPECT_FALSE(CCRef == CCTest);
828   EXPECT_TRUE(CCRef != CCTest);
829 
830   CCTest = CCRef;
831   CCTest.Output = "bonjour.o";
832   EXPECT_FALSE(CCRef == CCTest);
833   EXPECT_TRUE(CCRef != CCTest);
834 }
835 
836 class TargetAndModeTest : public MemDBTest {
837 public:
838   TargetAndModeTest() { llvm::InitializeAllTargetInfos(); }
839 
840 protected:
841   // Look up the command from a relative path, and return it in string form.
842   std::string getCommand(llvm::StringRef F) {
843     auto Results = inferTargetAndDriverMode(llvm::make_unique<MemCDB>(Entries))
844                        ->getCompileCommands(path(F));
845     if (Results.empty())
846       return "none";
847     return llvm::join(Results[0].CommandLine, " ");
848   }
849 };
850 
851 TEST_F(TargetAndModeTest, TargetAndMode) {
852   add("foo.cpp", "clang-cl", "");
853   add("bar.cpp", "clang++", "");
854 
855   EXPECT_EQ(getCommand("foo.cpp"),
856             "clang-cl --driver-mode=cl foo.cpp -D foo.cpp");
857   EXPECT_EQ(getCommand("bar.cpp"),
858             "clang++ --driver-mode=g++ bar.cpp -D bar.cpp");
859 }
860 
861 } // end namespace tooling
862 } // end namespace clang
863