UnusedAliasDeclsCheck.cpp 1.9 KB

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