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