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