1 //===--- UnusedUsingDeclsCheck.cpp - clang-tidy----------------------------===//
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 "UnusedUsingDeclsCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/Lex/Lexer.h"
13
14 using namespace clang::ast_matchers;
15
16 namespace clang {
17 namespace tidy {
18 namespace misc {
19
20 namespace {
21
AST_MATCHER_P(DeducedTemplateSpecializationType,refsToTemplatedDecl,clang::ast_matchers::internal::Matcher<NamedDecl>,DeclMatcher)22 AST_MATCHER_P(DeducedTemplateSpecializationType, refsToTemplatedDecl,
23 clang::ast_matchers::internal::Matcher<NamedDecl>, DeclMatcher) {
24 if (const auto *TD = Node.getTemplateName().getAsTemplateDecl())
25 return DeclMatcher.matches(*TD, Finder, Builder);
26 return false;
27 }
28
29 } // namespace
30
31 // A function that helps to tell whether a TargetDecl in a UsingDecl will be
32 // checked. Only variable, function, function template, class template, class,
33 // enum declaration and enum constant declaration are considered.
shouldCheckDecl(const Decl * TargetDecl)34 static bool shouldCheckDecl(const Decl *TargetDecl) {
35 return isa<RecordDecl>(TargetDecl) || isa<ClassTemplateDecl>(TargetDecl) ||
36 isa<FunctionDecl>(TargetDecl) || isa<VarDecl>(TargetDecl) ||
37 isa<FunctionTemplateDecl>(TargetDecl) || isa<EnumDecl>(TargetDecl) ||
38 isa<EnumConstantDecl>(TargetDecl);
39 }
40
registerMatchers(MatchFinder * Finder)41 void UnusedUsingDeclsCheck::registerMatchers(MatchFinder *Finder) {
42 Finder->addMatcher(usingDecl(isExpansionInMainFile()).bind("using"), this);
43 auto DeclMatcher = hasDeclaration(namedDecl().bind("used"));
44 Finder->addMatcher(loc(templateSpecializationType(DeclMatcher)), this);
45 Finder->addMatcher(loc(deducedTemplateSpecializationType(
46 refsToTemplatedDecl(namedDecl().bind("used")))),
47 this);
48 Finder->addMatcher(callExpr(callee(unresolvedLookupExpr().bind("used"))),
49 this);
50 Finder->addMatcher(
51 callExpr(hasDeclaration(functionDecl(
52 forEachTemplateArgument(templateArgument().bind("used"))))),
53 this);
54 Finder->addMatcher(loc(templateSpecializationType(forEachTemplateArgument(
55 templateArgument().bind("used")))),
56 this);
57 // Cases where we can identify the UsingShadowDecl directly, rather than
58 // just its target.
59 // FIXME: cover more cases in this way, as the AST supports it.
60 auto ThroughShadowMatcher = throughUsingDecl(namedDecl().bind("usedShadow"));
61 Finder->addMatcher(declRefExpr(ThroughShadowMatcher), this);
62 Finder->addMatcher(loc(usingType(ThroughShadowMatcher)), this);
63 }
64
check(const MatchFinder::MatchResult & Result)65 void UnusedUsingDeclsCheck::check(const MatchFinder::MatchResult &Result) {
66 if (Result.Context->getDiagnostics().hasUncompilableErrorOccurred())
67 return;
68
69 if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
70 // Ignores using-declarations defined in macros.
71 if (Using->getLocation().isMacroID())
72 return;
73
74 // Ignores using-declarations defined in class definition.
75 if (isa<CXXRecordDecl>(Using->getDeclContext()))
76 return;
77
78 // FIXME: We ignore using-decls defined in function definitions at the
79 // moment because of false positives caused by ADL and different function
80 // scopes.
81 if (isa<FunctionDecl>(Using->getDeclContext()))
82 return;
83
84 UsingDeclContext Context(Using);
85 Context.UsingDeclRange = CharSourceRange::getCharRange(
86 Using->getBeginLoc(),
87 Lexer::findLocationAfterToken(
88 Using->getEndLoc(), tok::semi, *Result.SourceManager, getLangOpts(),
89 /*SkipTrailingWhitespaceAndNewLine=*/true));
90 for (const auto *UsingShadow : Using->shadows()) {
91 const auto *TargetDecl = UsingShadow->getTargetDecl()->getCanonicalDecl();
92 if (shouldCheckDecl(TargetDecl))
93 Context.UsingTargetDecls.insert(TargetDecl);
94 }
95 if (!Context.UsingTargetDecls.empty())
96 Contexts.push_back(Context);
97 return;
98 }
99
100 // Mark a corresponding using declaration as used.
101 auto RemoveNamedDecl = [&](const NamedDecl *Used) {
102 removeFromFoundDecls(Used);
103 // Also remove variants of Used.
104 if (const auto *FD = dyn_cast<FunctionDecl>(Used)) {
105 removeFromFoundDecls(FD->getPrimaryTemplate());
106 } else if (const auto *Specialization =
107 dyn_cast<ClassTemplateSpecializationDecl>(Used)) {
108 removeFromFoundDecls(Specialization->getSpecializedTemplate());
109 } else if (const auto *FD = dyn_cast<FunctionDecl>(Used)) {
110 if (const auto *FDT = FD->getPrimaryTemplate())
111 removeFromFoundDecls(FDT);
112 } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(Used)) {
113 if (const auto *ET = ECD->getType()->getAs<EnumType>())
114 removeFromFoundDecls(ET->getDecl());
115 }
116 };
117 // We rely on the fact that the clang AST is walked in order, usages are only
118 // marked after a corresponding using decl has been found.
119 if (const auto *Used = Result.Nodes.getNodeAs<NamedDecl>("used")) {
120 RemoveNamedDecl(Used);
121 return;
122 }
123
124 if (const auto *UsedShadow =
125 Result.Nodes.getNodeAs<UsingShadowDecl>("usedShadow")) {
126 removeFromFoundDecls(UsedShadow->getTargetDecl());
127 return;
128 }
129
130 if (const auto *Used = Result.Nodes.getNodeAs<TemplateArgument>("used")) {
131 if (Used->getKind() == TemplateArgument::Template) {
132 if (const auto *TD = Used->getAsTemplate().getAsTemplateDecl())
133 removeFromFoundDecls(TD);
134 } else if (Used->getKind() == TemplateArgument::Type) {
135 if (auto *RD = Used->getAsType()->getAsCXXRecordDecl())
136 removeFromFoundDecls(RD);
137 } else if (Used->getKind() == TemplateArgument::Declaration) {
138 RemoveNamedDecl(Used->getAsDecl());
139 }
140 return;
141 }
142
143 if (const auto *DRE = Result.Nodes.getNodeAs<DeclRefExpr>("used")) {
144 RemoveNamedDecl(DRE->getDecl());
145 return;
146 }
147 // Check the uninstantiated template function usage.
148 if (const auto *ULE = Result.Nodes.getNodeAs<UnresolvedLookupExpr>("used")) {
149 for (const NamedDecl *ND : ULE->decls()) {
150 if (const auto *USD = dyn_cast<UsingShadowDecl>(ND))
151 removeFromFoundDecls(USD->getTargetDecl()->getCanonicalDecl());
152 }
153 }
154 }
155
removeFromFoundDecls(const Decl * D)156 void UnusedUsingDeclsCheck::removeFromFoundDecls(const Decl *D) {
157 if (!D)
158 return;
159 // FIXME: Currently, we don't handle the using-decls being used in different
160 // scopes (such as different namespaces, different functions). Instead of
161 // giving an incorrect message, we mark all of them as used.
162 //
163 // FIXME: Use a more efficient way to find a matching context.
164 for (auto &Context : Contexts) {
165 if (Context.UsingTargetDecls.contains(D->getCanonicalDecl()))
166 Context.IsUsed = true;
167 }
168 }
169
onEndOfTranslationUnit()170 void UnusedUsingDeclsCheck::onEndOfTranslationUnit() {
171 for (const auto &Context : Contexts) {
172 if (!Context.IsUsed) {
173 diag(Context.FoundUsingDecl->getLocation(), "using decl %0 is unused")
174 << Context.FoundUsingDecl;
175 // Emit a fix and a fix description of the check;
176 diag(Context.FoundUsingDecl->getLocation(),
177 /*Description=*/"remove the using", DiagnosticIDs::Note)
178 << FixItHint::CreateRemoval(Context.UsingDeclRange);
179 }
180 }
181 Contexts.clear();
182 }
183
184 } // namespace misc
185 } // namespace tidy
186 } // namespace clang
187