File: AnalysisTest.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (487 lines) | stat: -rw-r--r-- 16,203 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
//===--- AnalysisTest.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/Analysis.h"
#include "AnalysisInternal.h"
#include "TypesInternal.h"
#include "clang-include-cleaner/Record.h"
#include "clang-include-cleaner/Types.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Format/Format.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Testing/TestAST.h"
#include "clang/Tooling/Inclusions/StandardLibrary.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/Testing/Annotations/Annotations.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <cstddef>
#include <map>
#include <memory>
#include <string>
#include <vector>

namespace clang::include_cleaner {
namespace {
using testing::AllOf;
using testing::Contains;
using testing::ElementsAre;
using testing::Pair;
using testing::UnorderedElementsAre;

std::string guard(llvm::StringRef Code) {
  return "#pragma once\n" + Code.str();
}

class WalkUsedTest : public testing::Test {
protected:
  TestInputs Inputs;
  PragmaIncludes PI;
  WalkUsedTest() {
    Inputs.MakeAction = [this] {
      struct Hook : public SyntaxOnlyAction {
      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);
    };
  }

  std::multimap<size_t, std::vector<Header>>
  offsetToProviders(TestAST &AST, SourceManager &SM,
                    llvm::ArrayRef<SymbolReference> MacroRefs = {}) {
    llvm::SmallVector<Decl *> TopLevelDecls;
    for (Decl *D : AST.context().getTranslationUnitDecl()->decls()) {
      if (!SM.isWrittenInMainFile(SM.getExpansionLoc(D->getLocation())))
        continue;
      TopLevelDecls.emplace_back(D);
    }
    std::multimap<size_t, std::vector<Header>> OffsetToProviders;
    walkUsed(TopLevelDecls, MacroRefs, &PI, SM,
             [&](const SymbolReference &Ref, llvm::ArrayRef<Header> Providers) {
               auto [FID, Offset] = SM.getDecomposedLoc(Ref.RefLocation);
               if (FID != SM.getMainFileID())
                 ADD_FAILURE() << "Reference outside of the main file!";
               OffsetToProviders.emplace(Offset, Providers.vec());
             });
    return OffsetToProviders;
  }
};

TEST_F(WalkUsedTest, Basic) {
  llvm::Annotations Code(R"cpp(
  #include "header.h"
  #include "private.h"

  // No reference reported for the Parameter "p".
  void $bar^bar($private^Private p) {
    $foo^foo();
    std::$vector^vector $vconstructor^$v^v;
    $builtin^__builtin_popcount(1);
    std::$move^move(3);
  }
  )cpp");
  Inputs.Code = Code.code();
  Inputs.ExtraFiles["header.h"] = guard(R"cpp(
  void foo();
  namespace std { class vector {}; int&& move(int&&); }
  )cpp");
  Inputs.ExtraFiles["private.h"] = guard(R"cpp(
    // IWYU pragma: private, include "path/public.h"
    class Private {};
  )cpp");

  TestAST AST(Inputs);
  auto &SM = AST.sourceManager();
  auto HeaderFile = Header(AST.fileManager().getFile("header.h").get());
  auto PrivateFile = Header(AST.fileManager().getFile("private.h").get());
  auto PublicFile = Header("\"path/public.h\"");
  auto MainFile = Header(SM.getFileEntryForID(SM.getMainFileID()));
  auto VectorSTL = Header(*tooling::stdlib::Header::named("<vector>"));
  auto UtilitySTL = Header(*tooling::stdlib::Header::named("<utility>"));
  EXPECT_THAT(
      offsetToProviders(AST, SM),
      UnorderedElementsAre(
          Pair(Code.point("bar"), UnorderedElementsAre(MainFile)),
          Pair(Code.point("private"),
               UnorderedElementsAre(PublicFile, PrivateFile)),
          Pair(Code.point("foo"), UnorderedElementsAre(HeaderFile)),
          Pair(Code.point("vector"), UnorderedElementsAre(VectorSTL)),
          Pair(Code.point("vconstructor"), UnorderedElementsAre(VectorSTL)),
          Pair(Code.point("v"), UnorderedElementsAre(MainFile)),
          Pair(Code.point("builtin"), testing::IsEmpty()),
          Pair(Code.point("move"), UnorderedElementsAre(UtilitySTL))));
}

TEST_F(WalkUsedTest, MultipleProviders) {
  llvm::Annotations Code(R"cpp(
  #include "header1.h"
  #include "header2.h"
  void foo();

  void bar() {
    $foo^foo();
  }
  )cpp");
  Inputs.Code = Code.code();
  Inputs.ExtraFiles["header1.h"] = guard(R"cpp(
  void foo();
  )cpp");
  Inputs.ExtraFiles["header2.h"] = guard(R"cpp(
  void foo();
  )cpp");

  TestAST AST(Inputs);
  auto &SM = AST.sourceManager();
  auto HeaderFile1 = Header(AST.fileManager().getFile("header1.h").get());
  auto HeaderFile2 = Header(AST.fileManager().getFile("header2.h").get());
  auto MainFile = Header(SM.getFileEntryForID(SM.getMainFileID()));
  EXPECT_THAT(
      offsetToProviders(AST, SM),
      Contains(Pair(Code.point("foo"),
                    UnorderedElementsAre(HeaderFile1, HeaderFile2, MainFile))));
}

TEST_F(WalkUsedTest, MacroRefs) {
  llvm::Annotations Code(R"cpp(
    #include "hdr.h"
    int $3^x = $1^ANSWER;
    int $4^y = $2^ANSWER;
  )cpp");
  llvm::Annotations Hdr(guard("#define ^ANSWER 42"));
  Inputs.Code = Code.code();
  Inputs.ExtraFiles["hdr.h"] = Hdr.code();
  TestAST AST(Inputs);
  auto &SM = AST.sourceManager();
  const auto *HdrFile = SM.getFileManager().getFile("hdr.h").get();
  auto MainFile = Header(SM.getFileEntryForID(SM.getMainFileID()));

  auto HdrID = SM.translateFile(HdrFile);

  IdentifierTable Idents;
  Symbol Answer1 =
      Macro{&Idents.get("ANSWER"), SM.getComposedLoc(HdrID, Hdr.point())};
  Symbol Answer2 =
      Macro{&Idents.get("ANSWER"), SM.getComposedLoc(HdrID, Hdr.point())};
  EXPECT_THAT(
      offsetToProviders(
          AST, SM,
          {SymbolReference{
               Answer1, SM.getComposedLoc(SM.getMainFileID(), Code.point("1")),
               RefType::Explicit},
           SymbolReference{
               Answer2, SM.getComposedLoc(SM.getMainFileID(), Code.point("2")),
               RefType::Explicit}}),
      UnorderedElementsAre(
          Pair(Code.point("1"), UnorderedElementsAre(HdrFile)),
          Pair(Code.point("2"), UnorderedElementsAre(HdrFile)),
          Pair(Code.point("3"), UnorderedElementsAre(MainFile)),
          Pair(Code.point("4"), UnorderedElementsAre(MainFile))));
}

class AnalyzeTest : public testing::Test {
protected:
  TestInputs Inputs;
  PragmaIncludes PI;
  RecordedPP PP;
  AnalyzeTest() {
    Inputs.MakeAction = [this] {
      struct Hook : public SyntaxOnlyAction {
      public:
        Hook(RecordedPP &PP, PragmaIncludes &PI) : PP(PP), PI(PI) {}
        bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
          CI.getPreprocessor().addPPCallbacks(PP.record(CI.getPreprocessor()));
          PI.record(CI);
          return true;
        }

        RecordedPP &PP;
        PragmaIncludes &PI;
      };
      return std::make_unique<Hook>(PP, PI);
    };
  }
};

TEST_F(AnalyzeTest, Basic) {
  Inputs.Code = R"cpp(
#include "a.h"
#include "b.h"
#include "keep.h" // IWYU pragma: keep

int x = a + c;
)cpp";
  Inputs.ExtraFiles["a.h"] = guard("int a;");
  Inputs.ExtraFiles["b.h"] = guard(R"cpp(
    #include "c.h"
    int b;
  )cpp");
  Inputs.ExtraFiles["c.h"] = guard("int c;");
  Inputs.ExtraFiles["keep.h"] = guard("");
  TestAST AST(Inputs);
  auto Decls = AST.context().getTranslationUnitDecl()->decls();
  auto Results =
      analyze(std::vector<Decl *>{Decls.begin(), Decls.end()},
              PP.MacroReferences, PP.Includes, &PI, AST.sourceManager(),
              AST.preprocessor().getHeaderSearchInfo());

  const Include *B = PP.Includes.atLine(3);
  ASSERT_EQ(B->Spelled, "b.h");
  EXPECT_THAT(Results.Missing, ElementsAre("\"c.h\""));
  EXPECT_THAT(Results.Unused, ElementsAre(B));
}

TEST_F(AnalyzeTest, PrivateUsedInPublic) {
  // Check that umbrella header uses private include.
  Inputs.Code = R"cpp(#include "private.h")cpp";
  Inputs.ExtraFiles["private.h"] =
      guard("// IWYU pragma: private, include \"public.h\"");
  Inputs.FileName = "public.h";
  TestAST AST(Inputs);
  EXPECT_FALSE(PP.Includes.all().empty());
  auto Results = analyze({}, {}, PP.Includes, &PI, AST.sourceManager(),
                         AST.preprocessor().getHeaderSearchInfo());
  EXPECT_THAT(Results.Unused, testing::IsEmpty());
}

TEST_F(AnalyzeTest, NoCrashWhenUnresolved) {
  // Check that umbrella header uses private include.
  Inputs.Code = R"cpp(#include "not_found.h")cpp";
  Inputs.ErrorOK = true;
  TestAST AST(Inputs);
  EXPECT_FALSE(PP.Includes.all().empty());
  auto Results = analyze({}, {}, PP.Includes, &PI, AST.sourceManager(),
                         AST.preprocessor().getHeaderSearchInfo());
  EXPECT_THAT(Results.Unused, testing::IsEmpty());
}

TEST(FixIncludes, Basic) {
  llvm::StringRef Code = R"cpp(#include "d.h"
#include "a.h"
#include "b.h"
#include <c.h>
)cpp";

  Includes Inc;
  Include I;
  I.Spelled = "a.h";
  I.Line = 2;
  Inc.add(I);
  I.Spelled = "b.h";
  I.Line = 3;
  Inc.add(I);
  I.Spelled = "c.h";
  I.Line = 4;
  I.Angled = true;
  Inc.add(I);

  AnalysisResults Results;
  Results.Missing.push_back("\"aa.h\"");
  Results.Missing.push_back("\"ab.h\"");
  Results.Missing.push_back("<e.h>");
  Results.Unused.push_back(Inc.atLine(3));
  Results.Unused.push_back(Inc.atLine(4));

  EXPECT_EQ(fixIncludes(Results, "d.cc", Code, format::getLLVMStyle()),
R"cpp(#include "d.h"
#include "a.h"
#include "aa.h"
#include "ab.h"
#include <e.h>
)cpp");

  Results = {};
  Results.Missing.push_back("\"d.h\"");
  Code = R"cpp(#include "a.h")cpp";
  EXPECT_EQ(fixIncludes(Results, "d.cc", Code, format::getLLVMStyle()),
R"cpp(#include "d.h"
#include "a.h")cpp");
}

MATCHER_P3(expandedAt, FileID, Offset, SM, "") {
  auto [ExpanedFileID, ExpandedOffset] = SM->getDecomposedExpansionLoc(arg);
  return ExpanedFileID == FileID && ExpandedOffset == Offset;
}
MATCHER_P3(spelledAt, FileID, Offset, SM, "") {
  auto [SpelledFileID, SpelledOffset] = SM->getDecomposedSpellingLoc(arg);
  return SpelledFileID == FileID && SpelledOffset == Offset;
}
TEST(WalkUsed, FilterRefsNotSpelledInMainFile) {
  // Each test is expected to have a single expected ref of `target` symbol
  // (or have none).
  // The location in the reported ref is a macro location. $expand points to
  // the macro location, and $spell points to the spelled location.
  struct {
    llvm::StringRef Header;
    llvm::StringRef Main;
  } TestCases[] = {
      // Tests for decl references.
      {
          /*Header=*/"int target();",
          R"cpp(
            #define CALL_FUNC $spell^target()

            int b = $expand^CALL_FUNC;
          )cpp",
      },
      {/*Header=*/R"cpp(
           int target();
           #define CALL_FUNC target()
           )cpp",
       // No ref of `target` being reported, as it is not spelled in main file.
       "int a = CALL_FUNC;"},
      {
          /*Header=*/R"cpp(
            int target();
            #define PLUS_ONE(X) X() + 1
          )cpp",
          R"cpp(
            int a = $expand^PLUS_ONE($spell^target);
          )cpp",
      },
      {
          /*Header=*/R"cpp(
            int target();
            #define PLUS_ONE(X) X() + 1
          )cpp",
          R"cpp(
            int a = $expand^PLUS_ONE($spell^target);
          )cpp",
      },
      // Tests for macro references
      {/*Header=*/"#define target 1",
       R"cpp(
          #define USE_target $spell^target
          int b = $expand^USE_target;
        )cpp"},
      {/*Header=*/R"cpp(
          #define target 1
          #define USE_target target
        )cpp",
       // No ref of `target` being reported, it is not spelled in main file.
       R"cpp(
          int a = USE_target;
        )cpp"},
  };

  for (const auto &T : TestCases) {
    llvm::Annotations Main(T.Main);
    TestInputs Inputs(Main.code());
    Inputs.ExtraFiles["header.h"] = guard(T.Header);
    RecordedPP Recorded;
    Inputs.MakeAction = [&]() {
      struct RecordAction : public SyntaxOnlyAction {
        RecordedPP &Out;
        RecordAction(RecordedPP &Out) : Out(Out) {}
        bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
          auto &PP = CI.getPreprocessor();
          PP.addPPCallbacks(Out.record(PP));
          return true;
        }
      };
      return std::make_unique<RecordAction>(Recorded);
    };
    Inputs.ExtraArgs.push_back("-include");
    Inputs.ExtraArgs.push_back("header.h");
    TestAST AST(Inputs);
    llvm::SmallVector<Decl *> TopLevelDecls;
    for (Decl *D : AST.context().getTranslationUnitDecl()->decls())
      TopLevelDecls.emplace_back(D);
    auto &SM = AST.sourceManager();

    SourceLocation RefLoc;
    walkUsed(TopLevelDecls, Recorded.MacroReferences,
             /*PragmaIncludes=*/nullptr, SM,
             [&](const SymbolReference &Ref, llvm::ArrayRef<Header>) {
               if (!Ref.RefLocation.isMacroID())
                 return;
               if (llvm::to_string(Ref.Target) == "target") {
                 ASSERT_TRUE(RefLoc.isInvalid())
                     << "Expected only one 'target' ref loc per testcase";
                 RefLoc = Ref.RefLocation;
               }
             });
    FileID MainFID = SM.getMainFileID();
    if (RefLoc.isValid()) {
      EXPECT_THAT(RefLoc, AllOf(expandedAt(MainFID, Main.point("expand"), &SM),
                                spelledAt(MainFID, Main.point("spell"), &SM)))
          << T.Main.str();
    } else {
      EXPECT_THAT(Main.points(), testing::IsEmpty());
    }
  }
}

struct Tag {
  friend llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Tag &T) {
    return OS << "Anon Tag";
  }
};
TEST(Hints, Ordering) {
  auto Hinted = [](Hints Hints) {
    return clang::include_cleaner::Hinted<Tag>({}, Hints);
  };
  EXPECT_LT(Hinted(Hints::None), Hinted(Hints::CompleteSymbol));
  EXPECT_LT(Hinted(Hints::CompleteSymbol), Hinted(Hints::PublicHeader));
  EXPECT_LT(Hinted(Hints::PublicHeader), Hinted(Hints::PreferredHeader));
  EXPECT_LT(Hinted(Hints::CompleteSymbol | Hints::PublicHeader),
            Hinted(Hints::PreferredHeader));
}

// Test ast traversal & redecl selection end-to-end for templates, as explicit
// instantiations/specializations are not redecls of the primary template. We
// need to make sure we're selecting the right ones.
TEST_F(WalkUsedTest, TemplateDecls) {
  llvm::Annotations Code(R"cpp(
    #include "fwd.h"
    #include "def.h"
    #include "partial.h"
    template <> struct $exp_spec^Foo<char> {};
    template struct $exp^Foo<int>;
    $full^Foo<int> x;
    $implicit^Foo<bool> y;
    $partial^Foo<int*> z;
  )cpp");
  Inputs.Code = Code.code();
  Inputs.ExtraFiles["fwd.h"] = guard("template<typename> struct Foo;");
  Inputs.ExtraFiles["def.h"] = guard("template<typename> struct Foo {};");
  Inputs.ExtraFiles["partial.h"] =
      guard("template<typename T> struct Foo<T*> {};");
  TestAST AST(Inputs);
  auto &SM = AST.sourceManager();
  const auto *Fwd = SM.getFileManager().getFile("fwd.h").get();
  const auto *Def = SM.getFileManager().getFile("def.h").get();
  const auto *Partial = SM.getFileManager().getFile("partial.h").get();

  EXPECT_THAT(
      offsetToProviders(AST, SM),
      AllOf(Contains(
                Pair(Code.point("exp_spec"), UnorderedElementsAre(Fwd, Def))),
            Contains(Pair(Code.point("exp"), UnorderedElementsAre(Fwd, Def))),
            Contains(Pair(Code.point("full"), UnorderedElementsAre(Fwd, Def))),
            Contains(
                Pair(Code.point("implicit"), UnorderedElementsAre(Fwd, Def))),
            Contains(
                Pair(Code.point("partial"), UnorderedElementsAre(Partial)))));
}

} // namespace
} // namespace clang::include_cleaner