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