Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Null coalescing assignment for nullable value type should set state of nullable type not underlying type #67468

Merged
merged 7 commits into from
Apr 17, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2641,6 +2641,13 @@ protected override void JoinTryBlockState(ref LocalState self, ref LocalState ot
private void InheritDefaultState(TypeSymbol targetType, int targetSlot)
{
Debug.Assert(targetSlot > 0);
#if DEBUG
var actualType = _variables[targetSlot].Symbol.GetTypeOrReturnType().Type;
Debug.Assert(actualType is { });
Debug.Assert(actualType.ContainsErrorType() ||
targetType.ContainsErrorType() ||
isOfTypeOrBaseOrInterface(actualType, targetType));
Copy link
Contributor

@RikkiGibson RikkiGibson Apr 7, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we use some "classify conversion" API instead? e.g. if it's identity or implicit reference conversion, maybe that's good enough? #Resolved

#endif

// Reset the state of any members of the target.
var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance();
Expand All @@ -2652,6 +2659,43 @@ private void InheritDefaultState(TypeSymbol targetType, int targetSlot)
InheritDefaultState(symbol.GetTypeOrReturnType().Type, slot);
}
members.Free();

#if DEBUG
static bool isOfTypeOrBaseOrInterface(TypeSymbol actualType, TypeSymbol expectedType)
{
if (isType(actualType, expectedType))
{
return true;
}
if (actualType is NamedTypeSymbol namedType)
{
if (namedType.IsInterface)
{
return namedType.AllInterfacesNoUseSiteDiagnostics.Contains(expectedType);
}
else
{
while (true)
{
var baseType = namedType.BaseTypeNoUseSiteDiagnostics;
if (baseType is null)
{
return false;
}
if (isType(baseType, expectedType))
{
return true;
}
namedType = baseType;
}
}
}
return false;
}

static bool isType(TypeSymbol a, TypeSymbol b)
=> a.Equals(b, TypeCompareKind.AllIgnoreOptions);
#endif
}

private NullableFlowState GetDefaultState(Symbol symbol)
Expand Down Expand Up @@ -5105,12 +5149,26 @@ private static BoundExpression SkipReferenceConversions(BoundExpression possibly
var leftState = this.State.Clone();
LearnFromNonNullTest(leftOperand, ref leftState);
LearnFromNullTest(leftOperand, ref this.State);

// If we are assigning the underlying value type to a nullable value type variable,
Copy link
Contributor

@RikkiGibson RikkiGibson Apr 7, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found this comment a little unclear. I think it should say that we do a special step to set the nullable variable's top level state within this block, then change the slot to later simulate an assignment from the RHS to the LHS's Value property, to update nullable states within the underlying value type. #Resolved

// set the state of the .Value property of the variable.
if (node.IsNullableValueTypeAssignment)
{
Debug.Assert(targetType.Type.ContainsErrorType() ||
node.Type?.ContainsErrorType() == true ||
TypeSymbol.Equals(targetType.Type.GetNullableUnderlyingType(), node.Type, TypeCompareKind.AllIgnoreOptions));
if (leftSlot > 0)
{
SetState(ref this.State, leftSlot, NullableFlowState.NotNull);
leftSlot = GetNullableOfTValueSlot(targetType.Type, leftSlot, out _);
}
targetType = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated);
}

TypeWithState rightResult = VisitOptionalImplicitConversion(rightOperand, targetType, useLegacyWarnings: UseLegacyWarnings(leftOperand), trackMembers: false, AssignmentKind.Assignment);
Debug.Assert(TypeSymbol.Equals(targetType.Type, rightResult.Type, TypeCompareKind.AllIgnoreOptions));
TrackNullableStateForAssignment(rightOperand, targetType, leftSlot, rightResult, MakeSlot(rightOperand));

Join(ref this.State, ref leftState);
TypeWithState resultType = TypeWithState.Create(targetType.Type, rightResult.State);
SetResultType(node, resultType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156945,5 +156945,113 @@ public void Repro66960_2()
Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(5, 54)
);
}

[WorkItem(67040, "https://github.com/dotnet/roslyn/issues/67040")]
[Fact]
public void NullCoalescingAssignment_NullableValueTypeWithValue_01()
{
var source = """
#pragma warning disable 649
#nullable enable
readonly struct S<T>
{
public readonly T Item;
}
class Program
{
static void M(S<object> x, bool b)
{
S<object>? y;
y = x;
y ??= b ? default : default;
}
}
""";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}

[Fact]
public void NullCoalescingAssignment_NullableValueTypeWithValue_02()
{
var source = """
#pragma warning disable 649
#nullable enable
readonly struct S<T>
{
public readonly T Item;
}
class Program
{
static void M(S<object> x)
{
S<object>? y = x;
S<object>? z = null;
z ??= y;
z.Value.Item.ToString();
}
}
""";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}

[Fact]
public void NullCoalescingAssignment_NullableValueTypeWithValue_03()
{
var source = """
#nullable enable
struct S
{
public object? Item;
}
class Program
{
static void M()
{
S x = new S();
x.Item = 1;
S? y;
y = x;
y ??= new S();
y.Value.Item.ToString();
}
}
""";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (15,9): warning CS8602: Dereference of a possibly null reference.
// y.Value.Item.ToString();
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.Item").WithLocation(15, 9));
}

[Fact]
public void NullCoalescingAssignment_NullableValueTypeWithValue_04()
{
var source = """
#nullable enable
interface I
{
object? Item { get; set; }
}
class Program
{
static void M<T>() where T : struct, I
{
T x = new T();
x.Item = 1;
T? y;
y = x;
y ??= new T();
y.Value.Item.ToString();
}
}
""";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (15,9): warning CS8602: Dereference of a possibly null reference.
// y.Value.Item.ToString();
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.Item").WithLocation(15, 9));
}
}
}