11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Lex/Lexer.h"
15 using namespace clang::ast_matchers;
19 namespace readability {
21 void RedundantDeclarationCheck::registerMatchers(MatchFinder *
Finder) {
24 anyOf(varDecl(unless(isDefinition())),
25 functionDecl(unless(anyOf(isDefinition(), isDefaulted())))))
30 void RedundantDeclarationCheck::check(
const MatchFinder::MatchResult &Result) {
31 const auto *D = Result.Nodes.getNodeAs<NamedDecl>(
"Decl");
32 const auto *Prev = D->getPreviousDecl();
35 if (!Prev->getLocation().isValid())
37 if (Prev->getLocation() == D->getLocation())
40 const SourceManager &
SM = *Result.SourceManager;
42 const bool DifferentHeaders =
43 !SM.isInMainFile(D->getLocation()) &&
44 !SM.isWrittenInSameFile(Prev->getLocation(), D->getLocation());
46 bool MultiVar =
false;
47 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
49 for (
const auto Other : VD->getDeclContext()->decls()) {
50 if (Other != D && Other->getLocStart() == VD->getLocStart()) {
57 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
58 D->getSourceRange().getEnd(), 0,
SM, Result.Context->getLangOpts());
60 auto Diag = diag(D->getLocation(),
"redundant %0 declaration") << D;
61 if (!MultiVar && !DifferentHeaders)
62 Diag << FixItHint::CreateRemoval(
63 SourceRange(D->getSourceRange().getBegin(), EndLoc));
65 diag(Prev->getLocation(),
"previously declared here", DiagnosticIDs::Note);
std::unique_ptr< ast_matchers::MatchFinder > Finder