Debian Codegraph @

clang/unittests/Tooling/ToolingTest.cpp

raw
1 //===- unittest/Tooling/ToolingTest.cpp - Tooling unit tests --------------===//
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/Tooling/Tooling.h"
10 #include "clang/AST/ASTConsumer.h"
11 #include "clang/AST/DeclCXX.h"
12 #include "clang/AST/DeclGroup.h"
13 #include "clang/Driver/Compilation.h"
14 #include "clang/Driver/Driver.h"
15 #include "clang/Frontend/ASTUnit.h"
16 #include "clang/Frontend/CompilerInstance.h"
17 #include "clang/Frontend/FrontendAction.h"
18 #include "clang/Frontend/FrontendActions.h"
19 #include "clang/Frontend/TextDiagnosticBuffer.h"
20 #include "clang/Testing/CommandLineArgs.h"
21 #include "clang/Tooling/ArgumentsAdjusters.h"
22 #include "clang/Tooling/CompilationDatabase.h"
23 #include "clang/Tooling/JSONCompilationDatabase.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Support/JSON.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/TargetSelect.h"
29 #include "llvm/TargetParser/Host.h"
30 #include "gtest/gtest.h"
31 #include <algorithm>
32 #include <string>
33 #include <vector>
34
35 namespace clang {
36 namespace tooling {
37
38 namespace {
39 /// Takes an ast consumer and returns it from CreateASTConsumer. This only
40 /// works with single translation unit compilations.
41 class TestAction : public clang::ASTFrontendAction {
42 public:
43 /// Takes ownership of TestConsumer.
44 explicit TestAction(std::unique_ptr<clang::ASTConsumer> TestConsumer)
45 : TestConsumer(std::move(TestConsumer)) {}
46
47 protected:
48 std::unique_ptr<clang::ASTConsumer>
49 CreateASTConsumer(clang::CompilerInstance &compiler,
50 StringRef dummy) override {
51 /// TestConsumer will be deleted by the framework calling us.
52 return std::move(TestConsumer);
53 }
54
55 private:
56 std::unique_ptr<clang::ASTConsumer> TestConsumer;
57 };
58
59 class FindTopLevelDeclConsumer : public clang::ASTConsumer {
60 public:
61 explicit FindTopLevelDeclConsumer(bool *FoundTopLevelDecl)
62 : FoundTopLevelDecl(FoundTopLevelDecl) {}
63 bool HandleTopLevelDecl(clang::DeclGroupRef DeclGroup) override {
64 *FoundTopLevelDecl = true;
65 return true;
66 }
67 private:
68 bool * const FoundTopLevelDecl;
69 };
70 } // end namespace
71
72 TEST(runToolOnCode, FindsNoTopLevelDeclOnEmptyCode) {
73 bool FoundTopLevelDecl = false;
74 EXPECT_TRUE(runToolOnCode(
75 std::make_unique<TestAction>(
76 std::make_unique<FindTopLevelDeclConsumer>(&FoundTopLevelDecl)),
77 ""));
78 EXPECT_FALSE(FoundTopLevelDecl);
79 }
80
81 TEST(runToolOnCode, CudaSyntaxOnly) {
82 EXPECT_TRUE(runToolOnCodeWithArgs(
83 std::make_unique<TestAction>(std::make_unique<clang::ASTConsumer>()), "",
84 {"-fsyntax-only", "-x", "cuda", "--offload-arch=sm_70", "-nocudalib",
85 "-nocudainc"}));
86 }
87
88 TEST(runToolOnCode, CudaMultipleArchs) {
89 EXPECT_TRUE(runToolOnCodeWithArgs(
90 std::make_unique<TestAction>(std::make_unique<clang::ASTConsumer>()), "",
91 {"-fsyntax-only", "-x", "cuda", "--offload-arch=sm_70,sm_80",
92 "-nocudalib", "-nocudainc"}));
93 }
94
95 namespace {
96 class FindClassDeclXConsumer : public clang::ASTConsumer {
97 public:
98 FindClassDeclXConsumer(bool *FoundClassDeclX)
99 : FoundClassDeclX(FoundClassDeclX) {}
100 bool HandleTopLevelDecl(clang::DeclGroupRef GroupRef) override {
101 if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(
102 *GroupRef.begin())) {
103 if (Record->getName() == "X") {
104 *FoundClassDeclX = true;
105 }
106 }
107 return true;
108 }
109 private:
110 bool *FoundClassDeclX;
111 };
112 bool FindClassDeclX(ASTUnit *AST) {
113 for (std::vector<Decl *>::iterator i = AST->top_level_begin(),
114 e = AST->top_level_end();
115 i != e; ++i) {
116 if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(*i)) {
117 if (Record->getName() == "X") {
118 return true;
119 }
120 }
121 }
122 return false;
123 }
124
125 struct TestDiagnosticConsumer : public DiagnosticConsumer {
126 TestDiagnosticConsumer() : NumDiagnosticsSeen(0) {}
127 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
128 const Diagnostic &Info) override {
129 ++NumDiagnosticsSeen;
130 }
131 unsigned NumDiagnosticsSeen;
132 };
133 } // end namespace
134
135 TEST(runToolOnCode, FindsClassDecl) {
136 bool FoundClassDeclX = false;
137 EXPECT_TRUE(runToolOnCode(
138 std::make_unique<TestAction>(
139 std::make_unique<FindClassDeclXConsumer>(&FoundClassDeclX)),
140 "class X;"));
141 EXPECT_TRUE(FoundClassDeclX);
142
143 FoundClassDeclX = false;
144 EXPECT_TRUE(runToolOnCode(
145 std::make_unique<TestAction>(
146 std::make_unique<FindClassDeclXConsumer>(&FoundClassDeclX)),
147 "class Y;"));
148 EXPECT_FALSE(FoundClassDeclX);
149 }
150
151 TEST(buildASTFromCode, FindsClassDecl) {
152 std::unique_ptr<ASTUnit> AST = buildASTFromCode("class X;");
153 ASSERT_TRUE(AST.get());
154 EXPECT_TRUE(FindClassDeclX(AST.get()));
155
156 AST = buildASTFromCode("class Y;");
157 ASSERT_TRUE(AST.get());
158 EXPECT_FALSE(FindClassDeclX(AST.get()));
159 }
160
161 TEST(buildASTFromCode, ReportsErrors) {
162 TestDiagnosticConsumer Consumer;
163 std::unique_ptr<ASTUnit> AST = buildASTFromCodeWithArgs(
164 "int x = \"A\";", {}, "input.cc", "clang-tool",
165 std::make_shared<PCHContainerOperations>(),
166 getClangStripDependencyFileAdjuster(), FileContentMappings(), &Consumer);
167 EXPECT_TRUE(AST.get());
168 EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
169 }
170
171 TEST(buildASTFromCode, FileSystem) {
172 auto InMemoryFileSystem =
173 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
174 InMemoryFileSystem->addFile("included_file.h", 0,
175 llvm::MemoryBuffer::getMemBufferCopy("class X;"));
176 std::unique_ptr<ASTUnit> AST = buildASTFromCodeWithArgs(
177 R"(#include "included_file.h")", {}, "input.cc", "clang-tool",
178 std::make_shared<PCHContainerOperations>(),
179 getClangStripDependencyFileAdjuster(), FileContentMappings(), nullptr,
180 InMemoryFileSystem);
181 ASSERT_TRUE(AST.get());
182 EXPECT_TRUE(FindClassDeclX(AST.get()));
183 }
184
185 TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) {
186 std::unique_ptr<FrontendActionFactory> Factory(
187 newFrontendActionFactory<SyntaxOnlyAction>());
188 std::unique_ptr<FrontendAction> Action(Factory->create());
189 EXPECT_TRUE(Action.get() != nullptr);
190 }
191
192 struct IndependentFrontendActionCreator {
193 std::unique_ptr<ASTConsumer> newASTConsumer() {
194 return std::make_unique<FindTopLevelDeclConsumer>(nullptr);
195 }
196 };
197
198 TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) {
199 IndependentFrontendActionCreator Creator;
200 std::unique_ptr<FrontendActionFactory> Factory(
201 newFrontendActionFactory(&Creator));
202 std::unique_ptr<FrontendAction> Action(Factory->create());
203 EXPECT_TRUE(Action.get() != nullptr);
204 }
205
206 TEST(ToolInvocation, TestMapVirtualFile) {
207 auto OverlayFileSystem =
208 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(
209 llvm::vfs::getRealFileSystem());
210 auto InMemoryFileSystem =
211 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
212 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
213 auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
214 OverlayFileSystem);
215 std::vector<std::string> Args;
216 Args.push_back("tool-executable");
217 Args.push_back("-Idef");
218 Args.push_back("-fsyntax-only");
219 Args.push_back("test.cpp");
220 clang::tooling::ToolInvocation Invocation(
221 Args, std::make_unique<SyntaxOnlyAction>(), Files.get());
222 InMemoryFileSystem->addFile(
223 "test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("#include <abc>\n"));
224 InMemoryFileSystem->addFile("def/abc", 0,
225 llvm::MemoryBuffer::getMemBuffer("\n"));
226 EXPECT_TRUE(Invocation.run());
227 }
228
229 TEST(ToolInvocation, TestVirtualModulesCompilation) {
230 // FIXME: Currently, this only tests that we don't exit with an error if a
231 // mapped module.modulemap is found on the include path. In the future, expand
232 // this test to run a full modules enabled compilation, so we make sure we can
233 // rerun modules compilations with a virtual file system.
234 auto OverlayFileSystem =
235 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(
236 llvm::vfs::getRealFileSystem());
237 auto InMemoryFileSystem =
238 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
239 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
240 auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
241 OverlayFileSystem);
242 std::vector<std::string> Args;
243 Args.push_back("tool-executable");
244 Args.push_back("-Idef");
245 Args.push_back("-fsyntax-only");
246 Args.push_back("test.cpp");
247 clang::tooling::ToolInvocation Invocation(
248 Args, std::make_unique<SyntaxOnlyAction>(), Files.get());
249 InMemoryFileSystem->addFile(
250 "test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("#include <abc>\n"));
251 InMemoryFileSystem->addFile("def/abc", 0,
252 llvm::MemoryBuffer::getMemBuffer("\n"));
253 // Add a module.modulemap file in the include directory of our header, so we
254 // trigger the module.modulemap header search logic.
255 InMemoryFileSystem->addFile("def/module.modulemap", 0,
256 llvm::MemoryBuffer::getMemBuffer("\n"));
257 EXPECT_TRUE(Invocation.run());
258 }
259
260 TEST(ToolInvocation, DiagnosticsEngineProperlyInitializedForCC1Construction) {
261 auto OverlayFileSystem =
262 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(
263 llvm::vfs::getRealFileSystem());
264 auto InMemoryFileSystem =
265 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
266 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
267 auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
268 OverlayFileSystem);
269
270 std::vector<std::string> Args;
271 Args.push_back("tool-executable");
272 // Unknown warning option will result in a warning.
273 Args.push_back("-fexpensive-optimizations");
274 // Argument that will suppress the warning above.
275 Args.push_back("-Wno-ignored-optimization-argument");
276 Args.push_back("-E");
277 Args.push_back("test.cpp");
278
279 clang::tooling::ToolInvocation Invocation(
280 Args, std::make_unique<SyntaxOnlyAction>(), Files.get());
281 InMemoryFileSystem->addFile("test.cpp", 0,
282 llvm::MemoryBuffer::getMemBuffer(""));
283 TextDiagnosticBuffer Consumer;
284 Invocation.setDiagnosticConsumer(&Consumer);
285 EXPECT_TRUE(Invocation.run());
286 // Check that the warning was ignored due to the '-Wno-xxx' argument.
287 EXPECT_EQ(std::distance(Consumer.warn_begin(), Consumer.warn_end()), 0u);
288 }
289
290 TEST(ToolInvocation, CustomDiagnosticOptionsOverwriteParsedOnes) {
291 auto OverlayFileSystem =
292 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(
293 llvm::vfs::getRealFileSystem());
294 auto InMemoryFileSystem =
295 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
296 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
297 auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
298 OverlayFileSystem);
299
300 std::vector<std::string> Args;
301 Args.push_back("tool-executable");
302 // Unknown warning option will result in a warning.
303 Args.push_back("-fexpensive-optimizations");
304 // Argument that will suppress the warning above.
305 Args.push_back("-Wno-ignored-optimization-argument");
306 Args.push_back("-E");
307 Args.push_back("test.cpp");
308
309 clang::tooling::ToolInvocation Invocation(
310 Args, std::make_unique<SyntaxOnlyAction>(), Files.get());
311 InMemoryFileSystem->addFile("test.cpp", 0,
312 llvm::MemoryBuffer::getMemBuffer(""));
313 TextDiagnosticBuffer Consumer;
314 Invocation.setDiagnosticConsumer(&Consumer);
315
316 // Inject custom `DiagnosticOptions` for command-line parsing.
317 DiagnosticOptions DiagOpts;
318 Invocation.setDiagnosticOptions(&DiagOpts);
319
320 EXPECT_TRUE(Invocation.run());
321 // Check that the warning was issued during command-line parsing due to the
322 // custom `DiagnosticOptions` without '-Wno-xxx'.
323 EXPECT_EQ(std::distance(Consumer.warn_begin(), Consumer.warn_end()), 1u);
324 }
325
326 struct DiagnosticConsumerExpectingSourceManager : public DiagnosticConsumer {
327 bool SawSourceManager;
328
329 DiagnosticConsumerExpectingSourceManager() : SawSourceManager(false) {}
330
331 void HandleDiagnostic(clang::DiagnosticsEngine::Level,
332 const clang::Diagnostic &info) override {
333 SawSourceManager = info.hasSourceManager();
334 }
335 };
336
337 TEST(ToolInvocation, DiagConsumerExpectingSourceManager) {
338 auto OverlayFileSystem =
339 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(
340 llvm::vfs::getRealFileSystem());
341 auto InMemoryFileSystem =
342 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
343 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
344 auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
345 OverlayFileSystem);
346 std::vector<std::string> Args;
347 Args.push_back("tool-executable");
348 // Note: intentional error; user probably meant -ferror-limit=0.
349 Args.push_back("-ferror-limit=-1");
350 Args.push_back("-fsyntax-only");
351 Args.push_back("test.cpp");
352 clang::tooling::ToolInvocation Invocation(
353 Args, std::make_unique<SyntaxOnlyAction>(), Files.get());
354 InMemoryFileSystem->addFile(
355 "test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int main() {}\n"));
356
357 DiagnosticConsumerExpectingSourceManager Consumer;
358 Invocation.setDiagnosticConsumer(&Consumer);
359
360 EXPECT_TRUE(Invocation.run());
361 EXPECT_TRUE(Consumer.SawSourceManager);
362 }
363
364 TEST(ToolInvocation, CC1Args) {
365 auto OverlayFileSystem =
366 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(
367 llvm::vfs::getRealFileSystem());
368 auto InMemoryFileSystem =
369 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
370 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
371 auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
372 OverlayFileSystem);
373 std::vector<std::string> Args;
374 Args.push_back("tool-executable");
375 Args.push_back("-cc1");
376 Args.push_back("-fsyntax-only");
377 Args.push_back("test.cpp");
378 clang::tooling::ToolInvocation Invocation(
379 Args, std::make_unique<SyntaxOnlyAction>(), Files.get());
380 InMemoryFileSystem->addFile(
381 "test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("void foo(void);\n"));
382 EXPECT_TRUE(Invocation.run());
383 }
384
385 TEST(ToolInvocation, CC1ArgsInvalid) {
386 auto OverlayFileSystem =
387 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(
388 llvm::vfs::getRealFileSystem());
389 auto InMemoryFileSystem =
390 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
391 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
392 auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
393 OverlayFileSystem);
394 std::vector<std::string> Args;
395 Args.push_back("tool-executable");
396 Args.push_back("-cc1");
397 Args.push_back("-invalid-arg");
398 Args.push_back("test.cpp");
399 clang::tooling::ToolInvocation Invocation(
400 Args, std::make_unique<SyntaxOnlyAction>(), Files.get());
401 InMemoryFileSystem->addFile(
402 "test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("void foo(void);\n"));
403 EXPECT_FALSE(Invocation.run());
404 }
405
406 namespace {
407 /// Overlays the real filesystem with the given VFS and returns the result.
408 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem>
409 overlayRealFS(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
410 auto RFS = llvm::vfs::getRealFileSystem();
411 auto OverlayFS = llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(RFS);
412 OverlayFS->pushOverlay(VFS);
413 return OverlayFS;
414 }
415
416 struct CommandLineExtractorTest : public ::testing::Test {
417 llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFS;
418 DiagnosticOptions DiagOpts;
419 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
420 driver::Driver Driver;
421
422 public:
423 CommandLineExtractorTest()
424 : InMemoryFS(llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>()),
425 Diags(CompilerInstance::createDiagnostics(*InMemoryFS, DiagOpts)),
426 Driver("clang", llvm::sys::getDefaultTargetTriple(), *Diags,
427 "clang LLVM compiler", overlayRealFS(InMemoryFS)) {}
428
429 void addFile(StringRef Name, StringRef Content) {
430 InMemoryFS->addFile(Name, 0, llvm::MemoryBuffer::getMemBuffer(Content));
431 }
432
433 const llvm::opt::ArgStringList *
434 extractCC1Arguments(llvm::ArrayRef<const char *> Argv) {
435 const std::unique_ptr<driver::Compilation> Compilation(
436 Driver.BuildCompilation(llvm::ArrayRef(Argv)));
437
438 return getCC1Arguments(Diags.get(), Compilation.get());
439 }
440 };
441 } // namespace
442
443 TEST_F(CommandLineExtractorTest, AcceptOffloading) {
444 addFile("test.c", "int main() {}\n");
445 const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0",
446 "-x", "hip", "test.c",
447 "-nogpulib", "-nogpuinc"};
448 EXPECT_NE(extractCC1Arguments(Args), nullptr);
449 }
450
451 TEST_F(CommandLineExtractorTest, AcceptOffloadingCompile) {
452 addFile("test.c", "int main() {}\n");
453 const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0",
454 "-c", "-x", "hip",
455 "test.c", "-nogpulib", "-nogpuinc"};
456 EXPECT_NE(extractCC1Arguments(Args), nullptr);
457 }
458
459 TEST_F(CommandLineExtractorTest, AcceptOffloadingSyntaxOnly) {
460 addFile("test.c", "int main() {}\n");
461 const char *Args[] = {
462 "clang", "-target", "arm64-apple-macosx11.0.0",
463 "-fsyntax-only", "-x", "hip",
464 "test.c", "-nogpulib", "-nogpuinc"};
465 EXPECT_NE(extractCC1Arguments(Args), nullptr);
466 }
467
468 TEST_F(CommandLineExtractorTest, AcceptExternalAssembler) {
469 addFile("test.c", "int main() {}\n");
470 const char *Args[] = {
471 "clang", "-target", "arm64-apple-macosx11.0.0", "-fno-integrated-as",
472 "-c", "test.c"};
473 EXPECT_NE(extractCC1Arguments(Args), nullptr);
474 }
475
476 TEST_F(CommandLineExtractorTest, AcceptEmbedBitcode) {
477 addFile("test.c", "int main() {}\n");
478 const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0",
479 "-c", "-fembed-bitcode", "test.c"};
480 EXPECT_NE(extractCC1Arguments(Args), nullptr);
481 }
482
483 TEST_F(CommandLineExtractorTest, AcceptSaveTemps) {
484 addFile("test.c", "int main() {}\n");
485 const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0",
486 "-c", "-save-temps", "test.c"};
487 EXPECT_NE(extractCC1Arguments(Args), nullptr);
488 }
489
490 TEST_F(CommandLineExtractorTest, AcceptPreprocessedInputFile) {
491 addFile("test.i", "int main() {}\n");
492 const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0", "-c",
493 "test.i"};
494 EXPECT_NE(extractCC1Arguments(Args), nullptr);
495 }
496
497 TEST_F(CommandLineExtractorTest, RejectMultipleArchitectures) {
498 addFile("test.c", "int main() {}\n");
499 const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0",
500 "-arch", "x86_64", "-arch",
501 "arm64", "-c", "test.c"};
502 EXPECT_EQ(extractCC1Arguments(Args), nullptr);
503 }
504
505 TEST_F(CommandLineExtractorTest, RejectMultipleInputFiles) {
506 addFile("one.c", "void one() {}\n");
507 addFile("two.c", "void two() {}\n");
508 const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0",
509 "-c", "one.c", "two.c"};
510 EXPECT_EQ(extractCC1Arguments(Args), nullptr);
511 }
512
513 struct VerifyEndCallback : public SourceFileCallbacks {
514 VerifyEndCallback() : BeginCalled(0), EndCalled(0), Matched(false) {}
515 bool handleBeginSource(CompilerInstance &CI) override {
516 ++BeginCalled;
517 return true;
518 }
519 void handleEndSource() override { ++EndCalled; }
520 std::unique_ptr<ASTConsumer> newASTConsumer() {
521 return std::make_unique<FindTopLevelDeclConsumer>(&Matched);
522 }
523 unsigned BeginCalled;
524 unsigned EndCalled;
525 bool Matched;
526 };
527
528 #if !defined(_WIN32)
529 TEST(newFrontendActionFactory, InjectsSourceFileCallbacks) {
530 VerifyEndCallback EndCallback;
531
532 FixedCompilationDatabase Compilations("/", std::vector<std::string>());
533 std::vector<std::string> Sources;
534 Sources.push_back("/a.cc");
535 Sources.push_back("/b.cc");
536 ClangTool Tool(Compilations, Sources);
537
538 Tool.mapVirtualFile("/a.cc", "void a() {}");
539 Tool.mapVirtualFile("/b.cc", "void b() {}");
540
541 std::unique_ptr<FrontendActionFactory> Action(
542 newFrontendActionFactory(&EndCallback, &EndCallback));
543 Tool.run(Action.get());
544
545 EXPECT_TRUE(EndCallback.Matched);
546 EXPECT_EQ(2u, EndCallback.BeginCalled);
547 EXPECT_EQ(2u, EndCallback.EndCalled);
548 }
549 #endif
550
551 struct SkipBodyConsumer : public clang::ASTConsumer {
552 /// Skip the 'skipMe' function.
553 bool shouldSkipFunctionBody(Decl *D) override {
554 NamedDecl *F = dyn_cast<NamedDecl>(D);
555 return F && F->getNameAsString() == "skipMe";
556 }
557 };
558
559 struct SkipBodyAction : public clang::ASTFrontendAction {
560 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
561 StringRef) override {
562 Compiler.getFrontendOpts().SkipFunctionBodies = true;
563 return std::make_unique<SkipBodyConsumer>();
564 }
565 };
566
567 TEST(runToolOnCode, TestSkipFunctionBody) {
568 std::vector<std::string> Args = {"-std=c++11"};
569 std::vector<std::string> Args2 = {"-fno-delayed-template-parsing"};
570
571 EXPECT_TRUE(runToolOnCode(std::make_unique<SkipBodyAction>(),
572 "int skipMe() { an_error_here }"));
573 EXPECT_FALSE(runToolOnCode(std::make_unique<SkipBodyAction>(),
574 "int skipMeNot() { an_error_here }"));
575
576 // Test constructors with initializers
577 EXPECT_TRUE(runToolOnCodeWithArgs(
578 std::make_unique<SkipBodyAction>(),
579 "struct skipMe { skipMe() : an_error() { more error } };", Args));
580 EXPECT_TRUE(runToolOnCodeWithArgs(
581 std::make_unique<SkipBodyAction>(), "struct skipMe { skipMe(); };"
582 "skipMe::skipMe() : an_error([](){;}) { more error }",
583 Args));
584 EXPECT_TRUE(runToolOnCodeWithArgs(
585 std::make_unique<SkipBodyAction>(), "struct skipMe { skipMe(); };"
586 "skipMe::skipMe() : an_error{[](){;}} { more error }",
587 Args));
588 EXPECT_TRUE(runToolOnCodeWithArgs(
589 std::make_unique<SkipBodyAction>(),
590 "struct skipMe { skipMe(); };"
591 "skipMe::skipMe() : a<b<c>(e)>>(), f{}, g() { error }",
592 Args));
593 EXPECT_TRUE(runToolOnCodeWithArgs(
594 std::make_unique<SkipBodyAction>(), "struct skipMe { skipMe() : bases()... { error } };",
595 Args));
596
597 EXPECT_FALSE(runToolOnCodeWithArgs(
598 std::make_unique<SkipBodyAction>(), "struct skipMeNot { skipMeNot() : an_error() { } };",
599 Args));
600 EXPECT_FALSE(runToolOnCodeWithArgs(std::make_unique<SkipBodyAction>(),
601 "struct skipMeNot { skipMeNot(); };"
602 "skipMeNot::skipMeNot() : an_error() { }",
603 Args));
604
605 // Try/catch
606 EXPECT_TRUE(runToolOnCode(
607 std::make_unique<SkipBodyAction>(),
608 "void skipMe() try { an_error() } catch(error) { error };"));
609 EXPECT_TRUE(runToolOnCode(
610 std::make_unique<SkipBodyAction>(),
611 "struct S { void skipMe() try { an_error() } catch(error) { error } };"));
612 EXPECT_TRUE(
613 runToolOnCode(std::make_unique<SkipBodyAction>(),
614 "void skipMe() try { an_error() } catch(error) { error; }"
615 "catch(error) { error } catch (error) { }"));
616 EXPECT_FALSE(runToolOnCode(
617 std::make_unique<SkipBodyAction>(),
618 "void skipMe() try something;")); // don't crash while parsing
619
620 // Template
621 EXPECT_TRUE(runToolOnCode(
622 std::make_unique<SkipBodyAction>(), "template<typename T> int skipMe() { an_error_here }"
623 "int x = skipMe<int>();"));
624 EXPECT_FALSE(runToolOnCodeWithArgs(
625 std::make_unique<SkipBodyAction>(),
626 "template<typename T> int skipMeNot() { an_error_here }", Args2));
627
628 EXPECT_TRUE(runToolOnCodeWithArgs(
629 std::make_unique<SkipBodyAction>(),
630 "__inline __attribute__((__gnu_inline__)) void skipMe() {}",
631 {"--cuda-host-only", "-nocudainc", "-xcuda"}));
632 }
633
634 TEST(runToolOnCodeWithArgs, TestNoDepFile) {
635 llvm::SmallString<32> DepFilePath;
636 ASSERT_FALSE(llvm::sys::fs::getPotentiallyUniqueTempFileName("depfile", "d",
637 DepFilePath));
638 std::vector<std::string> Args;
639 Args.push_back("-MMD");
640 Args.push_back("-MT");
641 Args.push_back(std::string(DepFilePath.str()));
642 Args.push_back("-MF");
643 Args.push_back(std::string(DepFilePath.str()));
644 EXPECT_TRUE(runToolOnCodeWithArgs(std::make_unique<SkipBodyAction>(), "", Args));
645 EXPECT_FALSE(llvm::sys::fs::exists(DepFilePath.str()));
646 EXPECT_FALSE(llvm::sys::fs::remove(DepFilePath.str()));
647 }
648
649 struct CheckColoredDiagnosticsAction : public clang::ASTFrontendAction {
650 CheckColoredDiagnosticsAction(bool ShouldShowColor)
651 : ShouldShowColor(ShouldShowColor) {}
652 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
653 StringRef) override {
654 if (Compiler.getDiagnosticOpts().ShowColors != ShouldShowColor)
655 Compiler.getDiagnostics().Report(
656 Compiler.getDiagnostics().getCustomDiagID(
657 DiagnosticsEngine::Fatal,
658 "getDiagnosticOpts().ShowColors != ShouldShowColor"));
659 return std::make_unique<ASTConsumer>();
660 }
661
662 private:
663 bool ShouldShowColor = true;
664 };
665
666 TEST(runToolOnCodeWithArgs, DiagnosticsColor) {
667 EXPECT_TRUE(runToolOnCodeWithArgs(
668 std::make_unique<CheckColoredDiagnosticsAction>(true), "",
669 {"-fcolor-diagnostics"}));
670 EXPECT_TRUE(runToolOnCodeWithArgs(
671 std::make_unique<CheckColoredDiagnosticsAction>(false), "",
672 {"-fno-color-diagnostics"}));
673 EXPECT_TRUE(runToolOnCodeWithArgs(
674 std::make_unique<CheckColoredDiagnosticsAction>(true), "",
675 {"-fno-color-diagnostics", "-fcolor-diagnostics"}));
676 EXPECT_TRUE(runToolOnCodeWithArgs(
677 std::make_unique<CheckColoredDiagnosticsAction>(false), "",
678 {"-fcolor-diagnostics", "-fno-color-diagnostics"}));
679 EXPECT_TRUE(runToolOnCodeWithArgs(
680 std::make_unique<CheckColoredDiagnosticsAction>(true), "",
681 {"-fno-color-diagnostics", "-fdiagnostics-color=always"}));
682
683 // Check that this test would fail if ShowColors is not what it should.
684 EXPECT_FALSE(runToolOnCodeWithArgs(
685 std::make_unique<CheckColoredDiagnosticsAction>(false), "",
686 {"-fcolor-diagnostics"}));
687 }
688
689 TEST(ClangToolTest, ArgumentAdjusters) {
690 FixedCompilationDatabase Compilations("/", std::vector<std::string>());
691
692 ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
693 Tool.mapVirtualFile("/a.cc", "void a() {}");
694
695 std::unique_ptr<FrontendActionFactory> Action(
696 newFrontendActionFactory<SyntaxOnlyAction>());
697
698 bool Found = false;
699 bool Ran = false;
700 ArgumentsAdjuster CheckSyntaxOnlyAdjuster =
701 [&Found, &Ran](const CommandLineArguments &Args, StringRef /*unused*/) {
702 Ran = true;
703 if (llvm::is_contained(Args, "-fsyntax-only"))
704 Found = true;
705 return Args;
706 };
707 Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
708 Tool.run(Action.get());
709 EXPECT_TRUE(Ran);
710 EXPECT_TRUE(Found);
711
712 Ran = Found = false;
713 Tool.clearArgumentsAdjusters();
714 Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
715 Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
716 Tool.run(Action.get());
717 EXPECT_TRUE(Ran);
718 EXPECT_FALSE(Found);
719 }
720
721 TEST(ClangToolTest, NoDoubleSyntaxOnly) {
722 FixedCompilationDatabase Compilations("/", {"-fsyntax-only"});
723
724 ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
725 Tool.mapVirtualFile("/a.cc", "void a() {}");
726
727 std::unique_ptr<FrontendActionFactory> Action(
728 newFrontendActionFactory<SyntaxOnlyAction>());
729
730 size_t SyntaxOnlyCount = 0;
731 ArgumentsAdjuster CheckSyntaxOnlyAdjuster =
732 [&SyntaxOnlyCount](const CommandLineArguments &Args,
733 StringRef /*unused*/) {
734 for (llvm::StringRef Arg : Args) {
735 if (Arg == "-fsyntax-only")
736 ++SyntaxOnlyCount;
737 }
738 return Args;
739 };
740
741 Tool.clearArgumentsAdjusters();
742 Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
743 Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
744 Tool.run(Action.get());
745 EXPECT_EQ(SyntaxOnlyCount, 1U);
746 }
747
748 TEST(ClangToolTest, NoOutputCommands) {
749 FixedCompilationDatabase Compilations("/", {"-save-temps", "-save-temps=cwd",
750 "--save-temps",
751 "--save-temps=somedir"});
752
753 ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
754 Tool.mapVirtualFile("/a.cc", "void a() {}");
755
756 std::unique_ptr<FrontendActionFactory> Action(
757 newFrontendActionFactory<SyntaxOnlyAction>());
758
759 const std::vector<llvm::StringRef> OutputCommands = {"-save-temps"};
760 bool Ran = false;
761 ArgumentsAdjuster CheckSyntaxOnlyAdjuster =
762 [&OutputCommands, &Ran](const CommandLineArguments &Args,
763 StringRef /*unused*/) {
764 for (llvm::StringRef Arg : Args) {
765 for (llvm::StringRef OutputCommand : OutputCommands)
766 EXPECT_FALSE(Arg.contains(OutputCommand));
767 }
768 Ran = true;
769 return Args;
770 };
771
772 Tool.clearArgumentsAdjusters();
773 Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
774 Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
775 Tool.run(Action.get());
776 EXPECT_TRUE(Ran);
777 }
778
779 TEST(ClangToolTest, BaseVirtualFileSystemUsage) {
780 FixedCompilationDatabase Compilations("/", std::vector<std::string>());
781 auto OverlayFileSystem =
782 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(
783 llvm::vfs::getRealFileSystem());
784 auto InMemoryFileSystem =
785 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
786 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
787
788 InMemoryFileSystem->addFile(
789 "a.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int main() {}"));
790
791 ClangTool Tool(Compilations, std::vector<std::string>(1, "a.cpp"),
792 std::make_shared<PCHContainerOperations>(), OverlayFileSystem);
793 std::unique_ptr<FrontendActionFactory> Action(
794 newFrontendActionFactory<SyntaxOnlyAction>());
795 EXPECT_EQ(0, Tool.run(Action.get()));
796 }
797
798 // Check getClangStripDependencyFileAdjuster doesn't strip args after -MD/-MMD.
799 TEST(ClangToolTest, StripDependencyFileAdjuster) {
800 FixedCompilationDatabase Compilations("/", {"-MD", "-c", "-MMD", "-w"});
801
802 ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
803 Tool.mapVirtualFile("/a.cc", "void a() {}");
804
805 std::unique_ptr<FrontendActionFactory> Action(
806 newFrontendActionFactory<SyntaxOnlyAction>());
807
808 CommandLineArguments FinalArgs;
809 ArgumentsAdjuster CheckFlagsAdjuster =
810 [&FinalArgs](const CommandLineArguments &Args, StringRef /*unused*/) {
811 FinalArgs = Args;
812 return Args;
813 };
814 Tool.clearArgumentsAdjusters();
815 Tool.appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
816 Tool.appendArgumentsAdjuster(CheckFlagsAdjuster);
817 Tool.run(Action.get());
818
819 auto HasFlag = [&FinalArgs](const std::string &Flag) {
820 return llvm::is_contained(FinalArgs, Flag);
821 };
822 EXPECT_FALSE(HasFlag("-MD"));
823 EXPECT_FALSE(HasFlag("-MMD"));
824 EXPECT_TRUE(HasFlag("-c"));
825 EXPECT_TRUE(HasFlag("-w"));
826 }
827
828 // Check getClangStripDependencyFileAdjuster strips /showIncludes and variants
829 TEST(ClangToolTest, StripDependencyFileAdjusterShowIncludes) {
830 FixedCompilationDatabase Compilations(
831 "/", {"/showIncludes", "/showIncludes:user", "-showIncludes",
832 "-showIncludes:user", "-c"});
833
834 ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
835 Tool.mapVirtualFile("/a.cc", "void a() {}");
836
837 std::unique_ptr<FrontendActionFactory> Action(
838 newFrontendActionFactory<SyntaxOnlyAction>());
839
840 CommandLineArguments FinalArgs;
841 ArgumentsAdjuster CheckFlagsAdjuster =
842 [&FinalArgs](const CommandLineArguments &Args, StringRef /*unused*/) {
843 FinalArgs = Args;
844 return Args;
845 };
846 Tool.clearArgumentsAdjusters();
847 Tool.appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
848 Tool.appendArgumentsAdjuster(CheckFlagsAdjuster);
849 Tool.run(Action.get());
850
851 auto HasFlag = [&FinalArgs](const std::string &Flag) {
852 return llvm::is_contained(FinalArgs, Flag);
853 };
854 EXPECT_FALSE(HasFlag("/showIncludes"));
855 EXPECT_FALSE(HasFlag("/showIncludes:user"));
856 EXPECT_FALSE(HasFlag("-showIncludes"));
857 EXPECT_FALSE(HasFlag("-showIncludes:user"));
858 EXPECT_TRUE(HasFlag("-c"));
859 }
860
861 // Check getClangStripDependencyFileAdjuster doesn't strip args when using the
862 // MSVC cl.exe driver
863 TEST(ClangToolTest, StripDependencyFileAdjusterMsvc) {
864 FixedCompilationDatabase Compilations(
865 "/", {"--driver-mode=cl", "-MD", "-MDd", "-MT", "-O1", "-MTd", "-MP"});
866
867 ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
868 Tool.mapVirtualFile("/a.cc", "void a() {}");
869
870 std::unique_ptr<FrontendActionFactory> Action(
871 newFrontendActionFactory<SyntaxOnlyAction>());
872
873 CommandLineArguments FinalArgs;
874 ArgumentsAdjuster CheckFlagsAdjuster =
875 [&FinalArgs](const CommandLineArguments &Args, StringRef /*unused*/) {
876 FinalArgs = Args;
877 return Args;
878 };
879 Tool.clearArgumentsAdjusters();
880 Tool.appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
881 Tool.appendArgumentsAdjuster(CheckFlagsAdjuster);
882 Tool.run(Action.get());
883
884 auto HasFlag = [&FinalArgs](const std::string &Flag) {
885 return llvm::is_contained(FinalArgs, Flag);
886 };
887 EXPECT_TRUE(HasFlag("-MD"));
888 EXPECT_TRUE(HasFlag("-MDd"));
889 EXPECT_TRUE(HasFlag("-MT"));
890 EXPECT_TRUE(HasFlag("-O1"));
891 EXPECT_TRUE(HasFlag("-MTd"));
892 EXPECT_TRUE(HasFlag("-MP"));
893 }
894
895 // Check getClangStripPluginsAdjuster strips plugin related args.
896 TEST(ClangToolTest, StripPluginsAdjuster) {
897 FixedCompilationDatabase Compilations(
898 "/", {"-Xclang", "-add-plugin", "-Xclang", "random-plugin"});
899
900 ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
901 Tool.mapVirtualFile("/a.cc", "void a() {}");
902
903 std::unique_ptr<FrontendActionFactory> Action(
904 newFrontendActionFactory<SyntaxOnlyAction>());
905
906 CommandLineArguments FinalArgs;
907 ArgumentsAdjuster CheckFlagsAdjuster =
908 [&FinalArgs](const CommandLineArguments &Args, StringRef /*unused*/) {
909 FinalArgs = Args;
910 return Args;
911 };
912 Tool.clearArgumentsAdjusters();
913 Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
914 Tool.appendArgumentsAdjuster(CheckFlagsAdjuster);
915 Tool.run(Action.get());
916
917 auto HasFlag = [&FinalArgs](const std::string &Flag) {
918 return llvm::is_contained(FinalArgs, Flag);
919 };
920 EXPECT_FALSE(HasFlag("-Xclang"));
921 EXPECT_FALSE(HasFlag("-add-plugin"));
922 EXPECT_FALSE(HasFlag("-random-plugin"));
923 }
924
925 TEST(addTargetAndModeForProgramName, AddsTargetAndMode) {
926 llvm::InitializeAllTargets();
927
928 std::string Target = getAnyTargetForTesting();
929 ASSERT_FALSE(Target.empty());
930
931 std::vector<std::string> Args = {"clang", "-foo"};
932 addTargetAndModeForProgramName(Args, "");
933 EXPECT_EQ((std::vector<std::string>{"clang", "-foo"}), Args);
934 addTargetAndModeForProgramName(Args, Target + "-g++");
935 EXPECT_EQ((std::vector<std::string>{"clang", "--target=" + Target,
936 "--driver-mode=g++", "-foo"}),
937 Args);
938 }
939
940 TEST(addTargetAndModeForProgramName, PathIgnored) {
941 llvm::InitializeAllTargets();
942 std::string Target = getAnyTargetForTesting();
943 ASSERT_FALSE(Target.empty());
944
945 SmallString<32> ToolPath;
946 llvm::sys::path::append(ToolPath, "foo", "bar", Target + "-g++");
947
948 std::vector<std::string> Args = {"clang", "-foo"};
949 addTargetAndModeForProgramName(Args, ToolPath);
950 EXPECT_EQ((std::vector<std::string>{"clang", "--target=" + Target,
951 "--driver-mode=g++", "-foo"}),
952 Args);
953 }
954
955 TEST(addTargetAndModeForProgramName, IgnoresExistingTarget) {
956 llvm::InitializeAllTargets();
957 std::string Target = getAnyTargetForTesting();
958 ASSERT_FALSE(Target.empty());
959
960 std::vector<std::string> Args = {"clang", "-foo", "-target", "something"};
961 addTargetAndModeForProgramName(Args, Target + "-g++");
962 EXPECT_EQ((std::vector<std::string>{"clang", "--driver-mode=g++", "-foo",
963 "-target", "something"}),
964 Args);
965
966 std::vector<std::string> ArgsAlt = {"clang", "-foo", "--target=something"};
967 addTargetAndModeForProgramName(ArgsAlt, Target + "-g++");
968 EXPECT_EQ((std::vector<std::string>{"clang", "--driver-mode=g++", "-foo",
969 "--target=something"}),
970 ArgsAlt);
971 }
972
973 TEST(addTargetAndModeForProgramName, IgnoresExistingMode) {
974 llvm::InitializeAllTargets();
975 std::string Target = getAnyTargetForTesting();
976 ASSERT_FALSE(Target.empty());
977
978 std::vector<std::string> Args = {"clang", "-foo", "--driver-mode=abc"};
979 addTargetAndModeForProgramName(Args, Target + "-g++");
980 EXPECT_EQ((std::vector<std::string>{"clang", "--target=" + Target, "-foo",
981 "--driver-mode=abc"}),
982 Args);
983 }
984
985 #ifndef _WIN32
986 TEST(ClangToolTest, BuildASTs) {
987 FixedCompilationDatabase Compilations("/", std::vector<std::string>());
988
989 std::vector<std::string> Sources;
990 Sources.push_back("/a.cc");
991 Sources.push_back("/b.cc");
992 ClangTool Tool(Compilations, Sources);
993
994 Tool.mapVirtualFile("/a.cc", "void a() {}");
995 Tool.mapVirtualFile("/b.cc", "void b() {}");
996
997 std::vector<std::unique_ptr<ASTUnit>> ASTs;
998 EXPECT_EQ(0, Tool.buildASTs(ASTs));
999 EXPECT_EQ(2u, ASTs.size());
1000 }
1001
1002 TEST(ClangToolTest, InjectDiagnosticConsumer) {
1003 FixedCompilationDatabase Compilations("/", std::vector<std::string>());
1004 ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
1005 Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
1006 TestDiagnosticConsumer Consumer;
1007 Tool.setDiagnosticConsumer(&Consumer);
1008 std::unique_ptr<FrontendActionFactory> Action(
1009 newFrontendActionFactory<SyntaxOnlyAction>());
1010 Tool.run(Action.get());
1011 EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
1012 }
1013
1014 TEST(ClangToolTest, InjectDiagnosticConsumerInBuildASTs) {
1015 FixedCompilationDatabase Compilations("/", std::vector<std::string>());
1016 ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
1017 Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
1018 TestDiagnosticConsumer Consumer;
1019 Tool.setDiagnosticConsumer(&Consumer);
1020 std::vector<std::unique_ptr<ASTUnit>> ASTs;
1021 Tool.buildASTs(ASTs);
1022 EXPECT_EQ(1u, ASTs.size());
1023 EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
1024 }
1025 #endif
1026
1027 TEST(runToolOnCode, TestResetDiagnostics) {
1028 // This is a tool that resets the diagnostic during the compilation.
1029 struct ResetDiagnosticAction : public clang::ASTFrontendAction {
1030 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
1031 StringRef) override {
1032 struct Consumer : public clang::ASTConsumer {
1033 bool HandleTopLevelDecl(clang::DeclGroupRef D) override {
1034 auto &Diags = (*D.begin())->getASTContext().getDiagnostics();
1035 // Ignore any error
1036 Diags.Reset();
1037 // Disable warnings because computing the CFG might crash.
1038 Diags.setIgnoreAllWarnings(true);
1039 return true;
1040 }
1041 };
1042 return std::make_unique<Consumer>();
1043 }
1044 };
1045
1046 // Should not crash
1047 EXPECT_FALSE(
1048 runToolOnCode(std::make_unique<ResetDiagnosticAction>(),
1049 "struct Foo { Foo(int); ~Foo(); struct Fwd _fwd; };"
1050 "void func() { long x; Foo f(x); }"));
1051 }
1052
1053 namespace {
1054 struct TestCommand {
1055 llvm::StringRef File;
1056 llvm::StringRef Command;
1057 };
1058
1059 std::string runToolWithProgress(llvm::ArrayRef<TestCommand> Commands,
1060 llvm::StringRef BaseDir) {
1061 std::string ErrorMessage;
1062
1063 llvm::json::Array Entries;
1064 for (const auto &Cmd : Commands) {
1065 Entries.push_back(llvm::json::Object{
1066 {"directory", BaseDir}, {"command", Cmd.Command}, {"file", Cmd.File}});
1067 }
1068 std::string DatabaseContent;
1069 llvm::raw_string_ostream OS(DatabaseContent);
1070 OS << llvm::json::Value(std::move(Entries));
1071
1072 std::unique_ptr<CompilationDatabase> Database(
1073 JSONCompilationDatabase::loadFromBuffer(DatabaseContent, ErrorMessage,
1074 JSONCommandLineSyntax::Gnu));
1075 if (!Database) {
1076 ADD_FAILURE() << "Failed to load compilation database: " << ErrorMessage;
1077 return "";
1078 }
1079
1080 std::vector<std::string> AbsoluteFiles;
1081 for (const auto &Cmd : Commands) {
1082 SmallString<32> NativeFile(BaseDir);
1083 llvm::sys::path::append(NativeFile, Cmd.File);
1084 llvm::sys::path::native(NativeFile);
1085 std::string AbsPath = std::string(NativeFile);
1086 if (AbsoluteFiles.empty() || AbsoluteFiles.back() != AbsPath) {
1087 AbsoluteFiles.push_back(AbsPath);
1088 }
1089 }
1090
1091 ClangTool Tool(*Database, AbsoluteFiles);
1092 for (const auto &F : AbsoluteFiles) {
1093 Tool.mapVirtualFile(F, "int x;");
1094 }
1095
1096 testing::internal::CaptureStderr();
1097 Tool.run(newFrontendActionFactory<SyntaxOnlyAction>().get());
1098 return testing::internal::GetCapturedStderr();
1099 }
1100 } // namespace
1101
1102 TEST(ClangToolTest, ProgressReportSingleFile) {
1103 SmallString<32> BaseDir;
1104 llvm::sys::path::system_temp_directory(false, BaseDir);
1105 llvm::sys::path::native(BaseDir, llvm::sys::path::Style::posix);
1106
1107 EXPECT_TRUE(
1108 runToolWithProgress({{"test.cpp", "clang++ -c test.cpp"}}, BaseDir)
1109 .empty());
1110 }
1111
1112 TEST(ClangToolTest, ProgressReportMultipleFiles) {
1113 SmallString<32> BaseDir;
1114 llvm::sys::path::system_temp_directory(false, BaseDir);
1115 llvm::sys::path::native(BaseDir, llvm::sys::path::Style::posix);
1116
1117 std::string Output =
1118 runToolWithProgress({{"test1.cpp", "clang++ -c test1.cpp"},
1119 {"test2.cpp", "clang++ -c test2.cpp"}},
1120 BaseDir);
1121
1122 SmallString<32> NativeFile1(BaseDir);
1123 llvm::sys::path::append(NativeFile1, "test1.cpp");
1124 llvm::sys::path::native(NativeFile1);
1125 SmallString<32> NativeFile2(BaseDir);
1126 llvm::sys::path::append(NativeFile2, "test2.cpp");
1127 llvm::sys::path::native(NativeFile2);
1128
1129 std::string Expected = "[1/2] Processing file " + std::string(NativeFile1) +
1130 ".\n" + "[2/2] Processing file " +
1131 std::string(NativeFile2) + ".\n";
1132 EXPECT_EQ(Output, Expected);
1133 }
1134
1135 TEST(ClangToolTest, ProgressReportMultipleCommands) {
1136 SmallString<32> BaseDir;
1137 llvm::sys::path::system_temp_directory(false, BaseDir);
1138 llvm::sys::path::native(BaseDir, llvm::sys::path::Style::posix);
1139
1140 std::string Output =
1141 runToolWithProgress({{"test.cpp", "clang++ -c test.cpp -DCMD1"},
1142 {"test.cpp", "clang++ -c test.cpp -DCMD2"}},
1143 BaseDir);
1144
1145 SmallString<32> NativeFile(BaseDir);
1146 llvm::sys::path::append(NativeFile, "test.cpp");
1147 llvm::sys::path::native(NativeFile);
1148 std::string Expected =
1149 "[1/1] (1/2) Processing file " + std::string(NativeFile) + ".\n" +
1150 "[1/1] (2/2) Processing file " + std::string(NativeFile) + ".\n";
1151 EXPECT_EQ(Output, Expected);
1152 }
1153
1154 TEST(ClangToolTest, ProgressReportMixed) {
1155 SmallString<32> BaseDir;
1156 llvm::sys::path::system_temp_directory(false, BaseDir);
1157 llvm::sys::path::native(BaseDir, llvm::sys::path::Style::posix);
1158
1159 std::string Output =
1160 runToolWithProgress({{"test1.cpp", "clang++ -c test1.cpp"},
1161 {"test2.cpp", "clang++ -c test2.cpp -DCMD1"},
1162 {"test2.cpp", "clang++ -c test2.cpp -DCMD2"},
1163 {"test3.cpp", "clang++ -c test3.cpp"}},
1164 BaseDir);
1165
1166 SmallString<32> NativeFile1(BaseDir);
1167 llvm::sys::path::append(NativeFile1, "test1.cpp");
1168 llvm::sys::path::native(NativeFile1);
1169 SmallString<32> NativeFile2(BaseDir);
1170 llvm::sys::path::append(NativeFile2, "test2.cpp");
1171 llvm::sys::path::native(NativeFile2);
1172 SmallString<32> NativeFile3(BaseDir);
1173 llvm::sys::path::append(NativeFile3, "test3.cpp");
1174 llvm::sys::path::native(NativeFile3);
1175
1176 std::string Expected =
1177 "[1/3] Processing file " + std::string(NativeFile1) + ".\n" +
1178 "[2/3] (1/2) Processing file " + std::string(NativeFile2) + ".\n" +
1179 "[2/3] (2/2) Processing file " + std::string(NativeFile2) + ".\n" +
1180 "[3/3] Processing file " + std::string(NativeFile3) + ".\n";
1181 EXPECT_EQ(Output, Expected);
1182 }
1183
1184 } // end namespace tooling
1185 } // end namespace clang