Skip to content

Commit 4ca70da

Browse files
committed
warn on _Nonnull field initialized with null
1 parent 2ecf7ba commit 4ca70da

2 files changed

Lines changed: 18 additions & 0 deletions

File tree

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13021,6 +13021,11 @@ def note_nullable_return_fix : Note<
1302113021
def warn_flow_nullable_assignment : Warning<
1302213022
"assigning nullable pointer to nonnull variable %0">,
1302313023
InGroup<FlowNullableAssignment>;
13024+
def warn_flow_nullable_field_init : Warning<
13025+
"initializing nonnull member %0 with null">,
13026+
InGroup<FlowNullableAssignment>;
13027+
def note_nullable_field_init_fix : Note<
13028+
"remove '_Nonnull' if this member can be null, or remove the null initializer">;
1302413029
def note_nullable_assignment_fix : Note<
1302513030
"add a null check before assigning, or change the variable type to "
1302613031
"'_Nullable'">;

clang/lib/Sema/SemaDeclCXX.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4225,6 +4225,19 @@ void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
42254225
}
42264226

42274227
FD->setInClassInitializer(InitExpr.get());
4228+
4229+
// Warn when a _Nonnull field is initialized with null.
4230+
if (FD->getType()->isPointerType()) {
4231+
auto Nullability = FD->getType()->getNullability();
4232+
if (Nullability && *Nullability == NullabilityKind::NonNull) {
4233+
Expr *Init = InitExpr.get()->IgnoreParenImpCasts();
4234+
if (Init->isNullPointerConstant(Context,
4235+
Expr::NPC_ValueDependentIsNotNull)) {
4236+
Diag(Init->getExprLoc(), diag::warn_flow_nullable_field_init) << FD;
4237+
Diag(Init->getExprLoc(), diag::note_nullable_field_init_fix);
4238+
}
4239+
}
4240+
}
42284241
}
42294242

42304243
/// Find the direct and/or virtual base specifiers that

0 commit comments

Comments
 (0)