1 //===--- UnusedAliasDeclsCheck.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 "UnusedAliasDeclsCheck.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 {
17 namespace tidy {
18 namespace misc {
19
registerMatchers(MatchFinder * Finder)20 void UnusedAliasDeclsCheck::registerMatchers(MatchFinder *Finder) {
21 // We cannot do anything about headers (yet), as the alias declarations
22 // used in one header could be used by some other translation unit.
23 Finder->addMatcher(namespaceAliasDecl(isExpansionInMainFile()).bind("alias"),
24 this);
25 Finder->addMatcher(nestedNameSpecifier().bind("nns"), this);
26 }
27
check(const MatchFinder::MatchResult & Result)28 void UnusedAliasDeclsCheck::check(const MatchFinder::MatchResult &Result) {
29 if (const auto *AliasDecl = Result.Nodes.getNodeAs<NamedDecl>("alias")) {
30 FoundDecls[AliasDecl] = CharSourceRange::getCharRange(
31 AliasDecl->getBeginLoc(),
32 Lexer::findLocationAfterToken(
33 AliasDecl->getEndLoc(), tok::semi, *Result.SourceManager,
34 getLangOpts(),
35 /*SkipTrailingWhitespaceAndNewLine=*/true));
36 return;
37 }
38
39 if (const auto *NestedName =
40 Result.Nodes.getNodeAs<NestedNameSpecifier>("nns")) {
41 if (const auto *AliasDecl = NestedName->getAsNamespaceAlias()) {
42 FoundDecls[AliasDecl] = CharSourceRange();
43 }
44 }
45 }
46
onEndOfTranslationUnit()47 void UnusedAliasDeclsCheck::onEndOfTranslationUnit() {
48 for (const auto &FoundDecl : FoundDecls) {
49 if (!FoundDecl.second.isValid())
50 continue;
51 diag(FoundDecl.first->getLocation(), "namespace alias decl %0 is unused")
52 << FoundDecl.first << FixItHint::CreateRemoval(FoundDecl.second);
53 }
54 }
55
56 } // namespace misc
57 } // namespace tidy
58 } // namespace clang
59