clang-tools 22.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 UsingDeclContext Context(Using);
103 Context.UsingDeclRange = CharSourceRange::getCharRange(
104 Using->getBeginLoc(),
105 Lexer::findLocationAfterToken(
106 Using->getEndLoc(), tok::semi, *Result.SourceManager, getLangOpts(),
107 /*SkipTrailingWhitespaceAndNewLine=*/true));
108 for (const auto *UsingShadow : Using->shadows()) {
109 const auto *TargetDecl = UsingShadow->getTargetDecl()->getCanonicalDecl();
110 if (shouldCheckDecl(TargetDecl)) {
111 Context.UsingTargetDecls.insert(TargetDecl);
112 UsingTargetDeclsCache.insert(TargetDecl);
113 }
114 }
115 if (!Context.UsingTargetDecls.empty())
116 Contexts.push_back(Context);
117 return;
118 }
119
120 // Mark a corresponding using declaration as used.
121 auto RemoveNamedDecl = [&](const NamedDecl *Used) {
122 removeFromFoundDecls(Used);
123 // Also remove variants of Used.
124 if (const auto *FD = dyn_cast<FunctionDecl>(Used)) {
125 removeFromFoundDecls(FD->getPrimaryTemplate());
126 return;
127 }
128 if (const auto *Specialization =
129 dyn_cast<ClassTemplateSpecializationDecl>(Used)) {
130 removeFromFoundDecls(Specialization->getSpecializedTemplate());
131 return;
132 }
133 if (const auto *ECD = dyn_cast<EnumConstantDecl>(Used)) {
134 if (const auto *ET = ECD->getType()->getAsCanonical<EnumType>())
135 removeFromFoundDecls(ET->getDecl());
136 }
137 };
138 // We rely on the fact that the clang AST is walked in order, usages are only
139 // marked after a corresponding using decl has been found.
140 if (const auto *Used = Result.Nodes.getNodeAs<NamedDecl>("used")) {
141 RemoveNamedDecl(Used);
142 return;
143 }
144
145 if (const auto *UsedShadow =
146 Result.Nodes.getNodeAs<UsingShadowDecl>("usedShadow")) {
147 removeFromFoundDecls(UsedShadow->getTargetDecl());
148 return;
149 }
150
151 if (const auto *Used = Result.Nodes.getNodeAs<TemplateArgument>("used")) {
152 if (Used->getKind() == TemplateArgument::Template) {
153 if (const auto *TD = Used->getAsTemplate().getAsTemplateDecl())
154 removeFromFoundDecls(TD);
155 return;
156 }
157
158 if (Used->getKind() == TemplateArgument::Type) {
159 if (auto *RD = Used->getAsType()->getAsCXXRecordDecl())
160 removeFromFoundDecls(RD);
161 return;
162 }
163
164 if (Used->getKind() == TemplateArgument::Declaration)
165 RemoveNamedDecl(Used->getAsDecl());
166 return;
167 }
168
169 if (const auto *DRE = Result.Nodes.getNodeAs<DeclRefExpr>("used")) {
170 RemoveNamedDecl(DRE->getDecl());
171 return;
172 }
173 // Check the uninstantiated template function usage.
174 if (const auto *ULE = Result.Nodes.getNodeAs<UnresolvedLookupExpr>("used")) {
175 for (const NamedDecl *ND : ULE->decls())
176 if (const auto *USD = dyn_cast<UsingShadowDecl>(ND))
177 removeFromFoundDecls(USD->getTargetDecl()->getCanonicalDecl());
178 return;
179 }
180 // Check user-defined literals
181 if (const auto *UDL = Result.Nodes.getNodeAs<UserDefinedLiteral>("used")) {
182 const Decl *CalleeDecl = UDL->getCalleeDecl();
183 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl)) {
184 if (const FunctionTemplateDecl *FPT = FD->getPrimaryTemplate()) {
185 removeFromFoundDecls(FPT);
186 return;
187 }
188 }
189 removeFromFoundDecls(CalleeDecl);
190 }
191}
192
193void UnusedUsingDeclsCheck::removeFromFoundDecls(const Decl *D) {
194 if (!D)
195 return;
196 const Decl *CanonicalDecl = D->getCanonicalDecl();
197 if (!UsingTargetDeclsCache.contains(CanonicalDecl))
198 return;
199 // FIXME: Currently, we don't handle the using-decls being used in different
200 // scopes (such as different namespaces, different functions). Instead of
201 // giving an incorrect message, we mark all of them as used.
202 for (auto &Context : Contexts) {
203 if (Context.IsUsed)
204 continue;
205 if (Context.UsingTargetDecls.contains(CanonicalDecl))
206 Context.IsUsed = true;
207 }
208}
209
211 for (const auto &Context : Contexts) {
212 if (!Context.IsUsed) {
213 diag(Context.FoundUsingDecl->getLocation(), "using decl %0 is unused")
214 << Context.FoundUsingDecl;
215 // Emit a fix and a fix description of the check;
216 diag(Context.FoundUsingDecl->getLocation(),
217 /*Description=*/"remove the using", DiagnosticIDs::Note)
218 << FixItHint::CreateRemoval(Context.UsingDeclRange);
219 }
220 }
221 Contexts.clear();
222 UsingTargetDeclsCache.clear();
223}
224
225} // 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.