10#include "clang/AST/ASTContext.h"
11#include "clang/AST/Decl.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Lex/Lexer.h"
14#include "llvm/ADT/DenseMap.h"
21 return isa<IfStmt, SwitchStmt, ForStmt, WhileStmt, DoStmt, ReturnStmt,
22 GotoStmt, CXXTryStmt, CXXThrowExpr>(S);
26 const auto *Call = dyn_cast<CallExpr>(S);
30 const FunctionDecl *Func = Call->getDirectCallee();
34 return Func->isNoReturn();
40 return Node.getFieldIndex() >= Index;
43enum class AssignedLevel {
59 return Level == AssignedLevel::None || Level == AssignedLevel::Default;
68 const FieldDecl *Field,
const Expr *Init,
const CXXConstructorDecl *Ctor,
69 llvm::DenseMap<const FieldDecl *, AssignedLevel> &AssignedFields) {
70 auto It = AssignedFields.try_emplace(
Field, AssignedLevel::None).first;
76 if (
Field->getType().getCanonicalType()->isReferenceType()) {
78 It->second = AssignedLevel::HasSideEffect;
83 memberExpr(hasObjectExpression(cxxThisExpr()),
84 member(fieldDecl(indexNotLessThan(
Field->getFieldIndex()))));
85 auto DeclMatcher = declRefExpr(
86 to(valueDecl(unless(parmVarDecl()), hasDeclContext(equalsNode(Ctor)))));
87 const bool HasDependence = !match(expr(anyOf(MemberMatcher, DeclMatcher,
88 hasDescendant(MemberMatcher),
89 hasDescendant(DeclMatcher))),
90 *Init,
Field->getASTContext())
93 It->second = AssignedLevel::HasDependence;
103static std::optional<AssignmentPair>
105 const CXXConstructorDecl *Ctor) {
106 if (
const auto *BO = dyn_cast<BinaryOperator>(S)) {
107 if (BO->getOpcode() != BO_Assign)
110 const auto *ME = dyn_cast<MemberExpr>(BO->getLHS()->IgnoreParenImpCasts());
114 const auto *
Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
118 if (!isa<CXXThisExpr>(ME->getBase()))
120 const Expr *Init = BO->getRHS()->IgnoreParenImpCasts();
123 if (
const auto *COCE = dyn_cast<CXXOperatorCallExpr>(S)) {
124 if (COCE->getOperator() != OO_Equal)
128 dyn_cast<MemberExpr>(COCE->getArg(0)->IgnoreParenImpCasts());
132 const auto *
Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
136 if (!isa<CXXThisExpr>(ME->getBase()))
138 const Expr *Init = COCE->getArg(1)->IgnoreParenImpCasts();
149 Finder->addMatcher(cxxConstructorDecl(hasBody(compoundStmt()),
150 unless(isInstantiated()),
151 unless(isDelegatingConstructor()))
157 const MatchFinder::MatchResult &Result) {
158 const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>(
"ctor");
159 const auto *Body = cast<CompoundStmt>(Ctor->getBody());
161 const CXXRecordDecl *Class = Ctor->getParent();
162 bool FirstToCtorInits =
true;
164 llvm::DenseMap<const FieldDecl *, AssignedLevel> AssignedFields{};
166 for (
const CXXCtorInitializer *Init : Ctor->inits())
167 if (FieldDecl *
Field = Init->getMember())
170 for (
const Stmt *S : Body->body()) {
171 if (S->getBeginLoc().isMacroID()) {
172 StringRef
MacroName = Lexer::getImmediateMacroName(
173 S->getBeginLoc(), *Result.SourceManager,
getLangOpts());
174 if (
MacroName.contains_insensitive(
"assert"))
183 if (
const auto *CondOp = dyn_cast<ConditionalOperator>(S)) {
189 std::optional<AssignmentPair> AssignmentToMember =
191 if (!AssignmentToMember)
193 const FieldDecl *
Field = AssignmentToMember->Field;
194 const Expr *InitValue = AssignmentToMember->Init;
199 StringRef InsertPrefix =
"";
200 bool HasInitAlready =
false;
201 SourceLocation InsertPos;
202 SourceRange ReplaceRange;
203 bool AddComma =
false;
204 bool AddBrace =
false;
205 bool InvalidFix =
false;
206 unsigned Index =
Field->getFieldIndex();
207 const CXXCtorInitializer *LastInListInit =
nullptr;
208 for (
const CXXCtorInitializer *Init : Ctor->inits()) {
209 if (!Init->isWritten() || Init->isInClassMemberInitializer())
211 if (Init->getMember() ==
Field) {
212 HasInitAlready =
true;
213 if (isa<ImplicitValueInitExpr>(Init->getInit()))
214 InsertPos = Init->getRParenLoc();
216 ReplaceRange = Init->getInit()->getSourceRange();
217 AddBrace = isa<InitListExpr>(Init->getInit());
221 if (Init->isMemberInitializer() &&
222 Index < Init->getMember()->getFieldIndex()) {
223 InsertPos = Init->getSourceLocation();
229 LastInListInit = Init;
231 if (HasInitAlready) {
232 if (InsertPos.isValid())
233 InvalidFix |= InsertPos.isMacroID();
235 InvalidFix |= ReplaceRange.getBegin().isMacroID() ||
236 ReplaceRange.getEnd().isMacroID();
238 if (InsertPos.isInvalid()) {
239 if (LastInListInit) {
241 Lexer::getLocForEndOfToken(LastInListInit->getRParenLoc(), 0,
247 InsertPos = Lexer::getLocForEndOfToken(
248 Ctor->getTypeSourceInfo()
250 .getAs<clang::FunctionTypeLoc>()
258 InsertPrefix = FirstToCtorInits ?
" : " :
", ";
261 InvalidFix |= InsertPos.isMacroID();
264 SourceLocation SemiColonEnd;
265 if (
auto NextToken = Lexer::findNextToken(
266 S->getEndLoc(), *Result.SourceManager,
getLangOpts()))
267 SemiColonEnd = NextToken->getEndLoc();
271 auto Diag =
diag(S->getBeginLoc(),
"%0 should be initialized in a member"
272 " initializer of the constructor")
276 StringRef NewInit = Lexer::getSourceText(
277 Result.SourceManager->getExpansionRange(InitValue->getSourceRange()),
279 if (HasInitAlready) {
280 if (InsertPos.isValid())
281 Diag << FixItHint::CreateInsertion(InsertPos, NewInit);
283 Diag << FixItHint::CreateReplacement(ReplaceRange,
284 (
"{" + NewInit +
"}").str());
286 Diag << FixItHint::CreateReplacement(ReplaceRange, NewInit);
288 SmallString<128> Insertion({InsertPrefix,
Field->getName(),
"(", NewInit,
289 AddComma ?
"), " :
")"});
290 Diag << FixItHint::CreateInsertion(InsertPos, Insertion,
294 Diag << FixItHint::CreateRemoval(
295 CharSourceRange::getCharRange(S->getBeginLoc(), SemiColonEnd));
static constexpr Index None
llvm::SmallString< 256U > Name
::clang::DynTypedNode Node
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
bool areDiagsSelfContained() const
Returns true when the check is run in a use case when only 1 fix will be applied at a time.
const LangOptions & getLangOpts() const
Returns the language options from the context.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
PreferMemberInitializerCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
AST_MATCHER_P(UserDefinedLiteral, hasLiteral, clang::ast_matchers::internal::Matcher< Expr >, InnerMatcher)
static void updateAssignmentLevel(const FieldDecl *Field, const Expr *Init, const CXXConstructorDecl *Ctor, llvm::DenseMap< const FieldDecl *, AssignedLevel > &AssignedFields)
static bool canAdvanceAssignment(AssignedLevel Level)
static bool isNoReturnCallStatement(const Stmt *S)
static bool isControlStatement(const Stmt *S)
static std::optional< AssignmentPair > isAssignmentToMemberOf(const CXXRecordDecl *Rec, const Stmt *S, const CXXConstructorDecl *Ctor)