Debian Codegraph @

clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

raw
1 //===-- RecordTest.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-include-cleaner/Record.h"
10 #include "clang-include-cleaner/Types.h"
11 #include "clang/AST/Decl.h"
12 #include "clang/Basic/Diagnostic.h"
13 #include "clang/Basic/LLVM.h"
14 #include "clang/Basic/SourceLocation.h"
15 #include "clang/Frontend/CompilerInvocation.h"
16 #include "clang/Frontend/FrontendAction.h"
17 #include "clang/Frontend/FrontendActions.h"
18 #include "clang/Frontend/FrontendOptions.h"
19 #include "clang/Serialization/PCHContainerOperations.h"
20 #include "clang/Testing/TestAST.h"
21 #include "clang/Tooling/Inclusions/StandardLibrary.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/IntrusiveRefCntPtr.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/Support/Error.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/VirtualFileSystem.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Testing/Annotations/Annotations.h"
30 #include "gmock/gmock.h"
31 #include "gtest/gtest.h"
32 #include <cassert>
33 #include <memory>
34 #include <optional>
35 #include <utility>
36
37 namespace clang::include_cleaner {
38 namespace {
39 using testing::ElementsAreArray;
40 using testing::IsEmpty;
41
42 // Matches a Decl* if it is a NamedDecl with the given name.
43 MATCHER_P(named, N, "") {
44 if (const NamedDecl *ND = llvm::dyn_cast<NamedDecl>(arg)) {
45 if (N == ND->getNameAsString())
46 return true;
47 }
48 std::string S;
49 llvm::raw_string_ostream OS(S);
50 arg->dump(OS);
51 *result_listener << S;
52 return false;
53 }
54
55 MATCHER_P(FileNamed, N, "") {
56 if (arg.getFileEntry().tryGetRealPathName() == N)
57 return true;
58 *result_listener << arg.getFileEntry().tryGetRealPathName().str();
59 return false;
60 }
61
62 class RecordASTTest : public ::testing::Test {
63 protected:
64 TestInputs Inputs;
65 RecordedAST Recorded;
66
67 RecordASTTest() {
68 struct RecordAction : public ASTFrontendAction {
69 RecordedAST &Out;
70 RecordAction(RecordedAST &Out) : Out(Out) {}
71 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
72 StringRef) override {
73 return Out.record();
74 }
75 };
76 Inputs.MakeAction = [this] {
77 return std::make_unique<RecordAction>(Recorded);
78 };
79 }
80
81 TestAST build() { return TestAST(Inputs); }
82 };
83
84 // Top-level decl from the main file is a root, nested ones aren't.
85 TEST_F(RecordASTTest, Namespace) {
86 Inputs.Code =
87 R"cpp(
88 namespace ns {
89 int x;
90 namespace {
91 int y;
92 }
93 }
94 )cpp";
95 auto AST = build();
96 EXPECT_THAT(Recorded.Roots, testing::ElementsAre(named("ns")));
97 }
98
99 // Decl in included file is not a root.
100 TEST_F(RecordASTTest, Inclusion) {
101 Inputs.ExtraFiles["header.h"] = "void headerFunc();";
102 Inputs.Code = R"cpp(
103 #include "header.h"
104 void mainFunc();
105 )cpp";
106 auto AST = build();
107 EXPECT_THAT(Recorded.Roots, testing::ElementsAre(named("mainFunc")));
108 }
109
110 // Decl from macro expanded into the main file is a root.
111 TEST_F(RecordASTTest, Macros) {
112 Inputs.ExtraFiles["header.h"] = "#define X void x();";
113 Inputs.Code = R"cpp(
114 #include "header.h"
115 X
116 )cpp";
117 auto AST = build();
118 EXPECT_THAT(Recorded.Roots, testing::ElementsAre(named("x")));
119 }
120
121 // Decl from template instantiation is filtered out from roots.
122 TEST_F(RecordASTTest, ImplicitTemplates) {
123 Inputs.ExtraFiles["dispatch.h"] = R"cpp(
124 struct A {
125 static constexpr int value = 1;
126 };
127 template <class Getter>
128 int dispatch() {
129 return Getter::template get<A>();
130 }
131 )cpp";
132 Inputs.Code = R"cpp(
133 #include "dispatch.h"
134 struct MyGetter {
135 template <class T> static int get() { return T::value; }
136 };
137 int v = dispatch<MyGetter>();
138 )cpp";
139 auto AST = build();
140 EXPECT_THAT(Recorded.Roots,
141 testing::ElementsAre(named("MyGetter"), named("v")));
142 }
143
144 class RecordPPTest : public ::testing::Test {
145 protected:
146 TestInputs Inputs;
147 RecordedPP Recorded;
148
149 RecordPPTest() {
150 struct RecordAction : public PreprocessOnlyAction {
151 RecordedPP &Out;
152 RecordAction(RecordedPP &Out) : Out(Out) {}
153
154 void ExecuteAction() override {
155 auto &PP = getCompilerInstance().getPreprocessor();
156 PP.addPPCallbacks(Out.record(PP));
157 PreprocessOnlyAction::ExecuteAction();
158 }
159 };
160 Inputs.MakeAction = [this] {
161 return std::make_unique<RecordAction>(Recorded);
162 };
163 }
164
165 TestAST build() { return TestAST(Inputs); }
166 };
167
168 // Matches an Include with a particular spelling.
169 MATCHER_P(spelled, S, "") { return arg.Spelled == S; }
170
171 TEST_F(RecordPPTest, CapturesIncludes) {
172 llvm::Annotations MainFile(R"cpp(
173 $H^#include "./header.h"
174 $M^#include <missing.h>
175 )cpp");
176 Inputs.Code = MainFile.code();
177 Inputs.ExtraFiles["header.h"] = "";
178 Inputs.ErrorOK = true; // missing header
179 auto AST = build();
180
181 ASSERT_THAT(
182 Recorded.Includes.all(),
183 testing::ElementsAre(spelled("./header.h"), spelled("missing.h")));
184
185 auto &H = Recorded.Includes.all().front();
186 EXPECT_EQ(H.Line, 2u);
187 EXPECT_EQ(H.HashLocation,
188 AST.sourceManager().getComposedLoc(
189 AST.sourceManager().getMainFileID(), MainFile.point("H")));
190 EXPECT_EQ(H.Resolved, *AST.fileManager().getOptionalFileRef("header.h"));
191 EXPECT_FALSE(H.Angled);
192
193 auto &M = Recorded.Includes.all().back();
194 EXPECT_EQ(M.Line, 3u);
195 EXPECT_EQ(M.HashLocation,
196 AST.sourceManager().getComposedLoc(
197 AST.sourceManager().getMainFileID(), MainFile.point("M")));
198 EXPECT_EQ(M.Resolved, std::nullopt);
199 EXPECT_TRUE(M.Angled);
200 }
201
202 TEST_F(RecordPPTest, CapturesMacroRefs) {
203 llvm::Annotations Header(R"cpp(
204 #define $def^X 1
205
206 // Refs, but not in main file.
207 #define Y X
208 int one = X;
209 )cpp");
210 llvm::Annotations MainFile(R"cpp(
211 #define EARLY X // not a ref, no definition
212 #include "header.h"
213 #define LATE ^X
214 #define LATE2 ^X // a ref even if not expanded
215
216 int uno = ^X;
217 int jeden = $exp^LATE; // a ref in LATE's expansion
218
219 #define IDENT(X) X // not a ref, shadowed
220 int eins = IDENT(^X);
221
222 #undef ^X
223 // Not refs, rather a new macro with the same name.
224 #define X 2
225 int two = X;
226 )cpp");
227 Inputs.Code = MainFile.code();
228 Inputs.ExtraFiles["header.h"] = Header.code();
229 auto AST = build();
230 const auto &SM = AST.sourceManager();
231
232 SourceLocation Def = SM.getComposedLoc(
233 SM.translateFile(AST.fileManager().getFile("header.h").get()),
234 Header.point("def"));
235 ASSERT_THAT(Recorded.MacroReferences, Not(IsEmpty()));
236 Symbol OrigX = Recorded.MacroReferences.front().Target;
237 EXPECT_EQ("X", OrigX.macro().Name->getName());
238 EXPECT_EQ(Def, OrigX.macro().Definition);
239
240 std::vector<unsigned> RefOffsets;
241 std::vector<unsigned> ExpOffsets; // Expansion locs of refs in macro locs.
242 for (const auto &Ref : Recorded.MacroReferences) {
243 if (Ref.Target == OrigX) {
244 auto [FID, Off] = SM.getDecomposedLoc(Ref.RefLocation);
245 if (FID == SM.getMainFileID()) {
246 RefOffsets.push_back(Off);
247 } else if (Ref.RefLocation.isMacroID() &&
248 SM.isWrittenInMainFile(SM.getExpansionLoc(Ref.RefLocation))) {
249 ExpOffsets.push_back(
250 SM.getDecomposedExpansionLoc(Ref.RefLocation).second);
251 } else {
252 ADD_FAILURE() << Ref.RefLocation.printToString(SM);
253 }
254 }
255 }
256 EXPECT_THAT(RefOffsets, ElementsAreArray(MainFile.points()));
257 EXPECT_THAT(ExpOffsets, ElementsAreArray(MainFile.points("exp")));
258 }
259
260 TEST_F(RecordPPTest, CapturesConditionalMacroRefs) {
261 llvm::Annotations MainFile(R"cpp(
262 #define X 1
263
264 #ifdef ^X
265 #endif
266
267 #if defined(^X)
268 #endif
269
270 #ifndef ^X
271 #endif
272
273 #ifdef Y
274 #elifdef ^X
275 #endif
276
277 #ifndef ^X
278 #elifndef ^X
279 #endif
280 )cpp");
281
282 Inputs.Code = MainFile.code();
283 Inputs.ExtraArgs.push_back("-std=c++2b");
284 auto AST = build();
285
286 std::vector<unsigned> RefOffsets;
287 SourceManager &SM = AST.sourceManager();
288 for (const auto &Ref : Recorded.MacroReferences) {
289 auto [FID, Off] = SM.getDecomposedLoc(Ref.RefLocation);
290 ASSERT_EQ(FID, SM.getMainFileID());
291 EXPECT_EQ(Ref.RT, RefType::Ambiguous);
292 EXPECT_EQ("X", Ref.Target.macro().Name->getName());
293 RefOffsets.push_back(Off);
294 }
295 EXPECT_THAT(RefOffsets, ElementsAreArray(MainFile.points()));
296 }
297
298 class PragmaIncludeTest : public ::testing::Test {
299 protected:
300 // We don't build an AST, we just run a preprocessor action!
301 TestInputs Inputs;
302 PragmaIncludes PI;
303
304 PragmaIncludeTest() {
305 Inputs.MakeAction = [this] {
306 struct Hook : public PreprocessOnlyAction {
307 public:
308 Hook(PragmaIncludes *Out) : Out(Out) {}
309 bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
310 Out->record(CI);
311 return true;
312 }
313 PragmaIncludes *Out;
314 };
315 return std::make_unique<Hook>(&PI);
316 };
317 }
318
319 TestAST build(bool ResetPragmaIncludes = true) {
320 if (ResetPragmaIncludes) PI = PragmaIncludes();
321 return TestAST(Inputs);
322 }
323
324 void createEmptyFiles(llvm::ArrayRef<StringRef> FileNames) {
325 for (llvm::StringRef File : FileNames)
326 Inputs.ExtraFiles[File] = "#pragma once";
327 }
328 };
329
330 TEST_F(PragmaIncludeTest, IWYUKeep) {
331 Inputs.Code = R"cpp(
332 #include "keep1.h" // IWYU pragma: keep
333 #include "keep2.h" /* IWYU pragma: keep */
334
335 #include "export1.h" // IWYU pragma: export
336 // IWYU pragma: begin_exports
337 #include "export2.h"
338 #include "export3.h"
339 // IWYU pragma: end_exports
340
341 #include "normal.h"
342
343 // IWYU pragma: begin_keep
344 #include "keep3.h"
345 // IWYU pragma: end_keep
346
347 // IWYU pragma: begin_keep
348 #include "keep4.h"
349 // IWYU pragma: begin_keep
350 #include "keep5.h"
351 // IWYU pragma: end_keep
352 #include "keep6.h"
353 // IWYU pragma: end_keep
354 #include <vector>
355 #include <map> // IWYU pragma: keep
356 #include <set> // IWYU pragma: export
357 )cpp";
358 createEmptyFiles({"keep1.h", "keep2.h", "keep3.h", "keep4.h", "keep5.h",
359 "keep6.h", "export1.h", "export2.h", "export3.h",
360 "normal.h", "std/vector", "std/map", "std/set"});
361
362 Inputs.ExtraArgs.push_back("-isystemstd");
363 TestAST Processed = build();
364 auto &FM = Processed.fileManager();
365
366 EXPECT_FALSE(PI.shouldKeep(FM.getFile("normal.h").get()));
367 EXPECT_FALSE(PI.shouldKeep(FM.getFile("std/vector").get()));
368
369 // Keep
370 EXPECT_TRUE(PI.shouldKeep(FM.getFile("keep1.h").get()));
371 EXPECT_TRUE(PI.shouldKeep(FM.getFile("keep2.h").get()));
372 EXPECT_TRUE(PI.shouldKeep(FM.getFile("keep3.h").get()));
373 EXPECT_TRUE(PI.shouldKeep(FM.getFile("keep4.h").get()));
374 EXPECT_TRUE(PI.shouldKeep(FM.getFile("keep5.h").get()));
375 EXPECT_TRUE(PI.shouldKeep(FM.getFile("keep6.h").get()));
376 EXPECT_TRUE(PI.shouldKeep(FM.getFile("std/map").get()));
377
378 // Exports
379 EXPECT_TRUE(PI.shouldKeep(FM.getFile("export1.h").get()));
380 EXPECT_TRUE(PI.shouldKeep(FM.getFile("export2.h").get()));
381 EXPECT_TRUE(PI.shouldKeep(FM.getFile("export3.h").get()));
382 EXPECT_TRUE(PI.shouldKeep(FM.getFile("std/set").get()));
383 }
384
385 TEST_F(PragmaIncludeTest, AssociatedHeader) {
386 createEmptyFiles({"foo/main.h", "bar/main.h", "bar/other.h", "std/vector"});
387 auto IsKeep = [&](llvm::StringRef Name, TestAST &AST) {
388 return PI.shouldKeep(AST.fileManager().getFile(Name).get());
389 };
390
391 Inputs.FileName = "main.cc";
392 Inputs.ExtraArgs.push_back("-isystemstd");
393 {
394 Inputs.Code = R"cpp(
395 #include "foo/main.h"
396 #include "bar/main.h"
397 )cpp";
398 auto AST = build();
399 EXPECT_TRUE(IsKeep("foo/main.h", AST));
400 EXPECT_FALSE(IsKeep("bar/main.h", AST)) << "not first include";
401 }
402
403 {
404 Inputs.Code = R"cpp(
405 #include "bar/other.h"
406 #include "bar/main.h"
407 )cpp";
408 auto AST = build();
409 EXPECT_FALSE(IsKeep("bar/other.h", AST));
410 EXPECT_FALSE(IsKeep("bar/main.h", AST)) << "not first include";
411 }
412
413 {
414 Inputs.Code = R"cpp(
415 #include "foo/main.h"
416 #include "bar/other.h" // IWYU pragma: associated
417 #include <vector> // IWYU pragma: associated
418 )cpp";
419 auto AST = build();
420 EXPECT_TRUE(IsKeep("foo/main.h", AST));
421 EXPECT_TRUE(IsKeep("bar/other.h", AST));
422 EXPECT_TRUE(IsKeep("std/vector", AST));
423 }
424
425 Inputs.FileName = "vector.cc";
426 {
427 Inputs.Code = R"cpp(
428 #include <vector>
429 )cpp";
430 auto AST = build();
431 EXPECT_FALSE(IsKeep("std/vector", AST)) << "stdlib is not associated";
432 }
433 }
434
435 TEST_F(PragmaIncludeTest, IWYUPrivate) {
436 Inputs.Code = R"cpp(
437 #include "public.h"
438 )cpp";
439 Inputs.ExtraFiles["public.h"] = R"cpp(
440 #include "private.h"
441 #include "private2.h"
442 )cpp";
443 Inputs.ExtraFiles["private.h"] = R"cpp(
444 // IWYU pragma: private, include "public2.h"
445 )cpp";
446 Inputs.ExtraFiles["private2.h"] = R"cpp(
447 // IWYU pragma: private
448 )cpp";
449 TestAST Processed = build();
450 auto PrivateFE = Processed.fileManager().getFile("private.h");
451 assert(PrivateFE);
452 EXPECT_TRUE(PI.isPrivate(PrivateFE.get()));
453 EXPECT_EQ(PI.getPublic(PrivateFE.get()), "\"public2.h\"");
454
455 auto PublicFE = Processed.fileManager().getFile("public.h");
456 assert(PublicFE);
457 EXPECT_EQ(PI.getPublic(PublicFE.get()), ""); // no mapping.
458 EXPECT_FALSE(PI.isPrivate(PublicFE.get()));
459
460 auto Private2FE = Processed.fileManager().getFile("private2.h");
461 assert(Private2FE);
462 EXPECT_TRUE(PI.isPrivate(Private2FE.get()));
463 }
464
465 TEST_F(PragmaIncludeTest, IWYUExport) {
466 Inputs.Code = R"cpp(// Line 1
467 #include "export1.h"
468 #include "export2.h"
469 )cpp";
470 Inputs.ExtraFiles["export1.h"] = R"cpp(
471 #include "private.h" // IWYU pragma: export
472 )cpp";
473 Inputs.ExtraFiles["export2.h"] = R"cpp(
474 #include "export3.h"
475 )cpp";
476 Inputs.ExtraFiles["export3.h"] = R"cpp(
477 #include "private.h" // IWYU pragma: export
478 )cpp";
479 Inputs.ExtraFiles["private.h"] = "";
480 TestAST Processed = build();
481 const auto &SM = Processed.sourceManager();
482 auto &FM = Processed.fileManager();
483
484 EXPECT_THAT(PI.getExporters(FM.getFile("private.h").get(), FM),
485 testing::UnorderedElementsAre(FileNamed("export1.h"),
486 FileNamed("export3.h")));
487
488 EXPECT_TRUE(PI.getExporters(FM.getFile("export1.h").get(), FM).empty());
489 EXPECT_TRUE(PI.getExporters(FM.getFile("export2.h").get(), FM).empty());
490 EXPECT_TRUE(PI.getExporters(FM.getFile("export3.h").get(), FM).empty());
491 EXPECT_TRUE(
492 PI.getExporters(SM.getFileEntryForID(SM.getMainFileID()), FM).empty());
493 }
494
495 TEST_F(PragmaIncludeTest, IWYUExportForStandardHeaders) {
496 Inputs.Code = R"cpp(
497 #include "export.h"
498 )cpp";
499 Inputs.ExtraFiles["export.h"] = R"cpp(
500 #include <string> // IWYU pragma: export
501 )cpp";
502 Inputs.ExtraFiles["string"] = "";
503 Inputs.ExtraArgs = {"-isystem."};
504 TestAST Processed = build();
505 auto &FM = Processed.fileManager();
506 EXPECT_THAT(PI.getExporters(*tooling::stdlib::Header::named("<string>"), FM),
507 testing::UnorderedElementsAre(FileNamed("export.h")));
508 EXPECT_THAT(PI.getExporters(llvm::cantFail(FM.getFileRef("string")), FM),
509 testing::UnorderedElementsAre(FileNamed("export.h")));
510 }
511
512 TEST_F(PragmaIncludeTest, IWYUExportBlock) {
513 Inputs.Code = R"cpp(// Line 1
514 #include "normal.h"
515 )cpp";
516 Inputs.ExtraFiles["normal.h"] = R"cpp(
517 #include "foo.h"
518
519 // IWYU pragma: begin_exports
520 #include "export1.h"
521 #include "private1.h"
522 // IWYU pragma: end_exports
523 )cpp";
524 Inputs.ExtraFiles["export1.h"] = R"cpp(
525 // IWYU pragma: begin_exports
526 #include "private1.h"
527 #include "private2.h"
528 // IWYU pragma: end_exports
529
530 #include "bar.h"
531 #include "private3.h" // IWYU pragma: export
532 )cpp";
533 createEmptyFiles(
534 {"private1.h", "private2.h", "private3.h", "foo.h", "bar.h"});
535 TestAST Processed = build();
536 auto &FM = Processed.fileManager();
537
538 EXPECT_THAT(PI.getExporters(FM.getFile("private1.h").get(), FM),
539 testing::UnorderedElementsAre(FileNamed("export1.h"),
540 FileNamed("normal.h")));
541 EXPECT_THAT(PI.getExporters(FM.getFile("private2.h").get(), FM),
542 testing::UnorderedElementsAre(FileNamed("export1.h")));
543 EXPECT_THAT(PI.getExporters(FM.getFile("private3.h").get(), FM),
544 testing::UnorderedElementsAre(FileNamed("export1.h")));
545
546 EXPECT_TRUE(PI.getExporters(FM.getFile("foo.h").get(), FM).empty());
547 EXPECT_TRUE(PI.getExporters(FM.getFile("bar.h").get(), FM).empty());
548 }
549
550 TEST_F(PragmaIncludeTest, SelfContained) {
551 Inputs.Code = R"cpp(
552 #include "guarded.h"
553
554 #include "unguarded.h"
555 )cpp";
556 Inputs.ExtraFiles["guarded.h"] = R"cpp(
557 #pragma once
558 )cpp";
559 Inputs.ExtraFiles["unguarded.h"] = "";
560 TestAST Processed = build();
561 auto &FM = Processed.fileManager();
562 EXPECT_TRUE(PI.isSelfContained(FM.getFile("guarded.h").get()));
563 EXPECT_FALSE(PI.isSelfContained(FM.getFile("unguarded.h").get()));
564 }
565
566 TEST_F(PragmaIncludeTest, AlwaysKeep) {
567 Inputs.Code = R"cpp(
568 #include "always_keep.h"
569 #include "usual.h"
570 )cpp";
571 Inputs.ExtraFiles["always_keep.h"] = R"cpp(
572 #pragma once
573 // IWYU pragma: always_keep
574 )cpp";
575 Inputs.ExtraFiles["usual.h"] = "#pragma once";
576 TestAST Processed = build();
577 auto &FM = Processed.fileManager();
578 EXPECT_TRUE(PI.shouldKeep(FM.getFile("always_keep.h").get()));
579 EXPECT_FALSE(PI.shouldKeep(FM.getFile("usual.h").get()));
580 }
581
582 TEST_F(PragmaIncludeTest, ExportInUnnamedBuffer) {
583 llvm::StringLiteral Filename = "test.cpp";
584 auto Code = R"cpp(#include "exporter.h")cpp";
585 Inputs.ExtraFiles["exporter.h"] = R"cpp(
586 #pragma once
587 #include "foo.h" // IWYU pragma: export
588 )cpp";
589 Inputs.ExtraFiles["foo.h"] = "";
590
591 auto Clang = std::make_unique<CompilerInstance>(
592 std::make_shared<PCHContainerOperations>());
593 Clang->createDiagnostics();
594
595 Clang->setInvocation(std::make_unique<CompilerInvocation>());
596 ASSERT_TRUE(CompilerInvocation::CreateFromArgs(
597 Clang->getInvocation(), {Filename.data()}, Clang->getDiagnostics(),
598 "clang"));
599
600 // Create unnamed memory buffers for all the files.
601 auto VFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
602 VFS->addFile(Filename, /*ModificationTime=*/0,
603 llvm::MemoryBuffer::getMemBufferCopy(Code, /*BufferName=*/""));
604 for (const auto &Extra : Inputs.ExtraFiles)
605 VFS->addFile(Extra.getKey(), /*ModificationTime=*/0,
606 llvm::MemoryBuffer::getMemBufferCopy(Extra.getValue(),
607 /*BufferName=*/""));
608 auto *FM = Clang->createFileManager(VFS);
609 ASSERT_TRUE(Clang->ExecuteAction(*Inputs.MakeAction()));
610 EXPECT_THAT(
611 PI.getExporters(llvm::cantFail(FM->getFileRef("foo.h")), *FM),
612 testing::ElementsAre(llvm::cantFail(FM->getFileRef("exporter.h"))));
613 }
614
615 TEST_F(PragmaIncludeTest, OutlivesFMAndSM) {
616 Inputs.Code = R"cpp(
617 #include "public.h"
618 )cpp";
619 Inputs.ExtraFiles["public.h"] = R"cpp(
620 #include "private.h"
621 #include "private2.h" // IWYU pragma: export
622 )cpp";
623 Inputs.ExtraFiles["private.h"] = R"cpp(
624 // IWYU pragma: private, include "public.h"
625 )cpp";
626 Inputs.ExtraFiles["private2.h"] = R"cpp(
627 // IWYU pragma: private
628 )cpp";
629 build(); // Fills up PI, file/source manager used is destroyed afterwards.
630 Inputs.MakeAction = nullptr; // Don't populate PI anymore.
631
632 // Now this build gives us a new File&Source Manager.
633 TestAST Processed = build(/*ResetPragmaIncludes=*/false);
634 auto &FM = Processed.fileManager();
635 auto PrivateFE = FM.getFile("private.h");
636 assert(PrivateFE);
637 EXPECT_EQ(PI.getPublic(PrivateFE.get()), "\"public.h\"");
638
639 auto Private2FE = FM.getFile("private2.h");
640 assert(Private2FE);
641 EXPECT_THAT(PI.getExporters(Private2FE.get(), FM),
642 testing::ElementsAre(llvm::cantFail(FM.getFileRef("public.h"))));
643 }
644
645 TEST_F(PragmaIncludeTest, CanRecordManyTimes) {
646 Inputs.Code = R"cpp(
647 #include "public.h"
648 )cpp";
649 Inputs.ExtraFiles["public.h"] = R"cpp(
650 #include "private.h"
651 )cpp";
652 Inputs.ExtraFiles["private.h"] = R"cpp(
653 // IWYU pragma: private, include "public.h"
654 )cpp";
655
656 TestAST Processed = build();
657 auto &FM = Processed.fileManager();
658 auto PrivateFE = FM.getFile("private.h");
659 llvm::StringRef Public = PI.getPublic(PrivateFE.get());
660 EXPECT_EQ(Public, "\"public.h\"");
661
662 // This build populates same PI during build, but this time we don't have
663 // any IWYU pragmas. Make sure strings from previous recordings are still
664 // alive.
665 Inputs.Code = "";
666 build(/*ResetPragmaIncludes=*/false);
667 EXPECT_EQ(Public, "\"public.h\"");
668 }
669 } // namespace
670 } // namespace clang::include_cleaner