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) {
22 Finder->addMatcher(namedDecl(anyOf(varDecl(), functionDecl())).bind(
"Decl"),
26 void RedundantDeclarationCheck::check(
const MatchFinder::MatchResult &
Result) {
27 const auto *D = Result.Nodes.getNodeAs<NamedDecl>(
"Decl");
28 const auto *Prev = D->getPreviousDecl();
31 if (!Prev->getLocation().isValid())
33 if (Prev->getLocation() == D->getLocation())
36 const SourceManager &
SM = *Result.SourceManager;
38 const bool DifferentHeaders =
39 !SM.isInMainFile(D->getLocation()) &&
40 !SM.isWrittenInSameFile(Prev->getLocation(), D->getLocation());
42 bool MultiVar =
false;
43 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
44 if (VD->getPreviousDecl()->getStorageClass() == SC_Extern &&
45 VD->getStorageClass() != SC_Extern)
48 for (
const auto Other : VD->getDeclContext()->decls()) {
49 if (Other != D && Other->getLocStart() == VD->getLocStart()) {
55 const auto *FD = cast<FunctionDecl>(D);
56 if (FD->isThisDeclarationADefinition())
60 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
61 D->getSourceRange().getEnd(), 0,
SM, Result.Context->getLangOpts());
63 auto Diag = diag(D->getLocation(),
"redundant %0 declaration") << D;
64 if (!MultiVar && !DifferentHeaders)
65 Diag << FixItHint::CreateRemoval(
66 SourceRange(D->getSourceRange().getBegin(), EndLoc));
68 diag(Prev->getLocation(),
"previously declared here", DiagnosticIDs::Note);
std::unique_ptr< ast_matchers::MatchFinder > Finder