| 1 |
//===--- PreferMemberInitializerCheck.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 "PreferMemberInitializerCheck.h" |
| 10 |
#include "clang/AST/ASTContext.h" |
| 11 |
#include "clang/ASTMatchers/ASTMatchFinder.h" |
| 12 |
#include "clang/Lex/Lexer.h" |
| 13 |
|
| 14 |
using namespace clang::ast_matchers; |
| 15 |
|
| 16 |
namespace clang::tidy::cppcoreguidelines { |
| 17 |
|
| 18 |
static bool isControlStatement(const Stmt *S) { |
| 19 |
return isa<IfStmt, SwitchStmt, ForStmt, WhileStmt, DoStmt, ReturnStmt, |
| 20 |
GotoStmt, CXXTryStmt, CXXThrowExpr>(S); |
| 21 |
} |
| 22 |
|
| 23 |
static bool isNoReturnCallStatement(const Stmt *S) { |
| 24 |
const auto *Call = dyn_cast<CallExpr>(S); |
| 25 |
if (!Call) |
| 26 |
return false; |
| 27 |
|
| 28 |
const FunctionDecl *Func = Call->getDirectCallee(); |
| 29 |
if (!Func) |
| 30 |
return false; |
| 31 |
|
| 32 |
return Func->isNoReturn(); |
| 33 |
} |
| 34 |
|
| 35 |
static bool isLiteral(const Expr *E) { |
| 36 |
return isa<StringLiteral, CharacterLiteral, IntegerLiteral, FloatingLiteral, |
| 37 |
CXXBoolLiteralExpr, CXXNullPtrLiteralExpr>(E); |
| 38 |
} |
| 39 |
|
| 40 |
static bool isUnaryExprOfLiteral(const Expr *E) { |
| 41 |
if (const auto *UnOp = dyn_cast<UnaryOperator>(E)) |
| 42 |
return isLiteral(UnOp->getSubExpr()); |
| 43 |
return false; |
| 44 |
} |
| 45 |
|
| 46 |
static bool shouldBeDefaultMemberInitializer(const Expr *Value) { |
| 47 |
if (isLiteral(Value) || isUnaryExprOfLiteral(Value)) |
| 48 |
return true; |
| 49 |
|
| 50 |
if (const auto *DRE = dyn_cast<DeclRefExpr>(Value)) |
| 51 |
return isa<EnumConstantDecl>(DRE->getDecl()); |
| 52 |
|
| 53 |
return false; |
| 54 |
} |
| 55 |
|
| 56 |
namespace { |
| 57 |
AST_MATCHER_P(FieldDecl, indexNotLessThan, unsigned, Index) { |
| 58 |
return Node.getFieldIndex() >= Index; |
| 59 |
} |
| 60 |
} // namespace |
| 61 |
|
| 62 |
// Checks if Field is initialised using a field that will be initialised after |
| 63 |
// it. |
| 64 |
// TODO: Probably should guard against function calls that could have side |
| 65 |
// effects or if they do reference another field that's initialized before this |
| 66 |
// field, but is modified before the assignment. |
| 67 |
static bool isSafeAssignment(const FieldDecl *Field, const Expr *Init, |
| 68 |
const CXXConstructorDecl *Context) { |
| 69 |
|
| 70 |
auto MemberMatcher = |
| 71 |
memberExpr(hasObjectExpression(cxxThisExpr()), |
| 72 |
member(fieldDecl(indexNotLessThan(Field->getFieldIndex())))); |
| 73 |
|
| 74 |
auto DeclMatcher = declRefExpr( |
| 75 |
to(varDecl(unless(parmVarDecl()), hasDeclContext(equalsNode(Context))))); |
| 76 |
|
| 77 |
return match(expr(anyOf(MemberMatcher, DeclMatcher, |
| 78 |
hasDescendant(MemberMatcher), |
| 79 |
hasDescendant(DeclMatcher))), |
| 80 |
*Init, Field->getASTContext()) |
| 81 |
.empty(); |
| 82 |
} |
| 83 |
|
| 84 |
static std::pair<const FieldDecl *, const Expr *> |
| 85 |
isAssignmentToMemberOf(const CXXRecordDecl *Rec, const Stmt *S, |
| 86 |
const CXXConstructorDecl *Ctor) { |
| 87 |
if (const auto *BO = dyn_cast<BinaryOperator>(S)) { |
| 88 |
if (BO->getOpcode() != BO_Assign) |
| 89 |
return std::make_pair(nullptr, nullptr); |
| 90 |
|
| 91 |
const auto *ME = dyn_cast<MemberExpr>(BO->getLHS()->IgnoreParenImpCasts()); |
| 92 |
if (!ME) |
| 93 |
return std::make_pair(nullptr, nullptr); |
| 94 |
|
| 95 |
const auto *Field = dyn_cast<FieldDecl>(ME->getMemberDecl()); |
| 96 |
if (!Field) |
| 97 |
return std::make_pair(nullptr, nullptr); |
| 98 |
|
| 99 |
if (!isa<CXXThisExpr>(ME->getBase())) |
| 100 |
return std::make_pair(nullptr, nullptr); |
| 101 |
const Expr *Init = BO->getRHS()->IgnoreParenImpCasts(); |
| 102 |
if (isSafeAssignment(Field, Init, Ctor)) |
| 103 |
return std::make_pair(Field, Init); |
| 104 |
} else if (const auto *COCE = dyn_cast<CXXOperatorCallExpr>(S)) { |
| 105 |
if (COCE->getOperator() != OO_Equal) |
| 106 |
return std::make_pair(nullptr, nullptr); |
| 107 |
|
| 108 |
const auto *ME = |
| 109 |
dyn_cast<MemberExpr>(COCE->getArg(0)->IgnoreParenImpCasts()); |
| 110 |
if (!ME) |
| 111 |
return std::make_pair(nullptr, nullptr); |
| 112 |
|
| 113 |
const auto *Field = dyn_cast<FieldDecl>(ME->getMemberDecl()); |
| 114 |
if (!Field) |
| 115 |
return std::make_pair(nullptr, nullptr); |
| 116 |
|
| 117 |
if (!isa<CXXThisExpr>(ME->getBase())) |
| 118 |
return std::make_pair(nullptr, nullptr); |
| 119 |
const Expr *Init = COCE->getArg(1)->IgnoreParenImpCasts(); |
| 120 |
if (isSafeAssignment(Field, Init, Ctor)) |
| 121 |
return std::make_pair(Field, Init); |
| 122 |
} |
| 123 |
|
| 124 |
return std::make_pair(nullptr, nullptr); |
| 125 |
} |
| 126 |
|
| 127 |
PreferMemberInitializerCheck::PreferMemberInitializerCheck( |
| 128 |
StringRef Name, ClangTidyContext *Context) |
| 129 |
: ClangTidyCheck(Name, Context), |
| 130 |
IsUseDefaultMemberInitEnabled( |
| 131 |
Context->isCheckEnabled("modernize-use-default-member-init")), |
| 132 |
UseAssignment(OptionsView("modernize-use-default-member-init", |
| 133 |
Context->getOptions().CheckOptions, Context) |
| 134 |
.get("UseAssignment", false)) {} |
| 135 |
|
| 136 |
void PreferMemberInitializerCheck::storeOptions( |
| 137 |
ClangTidyOptions::OptionMap &Opts) { |
| 138 |
Options.store(Opts, "UseAssignment", UseAssignment); |
| 139 |
} |
| 140 |
|
| 141 |
void PreferMemberInitializerCheck::registerMatchers(MatchFinder *Finder) { |
| 142 |
Finder->addMatcher( |
| 143 |
cxxConstructorDecl(hasBody(compoundStmt()), unless(isInstantiated())) |
| 144 |
.bind("ctor"), |
| 145 |
this); |
| 146 |
} |
| 147 |
|
| 148 |
void PreferMemberInitializerCheck::check( |
| 149 |
const MatchFinder::MatchResult &Result) { |
| 150 |
const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("ctor"); |
| 151 |
const auto *Body = cast<CompoundStmt>(Ctor->getBody()); |
| 152 |
|
| 153 |
const CXXRecordDecl *Class = Ctor->getParent(); |
| 154 |
bool FirstToCtorInits = true; |
| 155 |
|
| 156 |
for (const Stmt *S : Body->body()) { |
| 157 |
if (S->getBeginLoc().isMacroID()) { |
| 158 |
StringRef MacroName = Lexer::getImmediateMacroName( |
| 159 |
S->getBeginLoc(), *Result.SourceManager, getLangOpts()); |
| 160 |
if (MacroName.contains_insensitive("assert")) |
| 161 |
return; |
| 162 |
} |
| 163 |
if (isControlStatement(S)) |
| 164 |
return; |
| 165 |
|
| 166 |
if (isNoReturnCallStatement(S)) |
| 167 |
return; |
| 168 |
|
| 169 |
if (const auto *CondOp = dyn_cast<ConditionalOperator>(S)) { |
| 170 |
if (isNoReturnCallStatement(CondOp->getLHS()) || |
| 171 |
isNoReturnCallStatement(CondOp->getRHS())) |
| 172 |
return; |
| 173 |
} |
| 174 |
|
| 175 |
const FieldDecl *Field; |
| 176 |
const Expr *InitValue; |
| 177 |
std::tie(Field, InitValue) = isAssignmentToMemberOf(Class, S, Ctor); |
| 178 |
if (Field) { |
| 179 |
if (IsUseDefaultMemberInitEnabled && getLangOpts().CPlusPlus11 && |
| 180 |
Ctor->isDefaultConstructor() && |
| 181 |
(getLangOpts().CPlusPlus20 || !Field->isBitField()) && |
| 182 |
!Field->hasInClassInitializer() && |
| 183 |
(!isa<RecordDecl>(Class->getDeclContext()) || |
| 184 |
!cast<RecordDecl>(Class->getDeclContext())->isUnion()) && |
| 185 |
shouldBeDefaultMemberInitializer(InitValue)) { |
| 186 |
|
| 187 |
bool InvalidFix = false; |
| 188 |
SourceLocation FieldEnd = |
| 189 |
Lexer::getLocForEndOfToken(Field->getSourceRange().getEnd(), 0, |
| 190 |
*Result.SourceManager, getLangOpts()); |
| 191 |
InvalidFix |= FieldEnd.isInvalid() || FieldEnd.isMacroID(); |
| 192 |
SourceLocation SemiColonEnd; |
| 193 |
if (auto NextToken = Lexer::findNextToken( |
| 194 |
S->getEndLoc(), *Result.SourceManager, getLangOpts())) |
| 195 |
SemiColonEnd = NextToken->getEndLoc(); |
| 196 |
else |
| 197 |
InvalidFix = true; |
| 198 |
auto Diag = |
| 199 |
diag(S->getBeginLoc(), "%0 should be initialized in an in-class" |
| 200 |
" default member initializer") |
| 201 |
<< Field; |
| 202 |
if (InvalidFix) |
| 203 |
continue; |
| 204 |
CharSourceRange StmtRange = |
| 205 |
CharSourceRange::getCharRange(S->getBeginLoc(), SemiColonEnd); |
| 206 |
|
| 207 |
SmallString<128> Insertion( |
| 208 |
{UseAssignment ? " = " : "{", |
| 209 |
Lexer::getSourceText( |
| 210 |
CharSourceRange(InitValue->getSourceRange(), true), |
| 211 |
*Result.SourceManager, getLangOpts()), |
| 212 |
UseAssignment ? "" : "}"}); |
| 213 |
|
| 214 |
Diag << FixItHint::CreateInsertion(FieldEnd, Insertion) |
| 215 |
<< FixItHint::CreateRemoval(StmtRange); |
| 216 |
|
| 217 |
} else { |
| 218 |
StringRef InsertPrefix = ""; |
| 219 |
bool HasInitAlready = false; |
| 220 |
SourceLocation InsertPos; |
| 221 |
SourceRange ReplaceRange; |
| 222 |
bool AddComma = false; |
| 223 |
bool InvalidFix = false; |
| 224 |
unsigned Index = Field->getFieldIndex(); |
| 225 |
const CXXCtorInitializer *LastInListInit = nullptr; |
| 226 |
for (const CXXCtorInitializer *Init : Ctor->inits()) { |
| 227 |
if (!Init->isWritten() || Init->isInClassMemberInitializer()) |
| 228 |
continue; |
| 229 |
if (Init->getMember() == Field) { |
| 230 |
HasInitAlready = true; |
| 231 |
if (isa<ImplicitValueInitExpr>(Init->getInit())) |
| 232 |
InsertPos = Init->getRParenLoc(); |
| 233 |
else { |
| 234 |
ReplaceRange = Init->getInit()->getSourceRange(); |
| 235 |
} |
| 236 |
break; |
| 237 |
} |
| 238 |
if (Init->isMemberInitializer() && |
| 239 |
Index < Init->getMember()->getFieldIndex()) { |
| 240 |
InsertPos = Init->getSourceLocation(); |
| 241 |
// There are initializers after the one we are inserting, so add a |
| 242 |
// comma after this insertion in order to not break anything. |
| 243 |
AddComma = true; |
| 244 |
break; |
| 245 |
} |
| 246 |
LastInListInit = Init; |
| 247 |
} |
| 248 |
if (HasInitAlready) { |
| 249 |
if (InsertPos.isValid()) |
| 250 |
InvalidFix |= InsertPos.isMacroID(); |
| 251 |
else |
| 252 |
InvalidFix |= ReplaceRange.getBegin().isMacroID() || |
| 253 |
ReplaceRange.getEnd().isMacroID(); |
| 254 |
} else { |
| 255 |
if (InsertPos.isInvalid()) { |
| 256 |
if (LastInListInit) { |
| 257 |
InsertPos = Lexer::getLocForEndOfToken( |
| 258 |
LastInListInit->getRParenLoc(), 0, *Result.SourceManager, |
| 259 |
getLangOpts()); |
| 260 |
// Inserting after the last constructor initializer, so we need a |
| 261 |
// comma. |
| 262 |
InsertPrefix = ", "; |
| 263 |
} else { |
| 264 |
InsertPos = Lexer::getLocForEndOfToken( |
| 265 |
Ctor->getTypeSourceInfo() |
| 266 |
->getTypeLoc() |
| 267 |
.getAs<clang::FunctionTypeLoc>() |
| 268 |
.getLocalRangeEnd(), |
| 269 |
0, *Result.SourceManager, getLangOpts()); |
| 270 |
|
| 271 |
// If this is first time in the loop, there are no initializers so |
| 272 |
// `:` declares member initialization list. If this is a |
| 273 |
// subsequent pass then we have already inserted a `:` so continue |
| 274 |
// with a comma. |
| 275 |
InsertPrefix = FirstToCtorInits ? " : " : ", "; |
| 276 |
} |
| 277 |
} |
| 278 |
InvalidFix |= InsertPos.isMacroID(); |
| 279 |
} |
| 280 |
|
| 281 |
SourceLocation SemiColonEnd; |
| 282 |
if (auto NextToken = Lexer::findNextToken( |
| 283 |
S->getEndLoc(), *Result.SourceManager, getLangOpts())) |
| 284 |
SemiColonEnd = NextToken->getEndLoc(); |
| 285 |
else |
| 286 |
InvalidFix = true; |
| 287 |
|
| 288 |
auto Diag = |
| 289 |
diag(S->getBeginLoc(), "%0 should be initialized in a member" |
| 290 |
" initializer of the constructor") |
| 291 |
<< Field; |
| 292 |
if (InvalidFix) |
| 293 |
continue; |
| 294 |
StringRef NewInit = Lexer::getSourceText( |
| 295 |
CharSourceRange(InitValue->getSourceRange(), true), |
| 296 |
*Result.SourceManager, getLangOpts()); |
| 297 |
if (HasInitAlready) { |
| 298 |
if (InsertPos.isValid()) |
| 299 |
Diag << FixItHint::CreateInsertion(InsertPos, NewInit); |
| 300 |
else |
| 301 |
Diag << FixItHint::CreateReplacement(ReplaceRange, NewInit); |
| 302 |
} else { |
| 303 |
SmallString<128> Insertion({InsertPrefix, Field->getName(), "(", |
| 304 |
NewInit, AddComma ? "), " : ")"}); |
| 305 |
Diag << FixItHint::CreateInsertion(InsertPos, Insertion, |
| 306 |
FirstToCtorInits); |
| 307 |
FirstToCtorInits = areDiagsSelfContained(); |
| 308 |
} |
| 309 |
Diag << FixItHint::CreateRemoval( |
| 310 |
CharSourceRange::getCharRange(S->getBeginLoc(), SemiColonEnd)); |
| 311 |
} |
| 312 |
} |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
} // namespace clang::tidy::cppcoreguidelines |