File: RecordTest.cpp

package info (click to toggle)
llvm-toolchain-20 1%3A20.1.8-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 2,111,388 kB
  • sloc: cpp: 7,438,767; ansic: 1,393,871; asm: 1,012,926; python: 241,728; f90: 86,635; objc: 75,411; lisp: 42,144; pascal: 17,286; sh: 10,027; ml: 5,082; perl: 4,730; awk: 3,523; makefile: 3,349; javascript: 2,251; xml: 892; fortran: 672
file content (692 lines) | stat: -rw-r--r-- 21,472 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//===-- RecordTest.cpp ----------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "clang-include-cleaner/Record.h"
#include "clang-include-cleaner/Types.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileEntry.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Serialization/PCHContainerOperations.h"
#include "clang/Testing/TestAST.h"
#include "clang/Tooling/Inclusions/StandardLibrary.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Testing/Annotations/Annotations.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <cassert>
#include <memory>
#include <optional>
#include <utility>

namespace clang::include_cleaner {
namespace {
using testing::ElementsAreArray;
using testing::IsEmpty;

// Matches a Decl* if it is a NamedDecl with the given name.
MATCHER_P(named, N, "") {
  if (const NamedDecl *ND = llvm::dyn_cast<NamedDecl>(arg)) {
    if (N == ND->getNameAsString())
      return true;
  }
  std::string S;
  llvm::raw_string_ostream OS(S);
  arg->dump(OS);
  *result_listener << S;
  return false;
}

MATCHER_P(FileNamed, N, "") {
  llvm::StringRef ActualName =
      llvm::sys::path::remove_leading_dotslash(arg.getName());
  if (ActualName == N)
    return true;
  *result_listener << ActualName.str();
  return false;
}

class RecordASTTest : public ::testing::Test {
protected:
  TestInputs Inputs;
  RecordedAST Recorded;

  RecordASTTest() {
    struct RecordAction : public ASTFrontendAction {
      RecordedAST &Out;
      RecordAction(RecordedAST &Out) : Out(Out) {}
      std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
                                                     StringRef) override {
        return Out.record();
      }
    };
    Inputs.MakeAction = [this] {
      return std::make_unique<RecordAction>(Recorded);
    };
  }

  TestAST build() { return TestAST(Inputs); }
};

// Top-level decl from the main file is a root, nested ones aren't.
TEST_F(RecordASTTest, Namespace) {
  Inputs.Code =
      R"cpp(
      namespace ns {
        int x;
        namespace {
          int y;
        }
      }
    )cpp";
  auto AST = build();
  EXPECT_THAT(Recorded.Roots, testing::ElementsAre(named("ns")));
}

// Decl in included file is not a root.
TEST_F(RecordASTTest, Inclusion) {
  Inputs.ExtraFiles["header.h"] = "void headerFunc();";
  Inputs.Code = R"cpp(
    #include "header.h"
    void mainFunc();
  )cpp";
  auto AST = build();
  EXPECT_THAT(Recorded.Roots, testing::ElementsAre(named("mainFunc")));
}

// Decl from macro expanded into the main file is a root.
TEST_F(RecordASTTest, Macros) {
  Inputs.ExtraFiles["header.h"] = "#define X void x();";
  Inputs.Code = R"cpp(
    #include "header.h"
    X
  )cpp";
  auto AST = build();
  EXPECT_THAT(Recorded.Roots, testing::ElementsAre(named("x")));
}

// Decl from template instantiation is filtered out from roots.
TEST_F(RecordASTTest, ImplicitTemplates) {
  Inputs.ExtraFiles["dispatch.h"] = R"cpp(
  struct A {
    static constexpr int value = 1;
  };
  template <class Getter>
  int dispatch() {
    return Getter::template get<A>();
  }
  )cpp";
  Inputs.Code = R"cpp(
  #include "dispatch.h"  
  struct MyGetter {
    template <class T> static int get() { return T::value; }
  };
  int v = dispatch<MyGetter>();
  )cpp";
  auto AST = build();
  EXPECT_THAT(Recorded.Roots,
              testing::ElementsAre(named("MyGetter"), named("v")));
}

class RecordPPTest : public ::testing::Test {
protected:
  TestInputs Inputs;
  RecordedPP Recorded;

  RecordPPTest() {
    struct RecordAction : public PreprocessOnlyAction {
      RecordedPP &Out;
      RecordAction(RecordedPP &Out) : Out(Out) {}

      void ExecuteAction() override {
        auto &PP = getCompilerInstance().getPreprocessor();
        PP.addPPCallbacks(Out.record(PP));
        PreprocessOnlyAction::ExecuteAction();
      }
    };
    Inputs.MakeAction = [this] {
      return std::make_unique<RecordAction>(Recorded);
    };
  }

  TestAST build() { return TestAST(Inputs); }
};

// Matches an Include with a particular spelling.
MATCHER_P(spelled, S, "") { return arg.Spelled == S; }

TEST_F(RecordPPTest, CapturesIncludes) {
  llvm::Annotations MainFile(R"cpp(
    $H^#include "./header.h"
    $M^#include <missing.h>
  )cpp");
  Inputs.Code = MainFile.code();
  Inputs.ExtraFiles["header.h"] = "";
  Inputs.ErrorOK = true; // missing header
  auto AST = build();

  ASSERT_THAT(
      Recorded.Includes.all(),
      testing::ElementsAre(spelled("./header.h"), spelled("missing.h")));

  auto &H = Recorded.Includes.all().front();
  EXPECT_EQ(H.Line, 2u);
  EXPECT_EQ(H.HashLocation,
            AST.sourceManager().getComposedLoc(
                AST.sourceManager().getMainFileID(), MainFile.point("H")));
  EXPECT_EQ(H.Resolved, *AST.fileManager().getOptionalFileRef("header.h"));
  EXPECT_FALSE(H.Angled);

  auto &M = Recorded.Includes.all().back();
  EXPECT_EQ(M.Line, 3u);
  EXPECT_EQ(M.HashLocation,
            AST.sourceManager().getComposedLoc(
                AST.sourceManager().getMainFileID(), MainFile.point("M")));
  EXPECT_EQ(M.Resolved, std::nullopt);
  EXPECT_TRUE(M.Angled);
}

TEST_F(RecordPPTest, CapturesMacroRefs) {
  llvm::Annotations Header(R"cpp(
    #define $def^X 1

    // Refs, but not in main file.
    #define Y X
    int one = X;
  )cpp");
  llvm::Annotations MainFile(R"cpp(
    #define EARLY X // not a ref, no definition
    #include "header.h"
    #define LATE ^X
    #define LATE2 ^X // a ref even if not expanded

    int uno = ^X;
    int jeden = $exp^LATE; // a ref in LATE's expansion

    #define IDENT(X) X // not a ref, shadowed
    int eins = IDENT(^X);

    #undef ^X
    // Not refs, rather a new macro with the same name.
    #define X 2
    int two = X;
  )cpp");
  Inputs.Code = MainFile.code();
  Inputs.ExtraFiles["header.h"] = Header.code();
  auto AST = build();
  const auto &SM = AST.sourceManager();

  SourceLocation Def = SM.getComposedLoc(
      SM.translateFile(*AST.fileManager().getOptionalFileRef("header.h")),
      Header.point("def"));
  ASSERT_THAT(Recorded.MacroReferences, Not(IsEmpty()));
  Symbol OrigX = Recorded.MacroReferences.front().Target;
  EXPECT_EQ("X", OrigX.macro().Name->getName());
  EXPECT_EQ(Def, OrigX.macro().Definition);

  std::vector<unsigned> RefOffsets;
  std::vector<unsigned> ExpOffsets; // Expansion locs of refs in macro locs.
  for (const auto &Ref : Recorded.MacroReferences) {
    if (Ref.Target == OrigX) {
      auto [FID, Off] = SM.getDecomposedLoc(Ref.RefLocation);
      if (FID == SM.getMainFileID()) {
        RefOffsets.push_back(Off);
      } else if (Ref.RefLocation.isMacroID() &&
                 SM.isWrittenInMainFile(SM.getExpansionLoc(Ref.RefLocation))) {
        ExpOffsets.push_back(
            SM.getDecomposedExpansionLoc(Ref.RefLocation).second);
      } else {
        ADD_FAILURE() << Ref.RefLocation.printToString(SM);
      }
    }
  }
  EXPECT_THAT(RefOffsets, ElementsAreArray(MainFile.points()));
  EXPECT_THAT(ExpOffsets, ElementsAreArray(MainFile.points("exp")));
}

TEST_F(RecordPPTest, CapturesConditionalMacroRefs) {
  llvm::Annotations MainFile(R"cpp(
    #define X 1

    #ifdef ^X
    #endif

    #if defined(^X)
    #endif

    #ifndef ^X
    #endif

    #ifdef Y
    #elifdef ^X
    #endif

    #ifndef ^X
    #elifndef ^X
    #endif
  )cpp");

  Inputs.Code = MainFile.code();
  Inputs.ExtraArgs.push_back("-std=c++2b");
  auto AST = build();

  std::vector<unsigned> RefOffsets;
  SourceManager &SM = AST.sourceManager();
  for (const auto &Ref : Recorded.MacroReferences) {
    auto [FID, Off] = SM.getDecomposedLoc(Ref.RefLocation);
    ASSERT_EQ(FID, SM.getMainFileID());
    EXPECT_EQ(Ref.RT, RefType::Ambiguous);
    EXPECT_EQ("X", Ref.Target.macro().Name->getName());
    RefOffsets.push_back(Off);
  }
  EXPECT_THAT(RefOffsets, ElementsAreArray(MainFile.points()));
}

class PragmaIncludeTest : public ::testing::Test {
protected:
  // We don't build an AST, we just run a preprocessor action!
  TestInputs Inputs;
  PragmaIncludes PI;

  PragmaIncludeTest() {
    Inputs.MakeAction = [this] {
      struct Hook : public PreprocessOnlyAction {
      public:
        Hook(PragmaIncludes *Out) : Out(Out) {}
        bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
          Out->record(CI);
          return true;
        }
        PragmaIncludes *Out;
      };
      return std::make_unique<Hook>(&PI);
    };
  }

  TestAST build(bool ResetPragmaIncludes = true) {
    if (ResetPragmaIncludes)
      PI = PragmaIncludes();
    return TestAST(Inputs);
  }

  void createEmptyFiles(llvm::ArrayRef<StringRef> FileNames) {
    for (llvm::StringRef File : FileNames)
      Inputs.ExtraFiles[File] = "#pragma once";
  }
};

TEST_F(PragmaIncludeTest, IWYUKeep) {
  Inputs.Code = R"cpp(
    #include "keep1.h" // IWYU pragma: keep
    #include "keep2.h" /* IWYU pragma: keep */

    #include "export1.h" // IWYU pragma: export
    // IWYU pragma: begin_exports
    #include "export2.h"
    #include "export3.h"
    // IWYU pragma: end_exports

    #include "normal.h"

    // IWYU pragma: begin_keep
    #include "keep3.h"
    // IWYU pragma: end_keep

    // IWYU pragma: begin_keep
    #include "keep4.h"
    // IWYU pragma: begin_keep
    #include "keep5.h"
    // IWYU pragma: end_keep
    #include "keep6.h"
    // IWYU pragma: end_keep
    #include <vector>
    #include <map> // IWYU pragma: keep
    #include <set> // IWYU pragma: export
  )cpp";
  createEmptyFiles({"keep1.h", "keep2.h", "keep3.h", "keep4.h", "keep5.h",
                    "keep6.h", "export1.h", "export2.h", "export3.h",
                    "normal.h", "std/vector", "std/map", "std/set"});

  Inputs.ExtraArgs.push_back("-isystemstd");
  TestAST Processed = build();
  auto &FM = Processed.fileManager();

  EXPECT_FALSE(PI.shouldKeep(*FM.getOptionalFileRef("normal.h")));
  EXPECT_FALSE(PI.shouldKeep(*FM.getOptionalFileRef("std/vector")));

  // Keep
  EXPECT_TRUE(PI.shouldKeep(*FM.getOptionalFileRef("keep1.h")));
  EXPECT_TRUE(PI.shouldKeep(*FM.getOptionalFileRef("keep2.h")));
  EXPECT_TRUE(PI.shouldKeep(*FM.getOptionalFileRef("keep3.h")));
  EXPECT_TRUE(PI.shouldKeep(*FM.getOptionalFileRef("keep4.h")));
  EXPECT_TRUE(PI.shouldKeep(*FM.getOptionalFileRef("keep5.h")));
  EXPECT_TRUE(PI.shouldKeep(*FM.getOptionalFileRef("keep6.h")));
  EXPECT_TRUE(PI.shouldKeep(*FM.getOptionalFileRef("std/map")));

  // Exports
  EXPECT_TRUE(PI.shouldKeep(*FM.getOptionalFileRef("export1.h")));
  EXPECT_TRUE(PI.shouldKeep(*FM.getOptionalFileRef("export2.h")));
  EXPECT_TRUE(PI.shouldKeep(*FM.getOptionalFileRef("export3.h")));
  EXPECT_TRUE(PI.shouldKeep(*FM.getOptionalFileRef("std/set")));
}

TEST_F(PragmaIncludeTest, AssociatedHeader) {
  createEmptyFiles({"foo/main.h", "bar/main.h", "bar/other.h", "std/vector"});
  auto IsKeep = [&](llvm::StringRef Name, TestAST &AST) {
    return PI.shouldKeep(*AST.fileManager().getOptionalFileRef(Name));
  };

  Inputs.FileName = "main.cc";
  Inputs.ExtraArgs.push_back("-isystemstd");
  {
    Inputs.Code = R"cpp(
      #include "foo/main.h"
      #include "bar/main.h"
    )cpp";
    auto AST = build();
    EXPECT_TRUE(IsKeep("foo/main.h", AST));
    EXPECT_FALSE(IsKeep("bar/main.h", AST)) << "not first include";
  }

  {
    Inputs.Code = R"cpp(
      #include "bar/other.h"
      #include "bar/main.h"
    )cpp";
    auto AST = build();
    EXPECT_FALSE(IsKeep("bar/other.h", AST));
    EXPECT_FALSE(IsKeep("bar/main.h", AST)) << "not first include";
  }

  {
    Inputs.Code = R"cpp(
      #include "foo/main.h"
      #include "bar/other.h" // IWYU pragma: associated
      #include <vector> // IWYU pragma: associated
    )cpp";
    auto AST = build();
    EXPECT_TRUE(IsKeep("foo/main.h", AST));
    EXPECT_TRUE(IsKeep("bar/other.h", AST));
    EXPECT_TRUE(IsKeep("std/vector", AST));
  }

  Inputs.FileName = "vector.cc";
  {
    Inputs.Code = R"cpp(
      #include <vector>
    )cpp";
    auto AST = build();
    EXPECT_FALSE(IsKeep("std/vector", AST)) << "stdlib is not associated";
  }
}

TEST_F(PragmaIncludeTest, IWYUPrivate) {
  Inputs.Code = R"cpp(
    #include "public.h"
  )cpp";
  Inputs.ExtraFiles["public.h"] = R"cpp(
    #include "private.h"
    #include "private2.h"
  )cpp";
  Inputs.ExtraFiles["private.h"] = R"cpp(
    // IWYU pragma: private, include "public2.h"
  )cpp";
  Inputs.ExtraFiles["private2.h"] = R"cpp(
    // IWYU pragma: private
  )cpp";
  TestAST Processed = build();
  auto PrivateFE = Processed.fileManager().getOptionalFileRef("private.h");
  assert(PrivateFE);
  EXPECT_TRUE(PI.isPrivate(*PrivateFE));
  EXPECT_EQ(PI.getPublic(*PrivateFE), "\"public2.h\"");

  auto PublicFE = Processed.fileManager().getOptionalFileRef("public.h");
  assert(PublicFE);
  EXPECT_EQ(PI.getPublic(*PublicFE), ""); // no mapping.
  EXPECT_FALSE(PI.isPrivate(*PublicFE));

  auto Private2FE = Processed.fileManager().getOptionalFileRef("private2.h");
  assert(Private2FE);
  EXPECT_TRUE(PI.isPrivate(*Private2FE));
}

TEST_F(PragmaIncludeTest, IWYUExport) {
  Inputs.Code = R"cpp(// Line 1
    #include "export1.h"
    #include "export2.h"
  )cpp";
  Inputs.ExtraFiles["export1.h"] = R"cpp(
    #include "private.h" // IWYU pragma: export
  )cpp";
  Inputs.ExtraFiles["export2.h"] = R"cpp(
    #include "export3.h"
  )cpp";
  Inputs.ExtraFiles["export3.h"] = R"cpp(
    #include "private.h" // IWYU pragma: export
  )cpp";
  Inputs.ExtraFiles["private.h"] = "";
  TestAST Processed = build();
  const auto &SM = Processed.sourceManager();
  auto &FM = Processed.fileManager();

  EXPECT_THAT(PI.getExporters(*FM.getOptionalFileRef("private.h"), FM),
              testing::UnorderedElementsAre(FileNamed("export1.h"),
                                            FileNamed("export3.h")));

  EXPECT_TRUE(PI.getExporters(*FM.getOptionalFileRef("export1.h"), FM).empty());
  EXPECT_TRUE(PI.getExporters(*FM.getOptionalFileRef("export2.h"), FM).empty());
  EXPECT_TRUE(PI.getExporters(*FM.getOptionalFileRef("export3.h"), FM).empty());
  EXPECT_TRUE(
      PI.getExporters(SM.getFileEntryForID(SM.getMainFileID()), FM).empty());
}

TEST_F(PragmaIncludeTest, IWYUExportForStandardHeaders) {
  Inputs.Code = R"cpp(
    #include "export.h"
  )cpp";
  Inputs.ExtraFiles["export.h"] = R"cpp(
    #include <string> // IWYU pragma: export
  )cpp";
  Inputs.ExtraFiles["string"] = "";
  Inputs.ExtraArgs = {"-isystem."};
  TestAST Processed = build();
  auto &FM = Processed.fileManager();
  EXPECT_THAT(PI.getExporters(*tooling::stdlib::Header::named("<string>"), FM),
              testing::UnorderedElementsAre(FileNamed("export.h")));
  EXPECT_THAT(PI.getExporters(llvm::cantFail(FM.getFileRef("string")), FM),
              testing::UnorderedElementsAre(FileNamed("export.h")));
}

TEST_F(PragmaIncludeTest, IWYUExportBlock) {
  Inputs.Code = R"cpp(// Line 1
   #include "normal.h"
  )cpp";
  Inputs.ExtraFiles["normal.h"] = R"cpp(
    #include "foo.h"

    // IWYU pragma: begin_exports
    #include "export1.h"
    #include "private1.h"
    // IWYU pragma: end_exports
  )cpp";
  Inputs.ExtraFiles["export1.h"] = R"cpp(
    // IWYU pragma: begin_exports
    #include "private1.h"
    #include "private2.h"
    // IWYU pragma: end_exports

    #include "bar.h"
    #include "private3.h" // IWYU pragma: export
  )cpp";
  createEmptyFiles(
      {"private1.h", "private2.h", "private3.h", "foo.h", "bar.h"});
  TestAST Processed = build();
  auto &FM = Processed.fileManager();

  auto GetNames = [](llvm::ArrayRef<FileEntryRef> FEs) {
    std::string Result;
    llvm::raw_string_ostream OS(Result);
    for (auto &FE : FEs) {
      OS << FE.getName() << " ";
    }
    return Result;
  };
  auto Exporters = PI.getExporters(*FM.getOptionalFileRef("private1.h"), FM);
  EXPECT_THAT(Exporters, testing::UnorderedElementsAre(FileNamed("export1.h"),
                                                       FileNamed("normal.h")))
      << GetNames(Exporters);

  Exporters = PI.getExporters(*FM.getOptionalFileRef("private2.h"), FM);
  EXPECT_THAT(Exporters, testing::UnorderedElementsAre(FileNamed("export1.h")))
      << GetNames(Exporters);

  Exporters = PI.getExporters(*FM.getOptionalFileRef("private3.h"), FM);
  EXPECT_THAT(Exporters, testing::UnorderedElementsAre(FileNamed("export1.h")))
      << GetNames(Exporters);

  Exporters = PI.getExporters(*FM.getOptionalFileRef("foo.h"), FM);
  EXPECT_TRUE(Exporters.empty()) << GetNames(Exporters);

  Exporters = PI.getExporters(*FM.getOptionalFileRef("bar.h"), FM);
  EXPECT_TRUE(Exporters.empty()) << GetNames(Exporters);
}

TEST_F(PragmaIncludeTest, SelfContained) {
  Inputs.Code = R"cpp(
  #include "guarded.h"

  #include "unguarded.h"
  )cpp";
  Inputs.ExtraFiles["guarded.h"] = R"cpp(
  #pragma once
  )cpp";
  Inputs.ExtraFiles["unguarded.h"] = "";
  TestAST Processed = build();
  auto &FM = Processed.fileManager();
  EXPECT_TRUE(PI.isSelfContained(*FM.getOptionalFileRef("guarded.h")));
  EXPECT_FALSE(PI.isSelfContained(*FM.getOptionalFileRef("unguarded.h")));
}

TEST_F(PragmaIncludeTest, AlwaysKeep) {
  Inputs.Code = R"cpp(
  #include "always_keep.h"
  #include "usual.h"
  )cpp";
  Inputs.ExtraFiles["always_keep.h"] = R"cpp(
  #pragma once
  // IWYU pragma: always_keep
  )cpp";
  Inputs.ExtraFiles["usual.h"] = "#pragma once";
  TestAST Processed = build();
  auto &FM = Processed.fileManager();
  EXPECT_TRUE(PI.shouldKeep(*FM.getOptionalFileRef("always_keep.h")));
  EXPECT_FALSE(PI.shouldKeep(*FM.getOptionalFileRef("usual.h")));
}

TEST_F(PragmaIncludeTest, ExportInUnnamedBuffer) {
  llvm::StringLiteral Filename = "test.cpp";
  auto Code = R"cpp(#include "exporter.h")cpp";
  Inputs.ExtraFiles["exporter.h"] = R"cpp(
  #pragma once
  #include "foo.h" // IWYU pragma: export
  )cpp";
  Inputs.ExtraFiles["foo.h"] = "";

  // Create unnamed memory buffers for all the files.
  auto VFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
  VFS->addFile(Filename, /*ModificationTime=*/0,
               llvm::MemoryBuffer::getMemBufferCopy(Code, /*BufferName=*/""));
  for (const auto &Extra : Inputs.ExtraFiles)
    VFS->addFile(Extra.getKey(), /*ModificationTime=*/0,
                 llvm::MemoryBuffer::getMemBufferCopy(Extra.getValue(),
                                                      /*BufferName=*/""));

  auto Clang = std::make_unique<CompilerInstance>(
      std::make_shared<PCHContainerOperations>());
  Clang->createDiagnostics(*VFS);

  Clang->setInvocation(std::make_unique<CompilerInvocation>());
  ASSERT_TRUE(CompilerInvocation::CreateFromArgs(
      Clang->getInvocation(), {Filename.data()}, Clang->getDiagnostics(),
      "clang"));

  auto *FM = Clang->createFileManager(VFS);
  ASSERT_TRUE(Clang->ExecuteAction(*Inputs.MakeAction()));
  EXPECT_THAT(
      PI.getExporters(llvm::cantFail(FM->getFileRef("foo.h")), *FM),
      testing::ElementsAre(llvm::cantFail(FM->getFileRef("exporter.h"))));
}

TEST_F(PragmaIncludeTest, OutlivesFMAndSM) {
  Inputs.Code = R"cpp(
    #include "public.h"
  )cpp";
  Inputs.ExtraFiles["public.h"] = R"cpp(
    #include "private.h"
    #include "private2.h" // IWYU pragma: export
  )cpp";
  Inputs.ExtraFiles["private.h"] = R"cpp(
    // IWYU pragma: private, include "public.h"
  )cpp";
  Inputs.ExtraFiles["private2.h"] = R"cpp(
    // IWYU pragma: private
  )cpp";
  build(); // Fills up PI, file/source manager used is destroyed afterwards.
  Inputs.MakeAction = nullptr; // Don't populate PI anymore.

  // Now this build gives us a new File&Source Manager.
  TestAST Processed = build(/*ResetPragmaIncludes=*/false);
  auto &FM = Processed.fileManager();
  auto PrivateFE = FM.getOptionalFileRef("private.h");
  assert(PrivateFE);
  EXPECT_EQ(PI.getPublic(*PrivateFE), "\"public.h\"");

  auto Private2FE = FM.getOptionalFileRef("private2.h");
  assert(Private2FE);
  EXPECT_THAT(PI.getExporters(*Private2FE, FM),
              testing::ElementsAre(llvm::cantFail(FM.getFileRef("public.h"))));
}

TEST_F(PragmaIncludeTest, CanRecordManyTimes) {
  Inputs.Code = R"cpp(
    #include "public.h"
  )cpp";
  Inputs.ExtraFiles["public.h"] = R"cpp(
    #include "private.h"
  )cpp";
  Inputs.ExtraFiles["private.h"] = R"cpp(
    // IWYU pragma: private, include "public.h"
  )cpp";

  TestAST Processed = build();
  auto &FM = Processed.fileManager();
  auto PrivateFE = FM.getOptionalFileRef("private.h");
  llvm::StringRef Public = PI.getPublic(*PrivateFE);
  EXPECT_EQ(Public, "\"public.h\"");

  // This build populates same PI during build, but this time we don't have
  // any IWYU pragmas. Make sure strings from previous recordings are still
  // alive.
  Inputs.Code = "";
  build(/*ResetPragmaIncludes=*/false);
  EXPECT_EQ(Public, "\"public.h\"");
}
} // namespace
} // namespace clang::include_cleaner