| 1 |
//===--- RedundantMemberInitCheck.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 "RedundantMemberInitCheck.h" |
| 10 |
#include "../utils/Matchers.h" |
| 11 |
#include "clang/AST/ASTContext.h" |
| 12 |
#include "clang/ASTMatchers/ASTMatchFinder.h" |
| 13 |
#include "clang/Lex/Lexer.h" |
| 14 |
#include <algorithm> |
| 15 |
|
| 16 |
using namespace clang::ast_matchers; |
| 17 |
using namespace clang::tidy::matchers; |
| 18 |
|
| 19 |
namespace clang::tidy::readability { |
| 20 |
|
| 21 |
void RedundantMemberInitCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { |
| 22 |
Options.store(Opts, "IgnoreBaseInCopyConstructors", |
| 23 |
IgnoreBaseInCopyConstructors); |
| 24 |
} |
| 25 |
|
| 26 |
void RedundantMemberInitCheck::registerMatchers(MatchFinder *Finder) { |
| 27 |
Finder->addMatcher( |
| 28 |
cxxConstructorDecl( |
| 29 |
unless(isDelegatingConstructor()), ofClass(unless(isUnion())), |
| 30 |
forEachConstructorInitializer( |
| 31 |
cxxCtorInitializer( |
| 32 |
withInitializer( |
| 33 |
cxxConstructExpr( |
| 34 |
hasDeclaration( |
| 35 |
cxxConstructorDecl(ofClass(cxxRecordDecl( |
| 36 |
unless(isTriviallyDefaultConstructible())))))) |
| 37 |
.bind("construct")), |
| 38 |
unless(forField(hasType(isConstQualified()))), |
| 39 |
unless(forField(hasParent(recordDecl(isUnion()))))) |
| 40 |
.bind("init"))) |
| 41 |
.bind("constructor"), |
| 42 |
this); |
| 43 |
} |
| 44 |
|
| 45 |
void RedundantMemberInitCheck::check(const MatchFinder::MatchResult &Result) { |
| 46 |
const auto *Init = Result.Nodes.getNodeAs<CXXCtorInitializer>("init"); |
| 47 |
const auto *Construct = Result.Nodes.getNodeAs<CXXConstructExpr>("construct"); |
| 48 |
const auto *ConstructorDecl = |
| 49 |
Result.Nodes.getNodeAs<CXXConstructorDecl>("constructor"); |
| 50 |
|
| 51 |
if (IgnoreBaseInCopyConstructors && ConstructorDecl->isCopyConstructor() && |
| 52 |
Init->isBaseInitializer()) |
| 53 |
return; |
| 54 |
|
| 55 |
if (Construct->getNumArgs() == 0 || |
| 56 |
Construct->getArg(0)->isDefaultArgument()) { |
| 57 |
if (Init->isAnyMemberInitializer()) { |
| 58 |
diag(Init->getSourceLocation(), "initializer for member %0 is redundant") |
| 59 |
<< Init->getAnyMember() |
| 60 |
<< FixItHint::CreateRemoval(Init->getSourceRange()); |
| 61 |
} else { |
| 62 |
diag(Init->getSourceLocation(), |
| 63 |
"initializer for base class %0 is redundant") |
| 64 |
<< Construct->getType() |
| 65 |
<< FixItHint::CreateRemoval(Init->getSourceRange()); |
| 66 |
} |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
} // namespace clang::tidy::readability |