1 //===--- UnusedUsingDeclsCheck.cpp - clang-tidy----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "UnusedUsingDeclsCheck.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Lex/Lexer.h"
14 
15 using namespace clang::ast_matchers;
16 
17 namespace clang {
18 namespace tidy {
19 namespace misc {
20 
21 // A function that helps to tell whether a TargetDecl in a UsingDecl will be
22 // checked. Only variable, function, function template, class template, class,
23 // enum declaration and enum constant declaration are considered.
24 static bool ShouldCheckDecl(const Decl *TargetDecl) {
25   return isa<RecordDecl>(TargetDecl) || isa<ClassTemplateDecl>(TargetDecl) ||
26          isa<FunctionDecl>(TargetDecl) || isa<VarDecl>(TargetDecl) ||
27          isa<FunctionTemplateDecl>(TargetDecl) || isa<EnumDecl>(TargetDecl) ||
28          isa<EnumConstantDecl>(TargetDecl);
29 }
30 
31 void UnusedUsingDeclsCheck::registerMatchers(MatchFinder *Finder) {
32   Finder->addMatcher(usingDecl(isExpansionInMainFile()).bind("using"), this);
33   auto DeclMatcher = hasDeclaration(namedDecl().bind("used"));
34   Finder->addMatcher(loc(enumType(DeclMatcher)), this);
35   Finder->addMatcher(loc(recordType(DeclMatcher)), this);
36   Finder->addMatcher(loc(templateSpecializationType(DeclMatcher)), this);
37   Finder->addMatcher(declRefExpr().bind("used"), this);
38   Finder->addMatcher(callExpr(callee(unresolvedLookupExpr().bind("used"))),
39                      this);
40   Finder->addMatcher(
41       callExpr(hasDeclaration(functionDecl(hasAnyTemplateArgument(
42           anyOf(refersToTemplate(templateName().bind("used")),
43                 refersToDeclaration(functionDecl().bind("used"))))))),
44       this);
45 }
46 
47 void UnusedUsingDeclsCheck::check(const MatchFinder::MatchResult &Result) {
48   if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
49     // Ignores using-declarations defined in macros.
50     if (Using->getLocation().isMacroID())
51       return;
52 
53     // Ignores using-declarations defined in class definition.
54     if (isa<CXXRecordDecl>(Using->getDeclContext()))
55       return;
56 
57     // FIXME: We ignore using-decls defined in function definitions at the
58     // moment because of false positives caused by ADL and different function
59     // scopes.
60     if (isa<FunctionDecl>(Using->getDeclContext()))
61       return;
62 
63     UsingDeclContext Context(Using);
64     Context.UsingDeclRange = CharSourceRange::getCharRange(
65         Using->getLocStart(),
66         Lexer::findLocationAfterToken(
67             Using->getLocEnd(), tok::semi, *Result.SourceManager,
68             Result.Context->getLangOpts(),
69             /*SkipTrailingWhitespaceAndNewLine=*/true));
70     for (const auto *UsingShadow : Using->shadows()) {
71       const auto *TargetDecl = UsingShadow->getTargetDecl()->getCanonicalDecl();
72       if (ShouldCheckDecl(TargetDecl))
73         Context.UsingTargetDecls.insert(TargetDecl);
74     }
75     if (!Context.UsingTargetDecls.empty())
76       Contexts.push_back(Context);
77     return;
78   }
79   // Mark using declarations as used by setting FoundDecls' value to zero. As
80   // the AST is walked in order, usages are only marked after a the
81   // corresponding using declaration has been found.
82   // FIXME: This currently doesn't look at whether the type reference is
83   // actually found with the help of the using declaration.
84   if (const auto *Used = Result.Nodes.getNodeAs<NamedDecl>("used")) {
85     if (const auto *FD = dyn_cast<FunctionDecl>(Used)) {
86       removeFromFoundDecls(FD->getPrimaryTemplate());
87     } else if (const auto *Specialization =
88                    dyn_cast<ClassTemplateSpecializationDecl>(Used)) {
89       Used = Specialization->getSpecializedTemplate();
90     }
91     removeFromFoundDecls(Used);
92     return;
93   }
94 
95   if (const auto *Used = Result.Nodes.getNodeAs<TemplateName>("used")) {
96     removeFromFoundDecls(Used->getAsTemplateDecl());
97     return;
98   }
99 
100   if (const auto *DRE = Result.Nodes.getNodeAs<DeclRefExpr>("used")) {
101     if (const auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
102       if (const auto *FDT = FD->getPrimaryTemplate())
103         removeFromFoundDecls(FDT);
104       else
105         removeFromFoundDecls(FD);
106     } else if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
107       removeFromFoundDecls(VD);
108     } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
109       removeFromFoundDecls(ECD);
110       if (const auto *ET = ECD->getType()->getAs<EnumType>())
111         removeFromFoundDecls(ET->getDecl());
112     }
113   }
114   // Check the uninstantiated template function usage.
115   if (const auto *ULE = Result.Nodes.getNodeAs<UnresolvedLookupExpr>("used")) {
116     for (const NamedDecl* ND : ULE->decls()) {
117       if (const auto *USD = dyn_cast<UsingShadowDecl>(ND))
118         removeFromFoundDecls(USD->getTargetDecl()->getCanonicalDecl());
119     }
120   }
121 }
122 
123 void UnusedUsingDeclsCheck::removeFromFoundDecls(const Decl *D) {
124   if (!D)
125     return;
126   // FIXME: Currently, we don't handle the using-decls being used in different
127   // scopes (such as different namespaces, different functions). Instead of
128   // giving an incorrect message, we mark all of them as used.
129   //
130   // FIXME: Use a more efficient way to find a matching context.
131   for (auto &Context : Contexts) {
132     if (Context.UsingTargetDecls.count(D->getCanonicalDecl()) > 0)
133       Context.IsUsed = true;
134   }
135 }
136 
137 void UnusedUsingDeclsCheck::onEndOfTranslationUnit() {
138   for (const auto &Context : Contexts) {
139     if (!Context.IsUsed) {
140       diag(Context.FoundUsingDecl->getLocation(), "using decl %0 is unused")
141           << Context.FoundUsingDecl
142           << FixItHint::CreateRemoval(Context.UsingDeclRange);
143     }
144   }
145   Contexts.clear();
146 }
147 
148 } // namespace misc
149 } // namespace tidy
150 } // namespace clang
151