10#include "clang/AST/ASTContext.h"
11#include "clang/AST/Decl.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Lex/Lexer.h"
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);
30 if (
const TagDecl *ND =
Node.getAsTagDecl())
31 return DeclMatcher.matches(*ND, Finder,
Builder);
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);
50 HeaderFileExtensions(Context->getHeaderFileExtensions()) {}
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")))),
59 Finder->addMatcher(callExpr(callee(unresolvedLookupExpr().bind(
"used"))),
62 callExpr(hasDeclaration(functionDecl(
63 forEachTemplateArgument(templateArgument().bind(
"used"))))),
65 Finder->addMatcher(loc(templateSpecializationType(forEachTemplateArgument(
66 templateArgument().bind(
"used")))),
68 Finder->addMatcher(userDefinedLiteral().bind(
"used"),
this);
70 loc(elaboratedType(unless(hasQualifier(nestedNameSpecifier())),
71 hasUnqualifiedDesugaredType(
72 type(asTagDecl(tagDecl().bind(
"used")))))),
77 auto ThroughShadowMatcher = throughUsingDecl(namedDecl().bind(
"usedShadow"));
78 Finder->addMatcher(declRefExpr(ThroughShadowMatcher),
this);
79 Finder->addMatcher(loc(usingType(ThroughShadowMatcher)),
this);
83 if (Result.Context->getDiagnostics().hasUncompilableErrorOccurred())
87 if (
auto MainFile = Result.SourceManager->getFileEntryRefForID(
88 Result.SourceManager->getMainFileID());
92 if (
const auto *Using = Result.Nodes.getNodeAs<UsingDecl>(
"using")) {
94 if (Using->getLocation().isMacroID())
98 if (isa<CXXRecordDecl>(Using->getDeclContext()))
104 if (isa<FunctionDecl>(Using->getDeclContext()))
107 UsingDeclContext Context(Using);
108 Context.UsingDeclRange = CharSourceRange::getCharRange(
109 Using->getBeginLoc(),
110 Lexer::findLocationAfterToken(
111 Using->getEndLoc(), tok::semi, *Result.SourceManager,
getLangOpts(),
113 for (
const auto *UsingShadow : Using->shadows()) {
114 const auto *TargetDecl = UsingShadow->getTargetDecl()->getCanonicalDecl();
116 Context.UsingTargetDecls.insert(TargetDecl);
117 UsingTargetDeclsCache.insert(TargetDecl);
120 if (!Context.UsingTargetDecls.empty())
121 Contexts.push_back(Context);
126 auto RemoveNamedDecl = [&](
const NamedDecl *Used) {
127 removeFromFoundDecls(Used);
129 if (
const auto *FD = dyn_cast<FunctionDecl>(Used)) {
130 removeFromFoundDecls(FD->getPrimaryTemplate());
133 if (
const auto *Specialization =
134 dyn_cast<ClassTemplateSpecializationDecl>(Used)) {
135 removeFromFoundDecls(Specialization->getSpecializedTemplate());
138 if (
const auto *ECD = dyn_cast<EnumConstantDecl>(Used)) {
139 if (
const auto *ET = ECD->getType()->getAs<EnumType>())
140 removeFromFoundDecls(ET->getDecl());
145 if (
const auto *Used = Result.Nodes.getNodeAs<NamedDecl>(
"used")) {
146 RemoveNamedDecl(Used);
150 if (
const auto *UsedShadow =
151 Result.Nodes.getNodeAs<UsingShadowDecl>(
"usedShadow")) {
152 removeFromFoundDecls(UsedShadow->getTargetDecl());
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);
163 if (Used->getKind() == TemplateArgument::Type) {
164 if (
auto *RD = Used->getAsType()->getAsCXXRecordDecl())
165 removeFromFoundDecls(RD);
169 if (Used->getKind() == TemplateArgument::Declaration) {
170 RemoveNamedDecl(Used->getAsDecl());
175 if (
const auto *DRE = Result.Nodes.getNodeAs<DeclRefExpr>(
"used")) {
176 RemoveNamedDecl(DRE->getDecl());
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());
188 if (
const auto *UDL = Result.Nodes.getNodeAs<UserDefinedLiteral>(
"used"))
189 removeFromFoundDecls(UDL->getCalleeDecl());
192void UnusedUsingDeclsCheck::removeFromFoundDecls(
const Decl *D) {
195 const Decl *CanonicalDecl = D->getCanonicalDecl();
196 if (!UsingTargetDeclsCache.contains(CanonicalDecl))
201 for (
auto &Context : Contexts) {
204 if (Context.UsingTargetDecls.contains(CanonicalDecl))
205 Context.IsUsed =
true;
210 for (
const auto &Context : Contexts) {
211 if (!Context.IsUsed) {
212 diag(Context.FoundUsingDecl->getLocation(),
"using decl %0 is unused")
213 << Context.FoundUsingDecl;
215 diag(Context.FoundUsingDecl->getLocation(),
216 "remove the using", DiagnosticIDs::Note)
217 << FixItHint::CreateRemoval(Context.UsingDeclRange);
221 UsingTargetDeclsCache.clear();
const FunctionDecl * Decl
llvm::SmallString< 256U > Name
CodeCompletionBuilder Builder
::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)
void onEndOfTranslationUnit() override
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.