1 //===- unittest/Tooling/ToolingTest.cpp - Tooling unit tests --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/AST/ASTConsumer.h"
11 #include "clang/AST/DeclCXX.h"
12 #include "clang/AST/DeclGroup.h"
13 #include "clang/Frontend/ASTUnit.h"
14 #include "clang/Frontend/CompilerInstance.h"
15 #include "clang/Frontend/FrontendAction.h"
16 #include "clang/Frontend/FrontendActions.h"
17 #include "clang/Tooling/CompilationDatabase.h"
18 #include "clang/Tooling/Tooling.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/TargetRegistry.h"
22 #include "llvm/Support/TargetSelect.h"
23 #include "gtest/gtest.h"
24 #include <algorithm>
25 #include <string>
26 
27 namespace clang {
28 namespace tooling {
29 
30 namespace {
31 /// Takes an ast consumer and returns it from CreateASTConsumer. This only
32 /// works with single translation unit compilations.
33 class TestAction : public clang::ASTFrontendAction {
34 public:
35   /// Takes ownership of TestConsumer.
36   explicit TestAction(std::unique_ptr<clang::ASTConsumer> TestConsumer)
37       : TestConsumer(std::move(TestConsumer)) {}
38 
39 protected:
40   std::unique_ptr<clang::ASTConsumer>
41   CreateASTConsumer(clang::CompilerInstance &compiler,
42                     StringRef dummy) override {
43     /// TestConsumer will be deleted by the framework calling us.
44     return std::move(TestConsumer);
45   }
46 
47 private:
48   std::unique_ptr<clang::ASTConsumer> TestConsumer;
49 };
50 
51 class FindTopLevelDeclConsumer : public clang::ASTConsumer {
52  public:
53   explicit FindTopLevelDeclConsumer(bool *FoundTopLevelDecl)
54       : FoundTopLevelDecl(FoundTopLevelDecl) {}
55   bool HandleTopLevelDecl(clang::DeclGroupRef DeclGroup) override {
56     *FoundTopLevelDecl = true;
57     return true;
58   }
59  private:
60   bool * const FoundTopLevelDecl;
61 };
62 } // end namespace
63 
64 TEST(runToolOnCode, FindsNoTopLevelDeclOnEmptyCode) {
65   bool FoundTopLevelDecl = false;
66   EXPECT_TRUE(
67       runToolOnCode(new TestAction(llvm::make_unique<FindTopLevelDeclConsumer>(
68                         &FoundTopLevelDecl)),
69                     ""));
70   EXPECT_FALSE(FoundTopLevelDecl);
71 }
72 
73 namespace {
74 class FindClassDeclXConsumer : public clang::ASTConsumer {
75  public:
76   FindClassDeclXConsumer(bool *FoundClassDeclX)
77       : FoundClassDeclX(FoundClassDeclX) {}
78   bool HandleTopLevelDecl(clang::DeclGroupRef GroupRef) override {
79     if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(
80             *GroupRef.begin())) {
81       if (Record->getName() == "X") {
82         *FoundClassDeclX = true;
83       }
84     }
85     return true;
86   }
87  private:
88   bool *FoundClassDeclX;
89 };
90 bool FindClassDeclX(ASTUnit *AST) {
91   for (std::vector<Decl *>::iterator i = AST->top_level_begin(),
92                                      e = AST->top_level_end();
93        i != e; ++i) {
94     if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(*i)) {
95       if (Record->getName() == "X") {
96         return true;
97       }
98     }
99   }
100   return false;
101 }
102 } // end namespace
103 
104 TEST(runToolOnCode, FindsClassDecl) {
105   bool FoundClassDeclX = false;
106   EXPECT_TRUE(
107       runToolOnCode(new TestAction(llvm::make_unique<FindClassDeclXConsumer>(
108                         &FoundClassDeclX)),
109                     "class X;"));
110   EXPECT_TRUE(FoundClassDeclX);
111 
112   FoundClassDeclX = false;
113   EXPECT_TRUE(
114       runToolOnCode(new TestAction(llvm::make_unique<FindClassDeclXConsumer>(
115                         &FoundClassDeclX)),
116                     "class Y;"));
117   EXPECT_FALSE(FoundClassDeclX);
118 }
119 
120 TEST(buildASTFromCode, FindsClassDecl) {
121   std::unique_ptr<ASTUnit> AST = buildASTFromCode("class X;");
122   ASSERT_TRUE(AST.get());
123   EXPECT_TRUE(FindClassDeclX(AST.get()));
124 
125   AST = buildASTFromCode("class Y;");
126   ASSERT_TRUE(AST.get());
127   EXPECT_FALSE(FindClassDeclX(AST.get()));
128 }
129 
130 TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) {
131   std::unique_ptr<FrontendActionFactory> Factory(
132       newFrontendActionFactory<SyntaxOnlyAction>());
133   std::unique_ptr<FrontendAction> Action(Factory->create());
134   EXPECT_TRUE(Action.get() != nullptr);
135 }
136 
137 struct IndependentFrontendActionCreator {
138   std::unique_ptr<ASTConsumer> newASTConsumer() {
139     return llvm::make_unique<FindTopLevelDeclConsumer>(nullptr);
140   }
141 };
142 
143 TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) {
144   IndependentFrontendActionCreator Creator;
145   std::unique_ptr<FrontendActionFactory> Factory(
146       newFrontendActionFactory(&Creator));
147   std::unique_ptr<FrontendAction> Action(Factory->create());
148   EXPECT_TRUE(Action.get() != nullptr);
149 }
150 
151 TEST(ToolInvocation, TestMapVirtualFile) {
152   llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
153       new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
154   llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
155       new llvm::vfs::InMemoryFileSystem);
156   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
157   llvm::IntrusiveRefCntPtr<FileManager> Files(
158       new FileManager(FileSystemOptions(), OverlayFileSystem));
159   std::vector<std::string> Args;
160   Args.push_back("tool-executable");
161   Args.push_back("-Idef");
162   Args.push_back("-fsyntax-only");
163   Args.push_back("test.cpp");
164   clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction,
165                                             Files.get());
166   InMemoryFileSystem->addFile(
167       "test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("#include <abc>\n"));
168   InMemoryFileSystem->addFile("def/abc", 0,
169                               llvm::MemoryBuffer::getMemBuffer("\n"));
170   EXPECT_TRUE(Invocation.run());
171 }
172 
173 TEST(ToolInvocation, TestVirtualModulesCompilation) {
174   // FIXME: Currently, this only tests that we don't exit with an error if a
175   // mapped module.map is found on the include path. In the future, expand this
176   // test to run a full modules enabled compilation, so we make sure we can
177   // rerun modules compilations with a virtual file system.
178   llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
179       new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
180   llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
181       new llvm::vfs::InMemoryFileSystem);
182   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
183   llvm::IntrusiveRefCntPtr<FileManager> Files(
184       new FileManager(FileSystemOptions(), OverlayFileSystem));
185   std::vector<std::string> Args;
186   Args.push_back("tool-executable");
187   Args.push_back("-Idef");
188   Args.push_back("-fsyntax-only");
189   Args.push_back("test.cpp");
190   clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction,
191                                             Files.get());
192   InMemoryFileSystem->addFile(
193       "test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("#include <abc>\n"));
194   InMemoryFileSystem->addFile("def/abc", 0,
195                               llvm::MemoryBuffer::getMemBuffer("\n"));
196   // Add a module.map file in the include directory of our header, so we trigger
197   // the module.map header search logic.
198   InMemoryFileSystem->addFile("def/module.map", 0,
199                               llvm::MemoryBuffer::getMemBuffer("\n"));
200   EXPECT_TRUE(Invocation.run());
201 }
202 
203 struct VerifyEndCallback : public SourceFileCallbacks {
204   VerifyEndCallback() : BeginCalled(0), EndCalled(0), Matched(false) {}
205   bool handleBeginSource(CompilerInstance &CI) override {
206     ++BeginCalled;
207     return true;
208   }
209   void handleEndSource() override { ++EndCalled; }
210   std::unique_ptr<ASTConsumer> newASTConsumer() {
211     return llvm::make_unique<FindTopLevelDeclConsumer>(&Matched);
212   }
213   unsigned BeginCalled;
214   unsigned EndCalled;
215   bool Matched;
216 };
217 
218 #if !defined(_WIN32)
219 TEST(newFrontendActionFactory, InjectsSourceFileCallbacks) {
220   VerifyEndCallback EndCallback;
221 
222   FixedCompilationDatabase Compilations("/", std::vector<std::string>());
223   std::vector<std::string> Sources;
224   Sources.push_back("/a.cc");
225   Sources.push_back("/b.cc");
226   ClangTool Tool(Compilations, Sources);
227 
228   Tool.mapVirtualFile("/a.cc", "void a() {}");
229   Tool.mapVirtualFile("/b.cc", "void b() {}");
230 
231   std::unique_ptr<FrontendActionFactory> Action(
232       newFrontendActionFactory(&EndCallback, &EndCallback));
233   Tool.run(Action.get());
234 
235   EXPECT_TRUE(EndCallback.Matched);
236   EXPECT_EQ(2u, EndCallback.BeginCalled);
237   EXPECT_EQ(2u, EndCallback.EndCalled);
238 }
239 #endif
240 
241 struct SkipBodyConsumer : public clang::ASTConsumer {
242   /// Skip the 'skipMe' function.
243   bool shouldSkipFunctionBody(Decl *D) override {
244     NamedDecl *F = dyn_cast<NamedDecl>(D);
245     return F && F->getNameAsString() == "skipMe";
246   }
247 };
248 
249 struct SkipBodyAction : public clang::ASTFrontendAction {
250   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
251                                                  StringRef) override {
252     Compiler.getFrontendOpts().SkipFunctionBodies = true;
253     return llvm::make_unique<SkipBodyConsumer>();
254   }
255 };
256 
257 TEST(runToolOnCode, TestSkipFunctionBody) {
258   std::vector<std::string> Args = {"-std=c++11"};
259   std::vector<std::string> Args2 = {"-fno-delayed-template-parsing"};
260 
261   EXPECT_TRUE(runToolOnCode(new SkipBodyAction,
262                             "int skipMe() { an_error_here }"));
263   EXPECT_FALSE(runToolOnCode(new SkipBodyAction,
264                              "int skipMeNot() { an_error_here }"));
265 
266   // Test constructors with initializers
267   EXPECT_TRUE(runToolOnCodeWithArgs(
268       new SkipBodyAction,
269       "struct skipMe { skipMe() : an_error() { more error } };", Args));
270   EXPECT_TRUE(runToolOnCodeWithArgs(
271       new SkipBodyAction, "struct skipMe { skipMe(); };"
272                           "skipMe::skipMe() : an_error([](){;}) { more error }",
273       Args));
274   EXPECT_TRUE(runToolOnCodeWithArgs(
275       new SkipBodyAction, "struct skipMe { skipMe(); };"
276                           "skipMe::skipMe() : an_error{[](){;}} { more error }",
277       Args));
278   EXPECT_TRUE(runToolOnCodeWithArgs(
279       new SkipBodyAction,
280       "struct skipMe { skipMe(); };"
281       "skipMe::skipMe() : a<b<c>(e)>>(), f{}, g() { error }",
282       Args));
283   EXPECT_TRUE(runToolOnCodeWithArgs(
284       new SkipBodyAction, "struct skipMe { skipMe() : bases()... { error } };",
285       Args));
286 
287   EXPECT_FALSE(runToolOnCodeWithArgs(
288       new SkipBodyAction, "struct skipMeNot { skipMeNot() : an_error() { } };",
289       Args));
290   EXPECT_FALSE(runToolOnCodeWithArgs(new SkipBodyAction,
291                                      "struct skipMeNot { skipMeNot(); };"
292                                      "skipMeNot::skipMeNot() : an_error() { }",
293                                      Args));
294 
295   // Try/catch
296   EXPECT_TRUE(runToolOnCode(
297       new SkipBodyAction,
298       "void skipMe() try { an_error() } catch(error) { error };"));
299   EXPECT_TRUE(runToolOnCode(
300       new SkipBodyAction,
301       "struct S { void skipMe() try { an_error() } catch(error) { error } };"));
302   EXPECT_TRUE(
303       runToolOnCode(new SkipBodyAction,
304                     "void skipMe() try { an_error() } catch(error) { error; }"
305                     "catch(error) { error } catch (error) { }"));
306   EXPECT_FALSE(runToolOnCode(
307       new SkipBodyAction,
308       "void skipMe() try something;")); // don't crash while parsing
309 
310   // Template
311   EXPECT_TRUE(runToolOnCode(
312       new SkipBodyAction, "template<typename T> int skipMe() { an_error_here }"
313                           "int x = skipMe<int>();"));
314   EXPECT_FALSE(runToolOnCodeWithArgs(
315       new SkipBodyAction,
316       "template<typename T> int skipMeNot() { an_error_here }", Args2));
317 }
318 
319 TEST(runToolOnCodeWithArgs, TestNoDepFile) {
320   llvm::SmallString<32> DepFilePath;
321   ASSERT_FALSE(llvm::sys::fs::getPotentiallyUniqueTempFileName("depfile", "d",
322                                                                DepFilePath));
323   std::vector<std::string> Args;
324   Args.push_back("-MMD");
325   Args.push_back("-MT");
326   Args.push_back(DepFilePath.str());
327   Args.push_back("-MF");
328   Args.push_back(DepFilePath.str());
329   EXPECT_TRUE(runToolOnCodeWithArgs(new SkipBodyAction, "", Args));
330   EXPECT_FALSE(llvm::sys::fs::exists(DepFilePath.str()));
331   EXPECT_FALSE(llvm::sys::fs::remove(DepFilePath.str()));
332 }
333 
334 struct CheckColoredDiagnosticsAction : public clang::ASTFrontendAction {
335   CheckColoredDiagnosticsAction(bool ShouldShowColor)
336       : ShouldShowColor(ShouldShowColor) {}
337   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
338                                                  StringRef) override {
339     if (Compiler.getDiagnosticOpts().ShowColors != ShouldShowColor)
340       Compiler.getDiagnostics().Report(
341           Compiler.getDiagnostics().getCustomDiagID(
342               DiagnosticsEngine::Fatal,
343               "getDiagnosticOpts().ShowColors != ShouldShowColor"));
344     return llvm::make_unique<ASTConsumer>();
345   }
346 
347 private:
348   bool ShouldShowColor = true;
349 };
350 
351 TEST(runToolOnCodeWithArgs, DiagnosticsColor) {
352 
353   EXPECT_TRUE(runToolOnCodeWithArgs(new CheckColoredDiagnosticsAction(true), "",
354                                     {"-fcolor-diagnostics"}));
355   EXPECT_TRUE(runToolOnCodeWithArgs(new CheckColoredDiagnosticsAction(false),
356                                     "", {"-fno-color-diagnostics"}));
357   EXPECT_TRUE(
358       runToolOnCodeWithArgs(new CheckColoredDiagnosticsAction(true), "",
359                             {"-fno-color-diagnostics", "-fcolor-diagnostics"}));
360   EXPECT_TRUE(
361       runToolOnCodeWithArgs(new CheckColoredDiagnosticsAction(false), "",
362                             {"-fcolor-diagnostics", "-fno-color-diagnostics"}));
363   EXPECT_TRUE(runToolOnCodeWithArgs(
364       new CheckColoredDiagnosticsAction(true), "",
365       {"-fno-color-diagnostics", "-fdiagnostics-color=always"}));
366 
367   // Check that this test would fail if ShowColors is not what it should.
368   EXPECT_FALSE(runToolOnCodeWithArgs(new CheckColoredDiagnosticsAction(false),
369                                      "", {"-fcolor-diagnostics"}));
370 }
371 
372 TEST(ClangToolTest, ArgumentAdjusters) {
373   FixedCompilationDatabase Compilations("/", std::vector<std::string>());
374 
375   ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
376   Tool.mapVirtualFile("/a.cc", "void a() {}");
377 
378   std::unique_ptr<FrontendActionFactory> Action(
379       newFrontendActionFactory<SyntaxOnlyAction>());
380 
381   bool Found = false;
382   bool Ran = false;
383   ArgumentsAdjuster CheckSyntaxOnlyAdjuster =
384       [&Found, &Ran](const CommandLineArguments &Args, StringRef /*unused*/) {
385     Ran = true;
386     if (std::find(Args.begin(), Args.end(), "-fsyntax-only") != Args.end())
387       Found = true;
388     return Args;
389   };
390   Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
391   Tool.run(Action.get());
392   EXPECT_TRUE(Ran);
393   EXPECT_TRUE(Found);
394 
395   Ran = Found = false;
396   Tool.clearArgumentsAdjusters();
397   Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
398   Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
399   Tool.run(Action.get());
400   EXPECT_TRUE(Ran);
401   EXPECT_FALSE(Found);
402 }
403 
404 TEST(ClangToolTest, BaseVirtualFileSystemUsage) {
405   FixedCompilationDatabase Compilations("/", std::vector<std::string>());
406   llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
407       new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
408   llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
409       new llvm::vfs::InMemoryFileSystem);
410   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
411 
412   InMemoryFileSystem->addFile(
413       "a.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int main() {}"));
414 
415   ClangTool Tool(Compilations, std::vector<std::string>(1, "a.cpp"),
416                  std::make_shared<PCHContainerOperations>(), OverlayFileSystem);
417   std::unique_ptr<FrontendActionFactory> Action(
418       newFrontendActionFactory<SyntaxOnlyAction>());
419   EXPECT_EQ(0, Tool.run(Action.get()));
420 }
421 
422 // Check getClangStripDependencyFileAdjuster doesn't strip args after -MD/-MMD.
423 TEST(ClangToolTest, StripDependencyFileAdjuster) {
424   FixedCompilationDatabase Compilations("/", {"-MD", "-c", "-MMD", "-w"});
425 
426   ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
427   Tool.mapVirtualFile("/a.cc", "void a() {}");
428 
429   std::unique_ptr<FrontendActionFactory> Action(
430       newFrontendActionFactory<SyntaxOnlyAction>());
431 
432   CommandLineArguments FinalArgs;
433   ArgumentsAdjuster CheckFlagsAdjuster =
434     [&FinalArgs](const CommandLineArguments &Args, StringRef /*unused*/) {
435       FinalArgs = Args;
436       return Args;
437     };
438   Tool.clearArgumentsAdjusters();
439   Tool.appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
440   Tool.appendArgumentsAdjuster(CheckFlagsAdjuster);
441   Tool.run(Action.get());
442 
443   auto HasFlag = [&FinalArgs](const std::string &Flag) {
444     return std::find(FinalArgs.begin(), FinalArgs.end(), Flag) !=
445            FinalArgs.end();
446   };
447   EXPECT_FALSE(HasFlag("-MD"));
448   EXPECT_FALSE(HasFlag("-MMD"));
449   EXPECT_TRUE(HasFlag("-c"));
450   EXPECT_TRUE(HasFlag("-w"));
451 }
452 
453 namespace {
454 /// Find a target name such that looking for it in TargetRegistry by that name
455 /// returns the same target. We expect that there is at least one target
456 /// configured with this property.
457 std::string getAnyTarget() {
458   llvm::InitializeAllTargets();
459   for (const auto &Target : llvm::TargetRegistry::targets()) {
460     std::string Error;
461     StringRef TargetName(Target.getName());
462     if (TargetName == "x86-64")
463       TargetName = "x86_64";
464     if (llvm::TargetRegistry::lookupTarget(TargetName, Error) == &Target) {
465       return TargetName;
466     }
467   }
468   return "";
469 }
470 }
471 
472 TEST(addTargetAndModeForProgramName, AddsTargetAndMode) {
473   std::string Target = getAnyTarget();
474   ASSERT_FALSE(Target.empty());
475 
476   std::vector<std::string> Args = {"clang", "-foo"};
477   addTargetAndModeForProgramName(Args, "");
478   EXPECT_EQ((std::vector<std::string>{"clang", "-foo"}), Args);
479   addTargetAndModeForProgramName(Args, Target + "-g++");
480   EXPECT_EQ((std::vector<std::string>{"clang", "-target", Target,
481                                       "--driver-mode=g++", "-foo"}),
482             Args);
483 }
484 
485 TEST(addTargetAndModeForProgramName, PathIgnored) {
486   std::string Target = getAnyTarget();
487   ASSERT_FALSE(Target.empty());
488 
489   SmallString<32> ToolPath;
490   llvm::sys::path::append(ToolPath, "foo", "bar", Target + "-g++");
491 
492   std::vector<std::string> Args = {"clang", "-foo"};
493   addTargetAndModeForProgramName(Args, ToolPath);
494   EXPECT_EQ((std::vector<std::string>{"clang", "-target", Target,
495                                       "--driver-mode=g++", "-foo"}),
496             Args);
497 }
498 
499 TEST(addTargetAndModeForProgramName, IgnoresExistingTarget) {
500   std::string Target = getAnyTarget();
501   ASSERT_FALSE(Target.empty());
502 
503   std::vector<std::string> Args = {"clang", "-foo", "-target", "something"};
504   addTargetAndModeForProgramName(Args, Target + "-g++");
505   EXPECT_EQ((std::vector<std::string>{"clang", "--driver-mode=g++", "-foo",
506                                       "-target", "something"}),
507             Args);
508 
509   std::vector<std::string> ArgsAlt = {"clang", "-foo", "-target=something"};
510   addTargetAndModeForProgramName(ArgsAlt, Target + "-g++");
511   EXPECT_EQ((std::vector<std::string>{"clang", "--driver-mode=g++", "-foo",
512                                       "-target=something"}),
513             ArgsAlt);
514 }
515 
516 TEST(addTargetAndModeForProgramName, IgnoresExistingMode) {
517   std::string Target = getAnyTarget();
518   ASSERT_FALSE(Target.empty());
519 
520   std::vector<std::string> Args = {"clang", "-foo", "--driver-mode=abc"};
521   addTargetAndModeForProgramName(Args, Target + "-g++");
522   EXPECT_EQ((std::vector<std::string>{"clang", "-target", Target, "-foo",
523                                       "--driver-mode=abc"}),
524             Args);
525 
526   std::vector<std::string> ArgsAlt = {"clang", "-foo", "--driver-mode", "abc"};
527   addTargetAndModeForProgramName(ArgsAlt, Target + "-g++");
528   EXPECT_EQ((std::vector<std::string>{"clang", "-target", Target, "-foo",
529                                       "--driver-mode", "abc"}),
530             ArgsAlt);
531 }
532 
533 #ifndef _WIN32
534 TEST(ClangToolTest, BuildASTs) {
535   FixedCompilationDatabase Compilations("/", std::vector<std::string>());
536 
537   std::vector<std::string> Sources;
538   Sources.push_back("/a.cc");
539   Sources.push_back("/b.cc");
540   ClangTool Tool(Compilations, Sources);
541 
542   Tool.mapVirtualFile("/a.cc", "void a() {}");
543   Tool.mapVirtualFile("/b.cc", "void b() {}");
544 
545   std::vector<std::unique_ptr<ASTUnit>> ASTs;
546   EXPECT_EQ(0, Tool.buildASTs(ASTs));
547   EXPECT_EQ(2u, ASTs.size());
548 }
549 
550 struct TestDiagnosticConsumer : public DiagnosticConsumer {
551   TestDiagnosticConsumer() : NumDiagnosticsSeen(0) {}
552   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
553                         const Diagnostic &Info) override {
554     ++NumDiagnosticsSeen;
555   }
556   unsigned NumDiagnosticsSeen;
557 };
558 
559 TEST(ClangToolTest, InjectDiagnosticConsumer) {
560   FixedCompilationDatabase Compilations("/", std::vector<std::string>());
561   ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
562   Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
563   TestDiagnosticConsumer Consumer;
564   Tool.setDiagnosticConsumer(&Consumer);
565   std::unique_ptr<FrontendActionFactory> Action(
566       newFrontendActionFactory<SyntaxOnlyAction>());
567   Tool.run(Action.get());
568   EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
569 }
570 
571 TEST(ClangToolTest, InjectDiagnosticConsumerInBuildASTs) {
572   FixedCompilationDatabase Compilations("/", std::vector<std::string>());
573   ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
574   Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
575   TestDiagnosticConsumer Consumer;
576   Tool.setDiagnosticConsumer(&Consumer);
577   std::vector<std::unique_ptr<ASTUnit>> ASTs;
578   Tool.buildASTs(ASTs);
579   EXPECT_EQ(1u, ASTs.size());
580   EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
581 }
582 #endif
583 
584 TEST(runToolOnCode, TestResetDiagnostics) {
585   // This is a tool that resets the diagnostic during the compilation.
586   struct ResetDiagnosticAction : public clang::ASTFrontendAction {
587     std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
588                                                    StringRef) override {
589       struct Consumer : public clang::ASTConsumer {
590         bool HandleTopLevelDecl(clang::DeclGroupRef D) override {
591           auto &Diags = (*D.begin())->getASTContext().getDiagnostics();
592           // Ignore any error
593           Diags.Reset();
594           // Disable warnings because computing the CFG might crash.
595           Diags.setIgnoreAllWarnings(true);
596           return true;
597         }
598       };
599       return llvm::make_unique<Consumer>();
600     }
601   };
602 
603   // Should not crash
604   EXPECT_FALSE(
605       runToolOnCode(new ResetDiagnosticAction,
606                     "struct Foo { Foo(int); ~Foo(); struct Fwd _fwd; };"
607                     "void func() { long x; Foo f(x); }"));
608 }
609 
610 } // end namespace tooling
611 } // end namespace clang
612