Repository navigation
Use non-null initial state for null-resilient properties in constructors #84991
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
Changes from 2 commits
f7b09e4
4c4cb30
048115d
12fdc44
adcc3fb
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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); | ||
| } | ||
|
|
||
|
|
@@ -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(); | ||
|
RikkiGibson marked this conversation as resolved.
Resolved
|
||
| if (member.IsStatic != isStatic) | ||
| { | ||
|
|
@@ -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; | ||
|
|
@@ -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. | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It looks like the field can be skipped in some cases (in #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
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The thing is, the warning is also missing before this PR, when
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. | ||
|
|
@@ -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), | ||
|
|
@@ -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; | ||
|
|
@@ -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()); | ||
|
|
||
|
|
@@ -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 | ||
|
|
@@ -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()) | ||
|
|
@@ -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) | ||
|
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)) | ||
|
|
@@ -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 && | ||
|
|
@@ -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) | ||
|
|
@@ -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 | ||
|
|
@@ -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; | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.