228 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 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/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} // namespace37 38// A function that helps to tell whether a TargetDecl in a UsingDecl will be39// 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 48UnusedUsingDeclsCheck::UnusedUsingDeclsCheck(StringRef Name,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 if55 // 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 than76 // 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 the97 // moment because of false positives caused by ADL and different function98 // 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 only139 // 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 }167 return;168 }169 170 if (const auto *DRE = Result.Nodes.getNodeAs<DeclRefExpr>("used")) {171 RemoveNamedDecl(DRE->getDecl());172 return;173 }174 // Check the uninstantiated template function usage.175 if (const auto *ULE = Result.Nodes.getNodeAs<UnresolvedLookupExpr>("used")) {176 for (const NamedDecl *ND : ULE->decls()) {177 if (const auto *USD = dyn_cast<UsingShadowDecl>(ND))178 removeFromFoundDecls(USD->getTargetDecl()->getCanonicalDecl());179 }180 return;181 }182 // Check user-defined literals183 if (const auto *UDL = Result.Nodes.getNodeAs<UserDefinedLiteral>("used")) {184 const Decl *CalleeDecl = UDL->getCalleeDecl();185 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl)) {186 if (const FunctionTemplateDecl *FPT = FD->getPrimaryTemplate()) {187 removeFromFoundDecls(FPT);188 return;189 }190 }191 removeFromFoundDecls(CalleeDecl);192 }193}194 195void UnusedUsingDeclsCheck::removeFromFoundDecls(const Decl *D) {196 if (!D)197 return;198 const Decl *CanonicalDecl = D->getCanonicalDecl();199 if (!UsingTargetDeclsCache.contains(CanonicalDecl))200 return;201 // FIXME: Currently, we don't handle the using-decls being used in different202 // scopes (such as different namespaces, different functions). Instead of203 // giving an incorrect message, we mark all of them as used.204 for (auto &Context : Contexts) {205 if (Context.IsUsed)206 continue;207 if (Context.UsingTargetDecls.contains(CanonicalDecl))208 Context.IsUsed = true;209 }210}211 212void UnusedUsingDeclsCheck::onEndOfTranslationUnit() {213 for (const auto &Context : Contexts) {214 if (!Context.IsUsed) {215 diag(Context.FoundUsingDecl->getLocation(), "using decl %0 is unused")216 << Context.FoundUsingDecl;217 // Emit a fix and a fix description of the check;218 diag(Context.FoundUsingDecl->getLocation(),219 /*Description=*/"remove the using", DiagnosticIDs::Note)220 << FixItHint::CreateRemoval(Context.UsingDeclRange);221 }222 }223 Contexts.clear();224 UsingTargetDeclsCache.clear();225}226 227} // namespace clang::tidy::misc228