[TargetVersion] Only enable on RISC-V and AArch64 (#115991)
[llvm-project.git] / clang-tools-extra / clang-tidy / misc / UnusedUsingDeclsCheck.cpp
blob1ff61bae46b1edef7dd16c3c113b70ff1afb70d7
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 //===----------------------------------------------------------------------===//
9 #include "UnusedUsingDeclsCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/AST/Decl.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Lex/Lexer.h"
15 using namespace clang::ast_matchers;
17 namespace clang::tidy::misc {
19 namespace {
21 AST_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;
28 AST_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;
35 } // namespace
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.
40 static 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);
47 UnusedUsingDeclsCheck::UnusedUsingDeclsCheck(StringRef Name,
48 ClangTidyContext *Context)
49 : ClangTidyCheck(Name, Context),
50 HeaderFileExtensions(Context->getHeaderFileExtensions()) {}
52 void 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);
82 void 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;
92 if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
93 // Ignores using-declarations defined in macros.
94 if (Using->getLocation().isMacroID())
95 return;
97 // Ignores using-declarations defined in class definition.
98 if (isa<CXXRecordDecl>(Using->getDeclContext()))
99 return;
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;
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);
120 if (!Context.UsingTargetDecls.empty())
121 Contexts.push_back(Context);
122 return;
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;
133 if (const auto *Specialization =
134 dyn_cast<ClassTemplateSpecializationDecl>(Used)) {
135 removeFromFoundDecls(Specialization->getSpecializedTemplate());
136 return;
138 if (const auto *ECD = dyn_cast<EnumConstantDecl>(Used)) {
139 if (const auto *ET = ECD->getType()->getAs<EnumType>())
140 removeFromFoundDecls(ET->getDecl());
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;
150 if (const auto *UsedShadow =
151 Result.Nodes.getNodeAs<UsingShadowDecl>("usedShadow")) {
152 removeFromFoundDecls(UsedShadow->getTargetDecl());
153 return;
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;
163 if (Used->getKind() == TemplateArgument::Type) {
164 if (auto *RD = Used->getAsType()->getAsCXXRecordDecl())
165 removeFromFoundDecls(RD);
166 return;
169 if (Used->getKind() == TemplateArgument::Declaration) {
170 RemoveNamedDecl(Used->getAsDecl());
172 return;
175 if (const auto *DRE = Result.Nodes.getNodeAs<DeclRefExpr>("used")) {
176 RemoveNamedDecl(DRE->getDecl());
177 return;
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());
185 return;
187 // Check user-defined literals
188 if (const auto *UDL = Result.Nodes.getNodeAs<UserDefinedLiteral>("used"))
189 removeFromFoundDecls(UDL->getCalleeDecl());
192 void 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;
209 void UnusedUsingDeclsCheck::onEndOfTranslationUnit() {
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);
220 Contexts.clear();
221 UsingTargetDeclsCache.clear();
224 } // namespace clang::tidy::misc