Debian Codegraph @

llvm-project/clang-tools-extra/include-cleaner/lib/Analysis.cpp

raw
1 //===--- Analysis.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/AST/Decl.h"
15 #include "clang/AST/DeclBase.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Format/Format.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Tooling/Core/Replacement.h"
20 #include "clang/Tooling/Inclusions/StandardLibrary.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringRef.h"
25
26 namespace clang::include_cleaner {
27
28 void walkUsed(llvm::ArrayRef<Decl *> ASTRoots,
29 llvm::ArrayRef<SymbolReference> MacroRefs,
30 const PragmaIncludes *PI, const SourceManager &SM,
31 UsedSymbolCB CB) {
32 // This is duplicated in writeHTMLReport, changes should be mirrored there.
33 tooling::stdlib::Recognizer Recognizer;
34 for (auto *Root : ASTRoots) {
35 walkAST(*Root, [&](SourceLocation Loc, NamedDecl &ND, RefType RT) {
36 if (!SM.isWrittenInMainFile(SM.getSpellingLoc(Loc)))
37 return;
38 // FIXME: Most of the work done here is repetative. It might be useful to
39 // have a cache/batching.
40 SymbolReference SymRef{Loc, ND, RT};
41 return CB(SymRef, headersForSymbol(ND, SM, PI));
42 });
43 }
44 for (const SymbolReference &MacroRef : MacroRefs) {
45 assert(MacroRef.Target.kind() == Symbol::Macro);
46 if (!SM.isWrittenInMainFile(SM.getSpellingLoc(MacroRef.RefLocation)))
47 continue;
48 CB(MacroRef, headersForSymbol(MacroRef.Target, SM, PI));
49 }
50 }
51
52 static std::string spellHeader(const Header &H, HeaderSearch &HS,
53 const FileEntry *Main) {
54 switch (H.kind()) {
55 case Header::Physical: {
56 bool IsSystem = false;
57 std::string Path = HS.suggestPathToFileForDiagnostics(
58 H.physical(), Main->tryGetRealPathName(), &IsSystem);
59 return IsSystem ? "<" + Path + ">" : "\"" + Path + "\"";
60 }
61 case Header::Standard:
62 return H.standard().name().str();
63 case Header::Verbatim:
64 return H.verbatim().str();
65 }
66 llvm_unreachable("Unknown Header kind");
67 }
68
69 AnalysisResults analyze(llvm::ArrayRef<Decl *> ASTRoots,
70 llvm::ArrayRef<SymbolReference> MacroRefs,
71 const Includes &Inc, const PragmaIncludes *PI,
72 const SourceManager &SM, HeaderSearch &HS) {
73 const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID());
74 llvm::DenseSet<const Include *> Used;
75 llvm::StringSet<> Missing;
76 walkUsed(ASTRoots, MacroRefs, PI, SM,
77 [&](const SymbolReference &Ref, llvm::ArrayRef<Header> Providers) {
78 bool Satisfied = false;
79 for (const Header &H : Providers) {
80 if (H.kind() == Header::Physical && H.physical() == MainFile)
81 Satisfied = true;
82 for (const Include *I : Inc.match(H)) {
83 Used.insert(I);
84 Satisfied = true;
85 }
86 }
87 if (!Satisfied && !Providers.empty() &&
88 Ref.RT == RefType::Explicit)
89 Missing.insert(spellHeader(Providers.front(), HS, MainFile));
90 });
91
92 AnalysisResults Results;
93 for (const Include &I : Inc.all())
94 if (!Used.contains(&I) && PI && !PI->shouldKeep(I.Line))
95 Results.Unused.push_back(&I);
96 for (llvm::StringRef S : Missing.keys())
97 Results.Missing.push_back(S.str());
98 llvm::sort(Results.Missing);
99 return Results;
100 }
101
102 std::string fixIncludes(const AnalysisResults &Results, llvm::StringRef Code,
103 const format::FormatStyle &Style) {
104 assert(Style.isCpp() && "Only C++ style supports include insertions!");
105 tooling::Replacements R;
106 // Encode insertions/deletions in the magic way clang-format understands.
107 for (const Include *I : Results.Unused)
108 cantFail(R.add(tooling::Replacement("input", UINT_MAX, 1, I->quote())));
109 for (llvm::StringRef Spelled : Results.Missing)
110 cantFail(R.add(tooling::Replacement("input", UINT_MAX, 0,
111 ("#include " + Spelled).str())));
112 // "cleanup" actually turns the UINT_MAX replacements into concrete edits.
113 auto Positioned = cantFail(format::cleanupAroundReplacements(Code, R, Style));
114 return cantFail(tooling::applyAllReplacements(Code, Positioned));
115 }
116
117 } // namespace clang::include_cleaner