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