Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ protected LocalDataFlowPass(

protected abstract int AddVariable(VariableIdentifier identifier);

/// <summary>
/// <summary>Get the slot for a variable, if the slot already exists.</summary>
/// <remarks>
/// Locals are given slots when their declarations are encountered. We only need give slots
/// to local variables, out parameters, and the "this" variable of a struct constructs.
/// Other variables are not given slots, and are therefore not tracked by the analysis. This
Expand All @@ -71,7 +72,7 @@ protected LocalDataFlowPass(
/// variables that occur before the variable is declared, as those are reported in an
/// earlier phase as "use before declaration". That allows us to avoid giving slots to local
/// variables before processing their declarations.
/// </summary>
/// </remarks>
protected int VariableSlot(Symbol symbol, int containingSlot = 0)
{
// Skip LocalStoreTracker from data flow analysis.
Expand Down
115 changes: 89 additions & 26 deletions src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,8 @@ protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByS

protected override bool TryGetVariable(VariableIdentifier identifier, out int slot)
{
// Only the owning symbol should be used to look up the slot.
Debug.Assert(GetOwningSymbolAndContainingSlot(identifier.Symbol, identifier.ContainingSlot) == ((object)identifier.Symbol, identifier.ContainingSlot));
return _variables.TryGetValue(identifier, out slot);
Comment thread
RikkiGibson marked this conversation as resolved.
Resolved
}

Expand Down Expand Up @@ -757,6 +759,10 @@ void enforceMemberNotNull(SyntaxNode? syntaxOpt, LocalState state)

void checkMemberStateOnConstructorExit(MethodSymbol constructor, Symbol member, LocalState state, int thisSlot, Location? exitLocation, ImmutableArray<string> membersWithStateEnforcedByRequiredMembers, bool forcePropertyAnalysis)
{
#if DEBUG
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
Debug.Assert(AccessCheck.IsSymbolAccessible(member, within: constructor.ContainingType, ref discardedUseSiteInfo));
#endif
var isStatic = !constructor.RequiresInstanceReceiver();
Comment thread
RikkiGibson marked this conversation as resolved.
Resolved
if (member.IsStatic != isStatic)
{
Expand Down Expand Up @@ -855,6 +861,10 @@ void makeNotNullMembersMaybeNull()
{
foreach (var member in getMembersNeedingDefaultInitialState())
{
#if DEBUG
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
Debug.Assert(AccessCheck.IsSymbolAccessible(member, within: method.ContainingType, ref discardedUseSiteInfo));
#endif
if (member.IsStatic != method.IsStatic)
{
continue;
Expand All @@ -863,7 +873,9 @@ void makeNotNullMembersMaybeNull()
var memberToInitialize = member;
switch (member)
{
case PropertySymbol { IsRequired: true }:
case PropertySymbol { IsRequired: true } requiredProperty when GetAccessibleBackingField(requiredProperty, method.ContainingType) is null:
// Visit a required property, unless it has a backing field which is accessible in the current context,
// in which case we expect the field to be visited in another iteration of this loop.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It looks like the field can be skipped in some cases (in if (IsPropertyOutputMoreStrictThanInput(prop))). For example,

#nullable enable
using System.Diagnostics.CodeAnalysis;

public class C
{
    [AllowNull]
    public required string P { get; set; }

    [SetsRequiredMembers]
    public C()
    {
        P.ToString();
    }
}

correctly reported a warning on P.ToString(); before this PR, but does not report it after.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The thing is, the warning is also missing before this PR, when required and [SetsRequiredMembers] are both deleted. So, I could see about putting the warning in both scenarios. Hopefully there is now a single point of control for doing that.

@RikkiGibson RikkiGibson Sep 3, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

If you are comfortable with it, I'd like to address the AllowNull issue more holistically in a follow-up. Basically, I think that we could arrive at an overall more desirable behavior by mostly just deleting a little more implementation code. But, there is test churn involved.

break;
case PropertySymbol:
// skip any manually implemented non-required properties.
Expand Down Expand Up @@ -967,27 +979,29 @@ static ImmutableArray<Symbol> membersToBeInitialized(NamedTypeSymbol containingT

(includeAllMembers: false, includeCurrentTypeRequiredMembers: true, includeBaseRequiredMembers: false)
=> containingType.GetMembersUnordered().SelectManyAsArray(
predicate: SymbolExtensions.IsRequired,
selector: symbol => getAllMembersToBeDefaulted(symbol, filterOverridingProperties: true)),
predicate: static (symbol, _) => symbol.IsRequired(),
selector: static (symbol, containingType) => getAllMembersToBeDefaulted(containingType, symbol, filterOverridingProperties: true),
containingType),

(includeAllMembers: false, includeCurrentTypeRequiredMembers: true, includeBaseRequiredMembers: true)
=> containingType.AllRequiredMembers.SelectManyAsArray(static kvp => getAllMembersToBeDefaulted(kvp.Value, filterOverridingProperties: true)),
=> containingType.AllRequiredMembers.SelectManyAsArray(static (kvp, containingType) => getAllMembersToBeDefaulted(containingType, kvp.Value, filterOverridingProperties: true), arg: containingType),

(includeAllMembers: true, includeCurrentTypeRequiredMembers: _, includeBaseRequiredMembers: false)
=> containingType.GetMembersUnordered().SelectManyAsArray(
selector: symbol =>
selector: static (symbol, containingType) =>
{
var symbolToInitialize = getFieldSymbolToBeInitialized(symbol);
var symbolToInitialize = getFieldSymbolToBeInitialized(containingType, symbol);
var prop = symbolToInitialize as PropertySymbol ?? (symbolToInitialize as FieldSymbol)?.AssociatedSymbol as PropertySymbol;
if (prop is not null && isFilterableOverrideOfAbstractProperty(prop))
if (prop is not null && isFilterableOverrideOfAbstractProperty(containingType, prop))
{
return OneOrMany<Symbol>.Empty;
}
else
{
return OneOrMany.Create(symbolToInitialize);
}
}),
},
arg: containingType),

(includeAllMembers: true, includeCurrentTypeRequiredMembers: true, includeBaseRequiredMembers: true)
=> getAllTypeAndRequiredMembers(containingType),
Expand All @@ -996,7 +1010,7 @@ static ImmutableArray<Symbol> membersToBeInitialized(NamedTypeSymbol containingT
=> throw ExceptionUtilities.Unreachable(),
};

static ImmutableArray<Symbol> getAllTypeAndRequiredMembers(TypeSymbol containingType)
static ImmutableArray<Symbol> getAllTypeAndRequiredMembers(NamedTypeSymbol containingType)
{
var members = containingType.GetMembersUnordered();
var baseRequiredMembers = containingType.BaseTypeNoUseSiteDiagnostics?.AllRequiredMembers ?? ImmutableSegmentedDictionary<string, Symbol>.Empty;
Expand All @@ -1018,19 +1032,19 @@ static ImmutableArray<Symbol> getAllTypeAndRequiredMembers(TypeSymbol containing
if (requiredMember is PropertySymbol { IsAbstract: true } abstractProperty)
{
if (members.FirstOrDefault(static (thisMember, baseMember) => thisMember.IsOverride && (object)thisMember.GetOverriddenMember() == baseMember, requiredMember) is { } overridingMember
&& isFilterableOverrideOfAbstractProperty((PropertySymbol)overridingMember))
&& isFilterableOverrideOfAbstractProperty(containingType, (PropertySymbol)overridingMember))
{
continue;
}
}

builder.AddRange(getAllMembersToBeDefaulted(requiredMember, filterOverridingProperties: false));
builder.AddRange(getAllMembersToBeDefaulted(containingType, requiredMember, filterOverridingProperties: false));
}

return builder.ToImmutableAndFree();
}

static OneOrMany<Symbol> getAllMembersToBeDefaulted(Symbol requiredMember, bool filterOverridingProperties)
static OneOrMany<Symbol> getAllMembersToBeDefaulted(NamedTypeSymbol containingType, Symbol requiredMember, bool filterOverridingProperties)
{
Debug.Assert(requiredMember.IsRequired());

Expand All @@ -1042,30 +1056,34 @@ static OneOrMany<Symbol> getAllMembersToBeDefaulted(Symbol requiredMember, bool
{
var property = (PropertySymbol)requiredMember;

if (filterOverridingProperties && isFilterableOverrideOfAbstractProperty(property))
if (filterOverridingProperties && isFilterableOverrideOfAbstractProperty(containingType, property))
{
return OneOrMany<Symbol>.Empty;
}

var @return = OneOrMany.Create(getFieldSymbolToBeInitialized(property));
var @return = OneOrMany.Create(getFieldSymbolToBeInitialized(containingType, property));

// If the set method is null (ie missing), that's an error, but we'll recover as best we can
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
foreach (var notNullMemberName in (property.SetMethod?.NotNullMembers ?? property.NotNullMembers))
{
foreach (var member in property.ContainingType.GetMembers(notNullMemberName))
{
@return = @return.Add(getFieldSymbolToBeInitialized(member));
if (AccessCheck.IsSymbolAccessible(member, containingType, ref discardedUseSiteInfo))
{
@return = @return.Add(getFieldSymbolToBeInitialized(containingType, member));
}
}
}

return @return;
}
}

static Symbol getFieldSymbolToBeInitialized(Symbol requiredMember)
=> requiredMember is SourcePropertySymbolBase { BackingField: { } backingField } ? backingField : requiredMember;
static Symbol getFieldSymbolToBeInitialized(NamedTypeSymbol containingType, Symbol requiredMember)
=> requiredMember is PropertySymbol property && GetAccessibleBackingField(property, containingType) is { } backingField ? backingField : requiredMember;

static bool isFilterableOverrideOfAbstractProperty(PropertySymbol property)
static bool isFilterableOverrideOfAbstractProperty(NamedTypeSymbol containingType, PropertySymbol property)
{
// If this is an override of an abstract property, and the overridden property has the same nullable
// annotation as us, we can skip default-initializing the property because the chained constructor
Expand All @@ -1075,8 +1093,8 @@ static bool isFilterableOverrideOfAbstractProperty(PropertySymbol property)
return false;
}

var symbolAnnotations = property is SourcePropertySymbolBase { UsesFieldKeyword: true, BackingField: { } field }
? field!.FlowAnalysisAnnotations
var symbolAnnotations = GetAccessibleBackingField(property, containingType) is { } field
? field.FlowAnalysisAnnotations
: property.GetFlowAnalysisAnnotations();
var symbolType = ApplyUnconditionalAnnotations(property.TypeWithAnnotations, symbolAnnotations);
if (!symbolType.NullableAnnotation.IsNotAnnotated())
Expand All @@ -1093,6 +1111,25 @@ static bool isFilterableOverrideOfAbstractProperty(PropertySymbol property)
}
}

/// <summary>
/// A property's backing field should only influence behavior of nullable analysis when the field is accessible.
/// For example, when the member being analyzed has the same containing type as the property.
///
/// Note: this refers to accessibility only in the "accessibility modifier" sense.
/// This method may return a non-null symbol even if the field cannot be referenced by name in the current context.
/// </summary>
/// <param name="containingType">Containing type of the member currently being analyzed.</param>
private static SynthesizedBackingFieldSymbol? GetAccessibleBackingField(PropertySymbol property, NamedTypeSymbol containingType)
Comment thread
RikkiGibson marked this conversation as resolved.
Resolved
{
if (property is not SourcePropertySymbolBase { BackingField: { } backingField })
return null;

var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return AccessCheck.IsSymbolAccessible(backingField, within: containingType, ref discardedUseSiteInfo)
? backingField
: null;
}

private void EnforceMemberNotNullOnMember(SyntaxNode? syntaxOpt, LocalState state, MethodSymbol method, string memberName)
{
foreach (var member in method.ContainingType.GetMembers(memberName))
Expand Down Expand Up @@ -2267,6 +2304,16 @@ protected override int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bo
if (containingSlot > 0 && !IsSlotMember(containingSlot, symbol))
return -1;

(symbol, containingSlot) = GetOwningSymbolAndContainingSlot(symbol, containingSlot);
return base.GetOrCreateSlot(symbol, containingSlot, forceSlotEvenIfEmpty, createIfMissing);
}

/// <summary>
/// If the incoming symbol+containingSlot pair shares a slot,
/// returns the owning pair. Otherwise returns the arguments.
/// </summary>
private (Symbol symbol, int containingSlot) GetOwningSymbolAndContainingSlot(Symbol symbol, int containingSlot)
{
// Primary constructor parameter and its backing field share the slot when
// we are dealing with 'this' instance.
if (symbol is ParameterSymbol { ContainingSymbol: SynthesizedPrimaryConstructor primaryConstructor } parameter &&
Expand All @@ -2291,6 +2338,7 @@ protected override int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bo
}

// Share a slot between backing field and associated property/event in the context of a constructor which owns initialization of that backing field.
// https://github.com/dotnet/roslyn/issues/84987: extend this sharing to more methods where the backing field is accessible
if (this._symbol is MethodSymbol constructor
&& constructor.IsConstructor()
&& constructor.IsStatic == symbol.IsStatic)
Expand All @@ -2304,17 +2352,25 @@ protected override int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bo
// - property initializer on normal auto-property
// - property assignment on getter-only auto-property.
// Example test: NullableReferenceTypesTests.ConstructorUsesStateFromInitializers will fail without this.
if (symbol is SynthesizedBackingFieldSymbol { AssociatedSymbol: SourcePropertySymbolBase { UsesFieldKeyword: false } property })
symbol = property;
// If symbol is a property that uses field keyword, then use field to determine initial state and to own the slot.
else if (symbol is SourcePropertySymbolBase { UsesFieldKeyword: true, BackingField: { } backingField })
symbol = backingField;
if (symbol is SynthesizedBackingFieldSymbol { AssociatedProperty.UsesFieldKeyword: false } backingField)
{
symbol = backingField.AssociatedProperty;
}
// If symbol is a property that uses field keyword, and property is not null-resilient, then use field to determine initial state and to own the slot.
else if (symbol is SourcePropertySymbolBase { UsesFieldKeyword: true } property
&& GetAccessibleBackingField(property, constructor.ContainingType) is { } accessibleBackingField
&& !IsAssociatedPropertyNullResilient(accessibleBackingField))
{
symbol = accessibleBackingField;
}
else if (symbol is SourceEventFieldSymbol eventField)
{
symbol = eventField.AssociatedSymbol;
}
}
}

return base.GetOrCreateSlot(symbol, containingSlot, forceSlotEvenIfEmpty, createIfMissing);
return (symbol, containingSlot);
}

private void VisitAndUnsplitAll<T>(ImmutableArray<T> nodes) where T : BoundNode
Expand Down Expand Up @@ -11291,6 +11347,13 @@ private void VisitThisOrBaseReference(BoundExpression node)
return null;
}

private bool IsAssociatedPropertyNullResilient(SynthesizedBackingFieldSymbol backingField)
{
// Only possible to answer this question if a null resilience inference is not currently in progress.
Debug.Assert(_getterNullResilienceData is null);
return backingField.InfersNullableAnnotation && backingField.GetInferredNullableAnnotation() == NullableAnnotation.Annotated;
}

private bool IsPropertyOutputMoreStrictThanInput(PropertySymbol property)
{
var type = property.TypeWithAnnotations;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ protected override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclar
public override Symbol AssociatedSymbol
=> _property;

internal SourcePropertySymbolBase AssociatedProperty
=> _property;

public override ImmutableArray<Location> Locations
=> _property.Locations;

Expand Down
Loading