| 1 |
//===--- AnalysisTest.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/Analysis.h" |
| 10 |
#include "AnalysisInternal.h" |
| 11 |
#include "clang-include-cleaner/Record.h" |
| 12 |
#include "clang-include-cleaner/Types.h" |
| 13 |
#include "clang/AST/ASTContext.h" |
| 14 |
#include "clang/Basic/FileManager.h" |
| 15 |
#include "clang/Basic/SourceLocation.h" |
| 16 |
#include "clang/Basic/SourceManager.h" |
| 17 |
#include "clang/Frontend/FrontendActions.h" |
| 18 |
#include "clang/Testing/TestAST.h" |
| 19 |
#include "clang/Tooling/Inclusions/StandardLibrary.h" |
| 20 |
#include "llvm/ADT/ArrayRef.h" |
| 21 |
#include "llvm/ADT/SmallVector.h" |
| 22 |
#include "llvm/Support/ScopedPrinter.h" |
| 23 |
#include "llvm/Testing/Annotations/Annotations.h" |
| 24 |
#include "gmock/gmock.h" |
| 25 |
#include "gtest/gtest.h" |
| 26 |
#include <cstddef> |
| 27 |
|
| 28 |
namespace clang::include_cleaner { |
| 29 |
namespace { |
| 30 |
using testing::AllOf; |
| 31 |
using testing::Contains; |
| 32 |
using testing::ElementsAre; |
| 33 |
using testing::Pair; |
| 34 |
using testing::UnorderedElementsAre; |
| 35 |
|
| 36 |
std::string guard(llvm::StringRef Code) { |
| 37 |
return "#pragma once\n" + Code.str(); |
| 38 |
} |
| 39 |
|
| 40 |
class WalkUsedTest : public testing::Test { |
| 41 |
protected: |
| 42 |
TestInputs Inputs; |
| 43 |
PragmaIncludes PI; |
| 44 |
WalkUsedTest() { |
| 45 |
Inputs.MakeAction = [this] { |
| 46 |
struct Hook : public SyntaxOnlyAction { |
| 47 |
public: |
| 48 |
Hook(PragmaIncludes *Out) : Out(Out) {} |
| 49 |
bool BeginSourceFileAction(clang::CompilerInstance &CI) override { |
| 50 |
Out->record(CI); |
| 51 |
return true; |
| 52 |
} |
| 53 |
|
| 54 |
PragmaIncludes *Out; |
| 55 |
}; |
| 56 |
return std::make_unique<Hook>(&PI); |
| 57 |
}; |
| 58 |
} |
| 59 |
|
| 60 |
llvm::DenseMap<size_t, std::vector<Header>> |
| 61 |
offsetToProviders(TestAST &AST, SourceManager &SM, |
| 62 |
llvm::ArrayRef<SymbolReference> MacroRefs = {}) { |
| 63 |
llvm::SmallVector<Decl *> TopLevelDecls; |
| 64 |
for (Decl *D : AST.context().getTranslationUnitDecl()->decls()) { |
| 65 |
if (!SM.isWrittenInMainFile(SM.getExpansionLoc(D->getLocation()))) |
| 66 |
continue; |
| 67 |
TopLevelDecls.emplace_back(D); |
| 68 |
} |
| 69 |
llvm::DenseMap<size_t, std::vector<Header>> OffsetToProviders; |
| 70 |
walkUsed(TopLevelDecls, MacroRefs, &PI, SM, |
| 71 |
[&](const SymbolReference &Ref, llvm::ArrayRef<Header> Providers) { |
| 72 |
auto [FID, Offset] = SM.getDecomposedLoc(Ref.RefLocation); |
| 73 |
if (FID != SM.getMainFileID()) |
| 74 |
ADD_FAILURE() << "Reference outside of the main file!"; |
| 75 |
OffsetToProviders.try_emplace(Offset, Providers.vec()); |
| 76 |
}); |
| 77 |
return OffsetToProviders; |
| 78 |
} |
| 79 |
}; |
| 80 |
|
| 81 |
TEST_F(WalkUsedTest, Basic) { |
| 82 |
llvm::Annotations Code(R"cpp( |
| 83 |
#include "header.h" |
| 84 |
#include "private.h" |
| 85 |
|
| 86 |
void $bar^bar($private^Private) { |
| 87 |
$foo^foo(); |
| 88 |
std::$vector^vector $vconstructor^v; |
| 89 |
} |
| 90 |
)cpp"); |
| 91 |
Inputs.Code = Code.code(); |
| 92 |
Inputs.ExtraFiles["header.h"] = guard(R"cpp( |
| 93 |
void foo(); |
| 94 |
namespace std { class vector {}; } |
| 95 |
)cpp"); |
| 96 |
Inputs.ExtraFiles["private.h"] = guard(R"cpp( |
| 97 |
// IWYU pragma: private, include "path/public.h" |
| 98 |
class Private {}; |
| 99 |
)cpp"); |
| 100 |
|
| 101 |
TestAST AST(Inputs); |
| 102 |
auto &SM = AST.sourceManager(); |
| 103 |
auto HeaderFile = Header(AST.fileManager().getFile("header.h").get()); |
| 104 |
auto PrivateFile = Header(AST.fileManager().getFile("private.h").get()); |
| 105 |
auto PublicFile = Header("\"path/public.h\""); |
| 106 |
auto MainFile = Header(SM.getFileEntryForID(SM.getMainFileID())); |
| 107 |
auto VectorSTL = Header(*tooling::stdlib::Header::named("<vector>")); |
| 108 |
EXPECT_THAT( |
| 109 |
offsetToProviders(AST, SM), |
| 110 |
UnorderedElementsAre( |
| 111 |
Pair(Code.point("bar"), UnorderedElementsAre(MainFile)), |
| 112 |
Pair(Code.point("private"), |
| 113 |
UnorderedElementsAre(PublicFile, PrivateFile)), |
| 114 |
Pair(Code.point("foo"), UnorderedElementsAre(HeaderFile)), |
| 115 |
Pair(Code.point("vector"), UnorderedElementsAre(VectorSTL)), |
| 116 |
Pair(Code.point("vconstructor"), UnorderedElementsAre(VectorSTL)))); |
| 117 |
} |
| 118 |
|
| 119 |
TEST_F(WalkUsedTest, MultipleProviders) { |
| 120 |
llvm::Annotations Code(R"cpp( |
| 121 |
#include "header1.h" |
| 122 |
#include "header2.h" |
| 123 |
void foo(); |
| 124 |
|
| 125 |
void bar() { |
| 126 |
$foo^foo(); |
| 127 |
} |
| 128 |
)cpp"); |
| 129 |
Inputs.Code = Code.code(); |
| 130 |
Inputs.ExtraFiles["header1.h"] = guard(R"cpp( |
| 131 |
void foo(); |
| 132 |
)cpp"); |
| 133 |
Inputs.ExtraFiles["header2.h"] = guard(R"cpp( |
| 134 |
void foo(); |
| 135 |
)cpp"); |
| 136 |
|
| 137 |
TestAST AST(Inputs); |
| 138 |
auto &SM = AST.sourceManager(); |
| 139 |
auto HeaderFile1 = Header(AST.fileManager().getFile("header1.h").get()); |
| 140 |
auto HeaderFile2 = Header(AST.fileManager().getFile("header2.h").get()); |
| 141 |
auto MainFile = Header(SM.getFileEntryForID(SM.getMainFileID())); |
| 142 |
EXPECT_THAT( |
| 143 |
offsetToProviders(AST, SM), |
| 144 |
Contains(Pair(Code.point("foo"), |
| 145 |
UnorderedElementsAre(HeaderFile1, HeaderFile2, MainFile)))); |
| 146 |
} |
| 147 |
|
| 148 |
TEST_F(WalkUsedTest, MacroRefs) { |
| 149 |
llvm::Annotations Code(R"cpp( |
| 150 |
#include "hdr.h" |
| 151 |
int x = $1^ANSWER; |
| 152 |
int y = $2^ANSWER; |
| 153 |
)cpp"); |
| 154 |
llvm::Annotations Hdr(guard("#define ^ANSWER 42")); |
| 155 |
Inputs.Code = Code.code(); |
| 156 |
Inputs.ExtraFiles["hdr.h"] = Hdr.code(); |
| 157 |
TestAST AST(Inputs); |
| 158 |
auto &SM = AST.sourceManager(); |
| 159 |
const auto *HdrFile = SM.getFileManager().getFile("hdr.h").get(); |
| 160 |
auto HdrID = SM.translateFile(HdrFile); |
| 161 |
|
| 162 |
IdentifierTable Idents; |
| 163 |
Symbol Answer1 = |
| 164 |
Macro{&Idents.get("ANSWER"), SM.getComposedLoc(HdrID, Hdr.point())}; |
| 165 |
Symbol Answer2 = |
| 166 |
Macro{&Idents.get("ANSWER"), SM.getComposedLoc(HdrID, Hdr.point())}; |
| 167 |
EXPECT_THAT( |
| 168 |
offsetToProviders(AST, SM, |
| 169 |
{SymbolReference{SM.getComposedLoc(SM.getMainFileID(), |
| 170 |
Code.point("1")), |
| 171 |
Answer1, RefType::Explicit}, |
| 172 |
SymbolReference{SM.getComposedLoc(SM.getMainFileID(), |
| 173 |
Code.point("2")), |
| 174 |
Answer2, RefType::Explicit}}), |
| 175 |
UnorderedElementsAre( |
| 176 |
Pair(Code.point("1"), UnorderedElementsAre(HdrFile)), |
| 177 |
Pair(Code.point("2"), UnorderedElementsAre(HdrFile)))); |
| 178 |
} |
| 179 |
|
| 180 |
TEST(Analyze, Basic) { |
| 181 |
TestInputs Inputs; |
| 182 |
Inputs.Code = R"cpp( |
| 183 |
#include "a.h" |
| 184 |
#include "b.h" |
| 185 |
#include "keep.h" // IWYU pragma: keep |
| 186 |
|
| 187 |
int x = a + c; |
| 188 |
)cpp"; |
| 189 |
Inputs.ExtraFiles["a.h"] = guard("int a;"); |
| 190 |
Inputs.ExtraFiles["b.h"] = guard(R"cpp( |
| 191 |
#include "c.h" |
| 192 |
int b; |
| 193 |
)cpp"); |
| 194 |
Inputs.ExtraFiles["c.h"] = guard("int c;"); |
| 195 |
Inputs.ExtraFiles["keep.h"] = guard(""); |
| 196 |
|
| 197 |
RecordedPP PP; |
| 198 |
PragmaIncludes PI; |
| 199 |
Inputs.MakeAction = [&PP, &PI] { |
| 200 |
struct Hook : public SyntaxOnlyAction { |
| 201 |
public: |
| 202 |
Hook(RecordedPP &PP, PragmaIncludes &PI) : PP(PP), PI(PI) {} |
| 203 |
bool BeginSourceFileAction(clang::CompilerInstance &CI) override { |
| 204 |
CI.getPreprocessor().addPPCallbacks(PP.record(CI.getPreprocessor())); |
| 205 |
PI.record(CI); |
| 206 |
return true; |
| 207 |
} |
| 208 |
|
| 209 |
RecordedPP &PP; |
| 210 |
PragmaIncludes &PI; |
| 211 |
}; |
| 212 |
return std::make_unique<Hook>(PP, PI); |
| 213 |
}; |
| 214 |
|
| 215 |
TestAST AST(Inputs); |
| 216 |
auto Decls = AST.context().getTranslationUnitDecl()->decls(); |
| 217 |
auto Results = |
| 218 |
analyze(std::vector<Decl *>{Decls.begin(), Decls.end()}, |
| 219 |
PP.MacroReferences, PP.Includes, &PI, AST.sourceManager(), |
| 220 |
AST.preprocessor().getHeaderSearchInfo()); |
| 221 |
|
| 222 |
const Include *B = PP.Includes.atLine(3); |
| 223 |
ASSERT_EQ(B->Spelled, "b.h"); |
| 224 |
EXPECT_THAT(Results.Missing, ElementsAre("\"c.h\"")); |
| 225 |
EXPECT_THAT(Results.Unused, ElementsAre(B)); |
| 226 |
} |
| 227 |
|
| 228 |
TEST(FixIncludes, Basic) { |
| 229 |
llvm::StringRef Code = R"cpp( |
| 230 |
#include "a.h" |
| 231 |
#include "b.h" |
| 232 |
#include <c.h> |
| 233 |
)cpp"; |
| 234 |
|
| 235 |
Includes Inc; |
| 236 |
Include I; |
| 237 |
I.Spelled = "a.h"; |
| 238 |
I.Line = 2; |
| 239 |
Inc.add(I); |
| 240 |
I.Spelled = "b.h"; |
| 241 |
I.Line = 3; |
| 242 |
Inc.add(I); |
| 243 |
I.Spelled = "c.h"; |
| 244 |
I.Line = 4; |
| 245 |
I.Angled = true; |
| 246 |
Inc.add(I); |
| 247 |
|
| 248 |
AnalysisResults Results; |
| 249 |
Results.Missing.push_back("\"aa.h\""); |
| 250 |
Results.Missing.push_back("\"ab.h\""); |
| 251 |
Results.Missing.push_back("<e.h>"); |
| 252 |
Results.Unused.push_back(Inc.atLine(3)); |
| 253 |
Results.Unused.push_back(Inc.atLine(4)); |
| 254 |
|
| 255 |
EXPECT_EQ(fixIncludes(Results, Code, format::getLLVMStyle()), R"cpp( |
| 256 |
#include "a.h" |
| 257 |
#include "aa.h" |
| 258 |
#include "ab.h" |
| 259 |
#include <e.h> |
| 260 |
)cpp"); |
| 261 |
} |
| 262 |
|
| 263 |
MATCHER_P3(expandedAt, FileID, Offset, SM, "") { |
| 264 |
auto [ExpanedFileID, ExpandedOffset] = SM->getDecomposedExpansionLoc(arg); |
| 265 |
return ExpanedFileID == FileID && ExpandedOffset == Offset; |
| 266 |
} |
| 267 |
MATCHER_P3(spelledAt, FileID, Offset, SM, "") { |
| 268 |
auto [SpelledFileID, SpelledOffset] = SM->getDecomposedSpellingLoc(arg); |
| 269 |
return SpelledFileID == FileID && SpelledOffset == Offset; |
| 270 |
} |
| 271 |
TEST(WalkUsed, FilterRefsNotSpelledInMainFile) { |
| 272 |
// Each test is expected to have a single expected ref of `target` symbol |
| 273 |
// (or have none). |
| 274 |
// The location in the reported ref is a macro location. $expand points to |
| 275 |
// the macro location, and $spell points to the spelled location. |
| 276 |
struct { |
| 277 |
llvm::StringRef Header; |
| 278 |
llvm::StringRef Main; |
| 279 |
} TestCases[] = { |
| 280 |
// Tests for decl references. |
| 281 |
{ |
| 282 |
/*Header=*/"int target();", |
| 283 |
R"cpp( |
| 284 |
#define CALL_FUNC $spell^target() |
| 285 |
|
| 286 |
int b = $expand^CALL_FUNC; |
| 287 |
)cpp", |
| 288 |
}, |
| 289 |
{/*Header=*/R"cpp( |
| 290 |
int target(); |
| 291 |
#define CALL_FUNC target() |
| 292 |
)cpp", |
| 293 |
// No ref of `target` being reported, as it is not spelled in main file. |
| 294 |
"int a = CALL_FUNC;"}, |
| 295 |
{ |
| 296 |
/*Header=*/R"cpp( |
| 297 |
int target(); |
| 298 |
#define PLUS_ONE(X) X() + 1 |
| 299 |
)cpp", |
| 300 |
R"cpp( |
| 301 |
int a = $expand^PLUS_ONE($spell^target); |
| 302 |
)cpp", |
| 303 |
}, |
| 304 |
{ |
| 305 |
/*Header=*/R"cpp( |
| 306 |
int target(); |
| 307 |
#define PLUS_ONE(X) X() + 1 |
| 308 |
)cpp", |
| 309 |
R"cpp( |
| 310 |
int a = $expand^PLUS_ONE($spell^target); |
| 311 |
)cpp", |
| 312 |
}, |
| 313 |
// Tests for macro references |
| 314 |
{/*Header=*/"#define target 1", |
| 315 |
R"cpp( |
| 316 |
#define USE_target $spell^target |
| 317 |
int b = $expand^USE_target; |
| 318 |
)cpp"}, |
| 319 |
{/*Header=*/R"cpp( |
| 320 |
#define target 1 |
| 321 |
#define USE_target target |
| 322 |
)cpp", |
| 323 |
// No ref of `target` being reported, it is not spelled in main file. |
| 324 |
R"cpp( |
| 325 |
int a = USE_target; |
| 326 |
)cpp"}, |
| 327 |
}; |
| 328 |
|
| 329 |
for (const auto &T : TestCases) { |
| 330 |
llvm::Annotations Main(T.Main); |
| 331 |
TestInputs Inputs(Main.code()); |
| 332 |
Inputs.ExtraFiles["header.h"] = guard(T.Header); |
| 333 |
RecordedPP Recorded; |
| 334 |
Inputs.MakeAction = [&]() { |
| 335 |
struct RecordAction : public SyntaxOnlyAction { |
| 336 |
RecordedPP &Out; |
| 337 |
RecordAction(RecordedPP &Out) : Out(Out) {} |
| 338 |
bool BeginSourceFileAction(clang::CompilerInstance &CI) override { |
| 339 |
auto &PP = CI.getPreprocessor(); |
| 340 |
PP.addPPCallbacks(Out.record(PP)); |
| 341 |
return true; |
| 342 |
} |
| 343 |
}; |
| 344 |
return std::make_unique<RecordAction>(Recorded); |
| 345 |
}; |
| 346 |
Inputs.ExtraArgs.push_back("-include"); |
| 347 |
Inputs.ExtraArgs.push_back("header.h"); |
| 348 |
TestAST AST(Inputs); |
| 349 |
llvm::SmallVector<Decl *> TopLevelDecls; |
| 350 |
for (Decl *D : AST.context().getTranslationUnitDecl()->decls()) |
| 351 |
TopLevelDecls.emplace_back(D); |
| 352 |
auto &SM = AST.sourceManager(); |
| 353 |
|
| 354 |
SourceLocation RefLoc; |
| 355 |
walkUsed(TopLevelDecls, Recorded.MacroReferences, |
| 356 |
/*PragmaIncludes=*/nullptr, SM, |
| 357 |
[&](const SymbolReference &Ref, llvm::ArrayRef<Header>) { |
| 358 |
if (!Ref.RefLocation.isMacroID()) |
| 359 |
return; |
| 360 |
if (llvm::to_string(Ref.Target) == "target") { |
| 361 |
ASSERT_TRUE(RefLoc.isInvalid()) |
| 362 |
<< "Expected only one 'target' ref loc per testcase"; |
| 363 |
RefLoc = Ref.RefLocation; |
| 364 |
} |
| 365 |
}); |
| 366 |
FileID MainFID = SM.getMainFileID(); |
| 367 |
if (RefLoc.isValid()) { |
| 368 |
EXPECT_THAT(RefLoc, AllOf(expandedAt(MainFID, Main.point("expand"), &SM), |
| 369 |
spelledAt(MainFID, Main.point("spell"), &SM))) |
| 370 |
<< T.Main.str(); |
| 371 |
} else { |
| 372 |
EXPECT_THAT(Main.points(), testing::IsEmpty()); |
| 373 |
} |
| 374 |
} |
| 375 |
} |
| 376 |
|
| 377 |
TEST(Hints, Ordering) { |
| 378 |
struct Tag {}; |
| 379 |
auto Hinted = [](Hints Hints) { |
| 380 |
return clang::include_cleaner::Hinted<Tag>({}, Hints); |
| 381 |
}; |
| 382 |
EXPECT_LT(Hinted(Hints::None), Hinted(Hints::CompleteSymbol)); |
| 383 |
EXPECT_LT(Hinted(Hints::CompleteSymbol), Hinted(Hints::PublicHeader)); |
| 384 |
EXPECT_LT(Hinted(Hints::PublicHeader), Hinted(Hints::PreferredHeader)); |
| 385 |
EXPECT_LT(Hinted(Hints::CompleteSymbol | Hints::PublicHeader), |
| 386 |
Hinted(Hints::PreferredHeader)); |
| 387 |
} |
| 388 |
|
| 389 |
} // namespace |
| 390 |
} // namespace clang::include_cleaner |