| 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 | |
| 9 | #include "UnusedUsingDeclsCheck.h" |
| 10 | #include "clang/AST/ASTContext.h" |
| 11 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
| 12 | #include "clang/Lex/Lexer.h" |
| 13 | |
| 14 | using namespace clang::ast_matchers; |
| 15 | |
| 16 | namespace clang::tidy::misc { |
| 17 | |
| 18 | namespace { |
| 19 | |
| 20 | AST_MATCHER_P(DeducedTemplateSpecializationType, refsToTemplatedDecl, |
| 21 | clang::ast_matchers::internal::Matcher<NamedDecl>, DeclMatcher) { |
| 22 | if (const auto *TD = Node.getTemplateName().getAsTemplateDecl()) |
| 23 | return DeclMatcher.matches(*TD, Finder, Builder); |
| 24 | return false; |
| 25 | } |
| 26 | |
| 27 | } // namespace |
| 28 | |
| 29 | // A function that helps to tell whether a TargetDecl in a UsingDecl will be |
| 30 | // checked. Only variable, function, function template, class template, class, |
| 31 | // enum declaration and enum constant declaration are considered. |
| 32 | static bool shouldCheckDecl(const Decl *TargetDecl) { |
| 33 | return isa<RecordDecl>(TargetDecl) || isa<ClassTemplateDecl>(TargetDecl) || |
| 34 | isa<FunctionDecl>(TargetDecl) || isa<VarDecl>(TargetDecl) || |
| 35 | isa<FunctionTemplateDecl>(TargetDecl) || isa<EnumDecl>(TargetDecl) || |
| 36 | isa<EnumConstantDecl>(TargetDecl); |
| 37 | } |
| 38 | |
| 39 | UnusedUsingDeclsCheck::UnusedUsingDeclsCheck(StringRef Name, |
| 40 | ClangTidyContext *Context) |
| 41 | : ClangTidyCheck(Name, Context), |
| 42 | RawStringHeaderFileExtensions(Options.getLocalOrGlobal( |
| 43 | "HeaderFileExtensions", utils::defaultHeaderFileExtensions())) { |
| 44 | if (!utils::parseFileExtensions(RawStringHeaderFileExtensions, |
| 45 | HeaderFileExtensions, |
| 46 | utils::defaultFileExtensionDelimiters())) |
| 47 | this->configurationDiag("Invalid header file extension: '%0'") |
| 48 | << RawStringHeaderFileExtensions; |
| 49 | } |
| 50 | |
| 51 | void UnusedUsingDeclsCheck::registerMatchers(MatchFinder *Finder) { |
| 52 | Finder->addMatcher(usingDecl(isExpansionInMainFile()).bind("using"), this); |
| 53 | auto DeclMatcher = hasDeclaration(namedDecl().bind("used")); |
| 54 | Finder->addMatcher(loc(templateSpecializationType(DeclMatcher)), this); |
| 55 | Finder->addMatcher(loc(deducedTemplateSpecializationType( |
| 56 | refsToTemplatedDecl(namedDecl().bind("used")))), |
| 57 | this); |
| 58 | Finder->addMatcher(callExpr(callee(unresolvedLookupExpr().bind("used"))), |
| 59 | this); |
| 60 | Finder->addMatcher( |
| 61 | callExpr(hasDeclaration(functionDecl( |
| 62 | forEachTemplateArgument(templateArgument().bind("used"))))), |
| 63 | this); |
| 64 | Finder->addMatcher(loc(templateSpecializationType(forEachTemplateArgument( |
| 65 | templateArgument().bind("used")))), |
| 66 | this); |
| 67 | Finder->addMatcher(userDefinedLiteral().bind("used"), this); |
| 68 | // Cases where we can identify the UsingShadowDecl directly, rather than |
| 69 | // just its target. |
| 70 | // FIXME: cover more cases in this way, as the AST supports it. |
| 71 | auto ThroughShadowMatcher = throughUsingDecl(namedDecl().bind("usedShadow")); |
| 72 | Finder->addMatcher(declRefExpr(ThroughShadowMatcher), this); |
| 73 | Finder->addMatcher(loc(usingType(ThroughShadowMatcher)), this); |
| 74 | } |
| 75 | |
| 76 | void UnusedUsingDeclsCheck::check(const MatchFinder::MatchResult &Result) { |
| 77 | if (Result.Context->getDiagnostics().hasUncompilableErrorOccurred()) |
| 78 | return; |
| 79 | // We don't emit warnings on unused-using-decls from headers, so bail out if |
| 80 | // the main file is a header. |
| 81 | if (const auto *MainFile = Result.SourceManager->getFileEntryForID( |
| 82 | Result.SourceManager->getMainFileID()); |
| 83 | utils::isFileExtension(MainFile->getName(), HeaderFileExtensions)) |
| 84 | return; |
| 85 | |
| 86 | if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) { |
| 87 | // Ignores using-declarations defined in macros. |
| 88 | if (Using->getLocation().isMacroID()) |
| 89 | return; |
| 90 | |
| 91 | // Ignores using-declarations defined in class definition. |
| 92 | if (isa<CXXRecordDecl>(Using->getDeclContext())) |
| 93 | return; |
| 94 | |
| 95 | // FIXME: We ignore using-decls defined in function definitions at the |
| 96 | // moment because of false positives caused by ADL and different function |
| 97 | // scopes. |
| 98 | if (isa<FunctionDecl>(Using->getDeclContext())) |
| 99 | return; |
| 100 | |
| 101 | UsingDeclContext Context(Using); |
| 102 | Context.UsingDeclRange = CharSourceRange::getCharRange( |
| 103 | Using->getBeginLoc(), |
| 104 | Lexer::findLocationAfterToken( |
| 105 | Using->getEndLoc(), tok::semi, *Result.SourceManager, getLangOpts(), |
| 106 | /*SkipTrailingWhitespaceAndNewLine=*/true)); |
| 107 | for (const auto *UsingShadow : Using->shadows()) { |
| 108 | const auto *TargetDecl = UsingShadow->getTargetDecl()->getCanonicalDecl(); |
| 109 | if (shouldCheckDecl(TargetDecl)) |
| 110 | Context.UsingTargetDecls.insert(TargetDecl); |
| 111 | } |
| 112 | if (!Context.UsingTargetDecls.empty()) |
| 113 | Contexts.push_back(Context); |
| 114 | return; |
| 115 | } |
| 116 | |
| 117 | // Mark a corresponding using declaration as used. |
| 118 | auto RemoveNamedDecl = [&](const NamedDecl *Used) { |
| 119 | removeFromFoundDecls(Used); |
| 120 | // Also remove variants of Used. |
| 121 | if (const auto *FD = dyn_cast<FunctionDecl>(Used)) { |
| 122 | removeFromFoundDecls(FD->getPrimaryTemplate()); |
| 123 | } else if (const auto *Specialization = |
| 124 | dyn_cast<ClassTemplateSpecializationDecl>(Used)) { |
| 125 | removeFromFoundDecls(Specialization->getSpecializedTemplate()); |
| 126 | } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(Used)) { |
| 127 | if (const auto *ET = ECD->getType()->getAs<EnumType>()) |
| 128 | removeFromFoundDecls(ET->getDecl()); |
| 129 | } |
| 130 | }; |
| 131 | // We rely on the fact that the clang AST is walked in order, usages are only |
| 132 | // marked after a corresponding using decl has been found. |
| 133 | if (const auto *Used = Result.Nodes.getNodeAs<NamedDecl>("used")) { |
| 134 | RemoveNamedDecl(Used); |
| 135 | return; |
| 136 | } |
| 137 | |
| 138 | if (const auto *UsedShadow = |
| 139 | Result.Nodes.getNodeAs<UsingShadowDecl>("usedShadow")) { |
| 140 | removeFromFoundDecls(UsedShadow->getTargetDecl()); |
| 141 | return; |
| 142 | } |
| 143 | |
| 144 | if (const auto *Used = Result.Nodes.getNodeAs<TemplateArgument>("used")) { |
| 145 | if (Used->getKind() == TemplateArgument::Template) { |
| 146 | if (const auto *TD = Used->getAsTemplate().getAsTemplateDecl()) |
| 147 | removeFromFoundDecls(TD); |
| 148 | } else if (Used->getKind() == TemplateArgument::Type) { |
| 149 | if (auto *RD = Used->getAsType()->getAsCXXRecordDecl()) |
| 150 | removeFromFoundDecls(RD); |
| 151 | } else if (Used->getKind() == TemplateArgument::Declaration) { |
| 152 | RemoveNamedDecl(Used->getAsDecl()); |
| 153 | } |
| 154 | return; |
| 155 | } |
| 156 | |
| 157 | if (const auto *DRE = Result.Nodes.getNodeAs<DeclRefExpr>("used")) { |
| 158 | RemoveNamedDecl(DRE->getDecl()); |
| 159 | return; |
| 160 | } |
| 161 | // Check the uninstantiated template function usage. |
| 162 | if (const auto *ULE = Result.Nodes.getNodeAs<UnresolvedLookupExpr>("used")) { |
| 163 | for (const NamedDecl *ND : ULE->decls()) { |
| 164 | if (const auto *USD = dyn_cast<UsingShadowDecl>(ND)) |
| 165 | removeFromFoundDecls(USD->getTargetDecl()->getCanonicalDecl()); |
| 166 | } |
| 167 | return; |
| 168 | } |
| 169 | // Check user-defined literals |
| 170 | if (const auto *UDL = Result.Nodes.getNodeAs<UserDefinedLiteral>("used")) |
| 171 | removeFromFoundDecls(UDL->getCalleeDecl()); |
| 172 | } |
| 173 | |
| 174 | void UnusedUsingDeclsCheck::removeFromFoundDecls(const Decl *D) { |
| 175 | if (!D) |
| 176 | return; |
| 177 | // FIXME: Currently, we don't handle the using-decls being used in different |
| 178 | // scopes (such as different namespaces, different functions). Instead of |
| 179 | // giving an incorrect message, we mark all of them as used. |
| 180 | // |
| 181 | // FIXME: Use a more efficient way to find a matching context. |
| 182 | for (auto &Context : Contexts) { |
| 183 | if (Context.UsingTargetDecls.contains(D->getCanonicalDecl())) |
| 184 | Context.IsUsed = true; |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | void UnusedUsingDeclsCheck::onEndOfTranslationUnit() { |
| 189 | for (const auto &Context : Contexts) { |
| 190 | if (!Context.IsUsed) { |
| 191 | diag(Context.FoundUsingDecl->getLocation(), "using decl %0 is unused") |
| 192 | << Context.FoundUsingDecl; |
| 193 | // Emit a fix and a fix description of the check; |
| 194 | diag(Context.FoundUsingDecl->getLocation(), |
| 195 | /*Description=*/"remove the using", DiagnosticIDs::Note) |
| 196 | << FixItHint::CreateRemoval(Context.UsingDeclRange); |
| 197 | } |
| 198 | } |
| 199 | Contexts.clear(); |
| 200 | } |
| 201 | |
| 202 | } // namespace clang::tidy::misc |