clang-tools 24.0.0git
UnusedUsingDeclsCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
11#include "clang/AST/ASTContext.h"
12#include "clang/AST/Decl.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14#include "clang/ASTMatchers/ASTMatchers.h"
15#include "clang/Lex/Lexer.h"
16
17using namespace clang::ast_matchers;
18
19namespace clang::tidy::misc {
20
21namespace {
22
23AST_MATCHER_P(DeducedTemplateSpecializationType, refsToTemplatedDecl,
24 ast_matchers::internal::Matcher<NamedDecl>, DeclMatcher) {
25 if (const auto *TD = Node.getTemplateName().getAsTemplateDecl())
26 return DeclMatcher.matches(*TD, Finder, Builder);
27 return false;
28}
29
30AST_MATCHER_P(Type, asTagDecl, ast_matchers::internal::Matcher<TagDecl>,
31 DeclMatcher) {
32 if (const TagDecl *ND = Node.getAsTagDecl())
33 return DeclMatcher.matches(*ND, Finder, Builder);
34 return false;
35}
36
37} // namespace
38
39// A function that helps to tell whether a TargetDecl in a UsingDecl will be
40// checked. Only variable, function, function template, class template, class,
41// enum declaration and enum constant declaration are considered.
42static bool shouldCheckDecl(const Decl *TargetDecl) {
43 return isa<RecordDecl>(TargetDecl) || isa<ClassTemplateDecl>(TargetDecl) ||
44 isa<FunctionDecl>(TargetDecl) || isa<VarDecl>(TargetDecl) ||
45 isa<FunctionTemplateDecl>(TargetDecl) || isa<EnumDecl>(TargetDecl) ||
46 isa<EnumConstantDecl>(TargetDecl);
47}
48
50 ClangTidyContext *Context)
51 : ClangTidyCheck(Name, Context) {}
52
53void UnusedUsingDeclsCheck::registerMatchers(MatchFinder *Finder) {
54 // We don't emit warnings on unused-using-decls from headers, so bail out if
55 // the main file is a header.
56 if (utils::isFileExtension(getCurrentMainFile(), getHeaderFileExtensions()))
57 return;
58 Finder->addMatcher(usingDecl(isExpansionInMainFile()).bind("using"), this);
59 const auto DeclMatcher = hasDeclaration(namedDecl().bind("used"));
60 Finder->addMatcher(loc(templateSpecializationType(DeclMatcher)), this);
61 Finder->addMatcher(loc(deducedTemplateSpecializationType(
62 refsToTemplatedDecl(namedDecl().bind("used")))),
63 this);
64 Finder->addMatcher(callExpr(callee(unresolvedLookupExpr().bind("used"))),
65 this);
66 Finder->addMatcher(
67 callExpr(hasDeclaration(functionDecl(
68 forEachTemplateArgument(templateArgument().bind("used"))))),
69 this);
70 Finder->addMatcher(loc(templateSpecializationType(forEachTemplateArgument(
71 templateArgument().bind("used")))),
72 this);
73 Finder->addMatcher(userDefinedLiteral().bind("used"), this);
74 Finder->addMatcher(loc(asTagDecl(tagDecl().bind("used"))), this);
75 // Cases where we can identify the UsingShadowDecl directly, rather than
76 // just its target.
77 // FIXME: cover more cases in this way, as the AST supports it.
78 const auto ThroughShadowMatcher =
79 throughUsingDecl(namedDecl().bind("usedShadow"));
80 Finder->addMatcher(declRefExpr(ThroughShadowMatcher), this);
81 Finder->addMatcher(loc(usingType(ThroughShadowMatcher)), this);
82}
83
84void UnusedUsingDeclsCheck::check(const MatchFinder::MatchResult &Result) {
85 if (Result.Context->getDiagnostics().hasUncompilableErrorOccurred())
86 return;
87
88 if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
89 // Ignores using-declarations defined in macros.
90 if (Using->getLocation().isMacroID())
91 return;
92
93 // Ignores using-declarations defined in class definition.
94 if (isa<CXXRecordDecl>(Using->getDeclContext()))
95 return;
96
97 // FIXME: We ignore using-decls defined in function definitions at the
98 // moment because of false positives caused by ADL and different function
99 // scopes.
100 if (isa<FunctionDecl>(Using->getDeclContext()))
101 return;
102
103 // Ignore exported using-decls.
104 if (Using->hasOwningModule() &&
105 Using->getModuleOwnershipKind() <=
106 Decl::ModuleOwnershipKind::VisibleWhenImported)
107 return;
108
109 UsingDeclContext Context(Using);
110 Context.UsingDeclRange = CharSourceRange::getCharRange(
111 Using->getBeginLoc(),
112 Lexer::findLocationAfterToken(
113 Using->getEndLoc(), tok::semi, *Result.SourceManager, getLangOpts(),
114 /*SkipTrailingWhitespaceAndNewLine=*/true));
115 for (const auto *UsingShadow : Using->shadows()) {
116 const auto *TargetDecl = UsingShadow->getTargetDecl()->getCanonicalDecl();
117 if (shouldCheckDecl(TargetDecl)) {
118 Context.UsingTargetDecls.insert(TargetDecl);
119 UsingTargetDeclsCache.insert(TargetDecl);
120 }
121 }
122 if (!Context.UsingTargetDecls.empty())
123 Contexts.push_back(Context);
124 return;
125 }
126
127 // Mark a corresponding using declaration as used.
128 const auto RemoveNamedDecl = [&](const NamedDecl *Used) {
129 removeFromFoundDecls(Used);
130 // Also remove variants of Used.
131 if (const auto *FD = dyn_cast<FunctionDecl>(Used)) {
132 removeFromFoundDecls(FD->getPrimaryTemplate());
133 return;
134 }
135 if (const auto *Specialization =
136 dyn_cast<ClassTemplateSpecializationDecl>(Used)) {
137 removeFromFoundDecls(Specialization->getSpecializedTemplate());
138 return;
139 }
140 if (const auto *ECD = dyn_cast<EnumConstantDecl>(Used)) {
141 if (const auto *ET = ECD->getType()->getAsCanonical<EnumType>())
142 removeFromFoundDecls(ET->getDecl());
143 }
144 };
145 // We rely on the fact that the clang AST is walked in order, usages are only
146 // marked after a corresponding using decl has been found.
147 if (const auto *Used = Result.Nodes.getNodeAs<NamedDecl>("used")) {
148 RemoveNamedDecl(Used);
149 return;
150 }
151
152 if (const auto *UsedShadow =
153 Result.Nodes.getNodeAs<UsingShadowDecl>("usedShadow")) {
154 removeFromFoundDecls(UsedShadow->getTargetDecl());
155 return;
156 }
157
158 if (const auto *Used = Result.Nodes.getNodeAs<TemplateArgument>("used")) {
159 if (Used->getKind() == TemplateArgument::Template) {
160 if (const auto *TD = Used->getAsTemplate().getAsTemplateDecl())
161 removeFromFoundDecls(TD);
162 return;
163 }
164
165 if (Used->getKind() == TemplateArgument::Type) {
166 if (const auto *RD = Used->getAsType()->getAsCXXRecordDecl())
167 removeFromFoundDecls(RD);
168 return;
169 }
170
171 if (Used->getKind() == TemplateArgument::Declaration)
172 RemoveNamedDecl(Used->getAsDecl());
173 return;
174 }
175
176 if (const auto *DRE = Result.Nodes.getNodeAs<DeclRefExpr>("used")) {
177 RemoveNamedDecl(DRE->getDecl());
178 return;
179 }
180 // Check the uninstantiated template function usage.
181 if (const auto *ULE = Result.Nodes.getNodeAs<UnresolvedLookupExpr>("used")) {
182 for (const NamedDecl *ND : ULE->decls())
183 if (const auto *USD = dyn_cast<UsingShadowDecl>(ND))
184 removeFromFoundDecls(USD->getTargetDecl()->getCanonicalDecl());
185 return;
186 }
187 // Check user-defined literals
188 if (const auto *UDL = Result.Nodes.getNodeAs<UserDefinedLiteral>("used")) {
189 const Decl *CalleeDecl = UDL->getCalleeDecl();
190 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl)) {
191 if (const FunctionTemplateDecl *FPT = FD->getPrimaryTemplate()) {
192 removeFromFoundDecls(FPT);
193 return;
194 }
195 }
196 removeFromFoundDecls(CalleeDecl);
197 }
198}
199
200void UnusedUsingDeclsCheck::removeFromFoundDecls(const Decl *D) {
201 if (!D)
202 return;
203 const Decl *CanonicalDecl = D->getCanonicalDecl();
204 if (!UsingTargetDeclsCache.contains(CanonicalDecl))
205 return;
206 // FIXME: Currently, we don't handle the using-decls being used in different
207 // scopes (such as different namespaces, different functions). Instead of
208 // giving an incorrect message, we mark all of them as used.
209 for (auto &Context : Contexts) {
210 if (Context.IsUsed)
211 continue;
212 if (Context.UsingTargetDecls.contains(CanonicalDecl))
213 Context.IsUsed = true;
214 }
215}
216
218 for (const auto &Context : Contexts) {
219 if (!Context.IsUsed) {
220 diag(Context.FoundUsingDecl->getLocation(), "using decl %0 is unused")
221 << Context.FoundUsingDecl;
222 // Emit a fix and a fix description of the check;
223 diag(Context.FoundUsingDecl->getLocation(),
224 /*Description=*/"remove the using", DiagnosticIDs::Note)
225 << FixItHint::CreateRemoval(Context.UsingDeclRange);
226 }
227 }
228 Contexts.clear();
229 UsingTargetDeclsCache.clear();
230}
231
232} // namespace clang::tidy::misc
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
UnusedUsingDeclsCheck(StringRef Name, ClangTidyContext *Context)
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
static bool shouldCheckDecl(const Decl *TargetDecl)
bool isFileExtension(StringRef FileName, const FileExtensionsSet &FileExtensions)
Decides whether a file has one of the specified file extensions.