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

Support ref field assignment in object initializers #62584

Merged
merged 9 commits into from
Jul 21, 2022
Merged
Show file tree
Hide file tree
Changes from 7 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
13 changes: 11 additions & 2 deletions src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,7 @@ internal bool CheckValueKind(SyntaxNode node, BoundExpression expr, BindValueKin
// dynamic expressions are readwrite, and can even be passed by ref (which is implemented via a temp)
case BoundKind.DynamicMemberAccess:
case BoundKind.DynamicIndexerAccess:
case BoundKind.DynamicObjectInitializerMember:
{
if (RequiresRefAssignableVariable(valueKind))
{
Expand Down Expand Up @@ -3144,7 +3145,11 @@ private uint GetValEscapeOfObjectInitializer(BoundObjectInitializerExpression in
if (expression.Kind == BoundKind.AssignmentOperator)
{
var assignment = (BoundAssignmentOperator)expression;
result = Math.Max(result, GetValEscape(assignment.Right, scopeOfTheContainingExpression));
var rightValEscape = assignment.IsRef
? GetRefEscape(assignment.Right, scopeOfTheContainingExpression)
: GetValEscape(assignment.Right, scopeOfTheContainingExpression);

result = Math.Max(result, rightValEscape);

var left = (BoundObjectInitializerMember)assignment.Left;
result = Math.Max(result, GetValEscape(left.Arguments, scopeOfTheContainingExpression));
Expand Down Expand Up @@ -3773,7 +3778,11 @@ private bool CheckValEscapeOfObjectInitializer(BoundObjectInitializerExpression
if (expression.Kind == BoundKind.AssignmentOperator)
{
var assignment = (BoundAssignmentOperator)expression;
if (!CheckValEscape(expression.Syntax, assignment.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
bool valid = assignment.IsRef
? CheckRefEscape(expression.Syntax, assignment.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics)
: CheckValEscape(expression.Syntax, assignment.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);

if (!valid)
{
return false;
}
Expand Down
147 changes: 79 additions & 68 deletions src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs

Large diffs are not rendered by default.

83 changes: 55 additions & 28 deletions src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1445,40 +1445,25 @@ private BoundExpression BindAssignment(AssignmentExpressionSyntax node, BindingD
}

BindValueKind lhsKind;
BindValueKind rhsKind;
ExpressionSyntax rhsExpr;
bool isRef = false;

if (node.Right.Kind() == SyntaxKind.RefExpression)
{
isRef = true;
lhsKind = BindValueKind.RefAssignable;
rhsKind = BindValueKind.RefersToLocation;
rhsExpr = ((RefExpressionSyntax)node.Right).Expression;
}
else
{
lhsKind = BindValueKind.Assignable;
rhsKind = BindValueKind.RValue;
rhsExpr = node.Right;
}

var op1 = BindValue(node.Left, diagnostics, lhsKind);
ReportSuppressionIfNeeded(op1, diagnostics);

var lhsRefKind = RefKind.None;
// If the LHS is a ref (not ref-readonly), the rhs
// must also be value-assignable
if (lhsKind == BindValueKind.RefAssignable && !op1.HasErrors)
{
// We should now know that op1 is a valid lvalue
lhsRefKind = op1.GetRefKind();
if (lhsRefKind == RefKind.Ref || lhsRefKind == RefKind.Out)
{
rhsKind |= BindValueKind.Assignable;
}
}

var rhsKind = isRef ? GetRequiredRHSValueKindForRefAssignment(op1) : BindValueKind.RValue;
var op2 = BindValue(rhsExpr, diagnostics, rhsKind);

if (op1.Kind == BoundKind.DiscardExpression)
Expand All @@ -1487,7 +1472,26 @@ private BoundExpression BindAssignment(AssignmentExpressionSyntax node, BindingD
op1 = InferTypeForDiscardAssignment((BoundDiscardExpression)op1, op2, diagnostics);
}

return BindAssignment(node, op1, op2, isRef, diagnostics);
return BindAssignment(node, op1, op2, isRef, verifyEscapeSafety: true, diagnostics);
}

private static BindValueKind GetRequiredRHSValueKindForRefAssignment(BoundExpression boundLeft)
{
var rhsKind = BindValueKind.RefersToLocation;

if (!boundLeft.HasErrors)
{
// We should now know that boundLeft is a valid lvalue
var lhsRefKind = boundLeft.GetRefKind();
if (lhsRefKind is RefKind.Ref or RefKind.Out)
{
// If the LHS is a ref (not ref-readonly), the RHS
// must also be value-assignable
rhsKind |= BindValueKind.Assignable;
}
}

return rhsKind;
}

private BoundExpression InferTypeForDiscardAssignment(BoundDiscardExpression op1, BoundExpression op2, BindingDiagnosticBag diagnostics)
Expand All @@ -1511,6 +1515,7 @@ private BoundAssignmentOperator BindAssignment(
BoundExpression op1,
BoundExpression op2,
bool isRef,
bool verifyEscapeSafety,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(op1 != null);
Expand Down Expand Up @@ -1538,21 +1543,24 @@ private BoundAssignmentOperator BindAssignment(
op2 = BindToNaturalType(op2, diagnostics);
}

if (isRef)
if (verifyEscapeSafety)
{
var leftEscape = GetRefEscape(op1, LocalScopeDepth);
var rightEscape = GetRefEscape(op2, LocalScopeDepth);
if (leftEscape < rightEscape)
if (isRef)
{
Error(diagnostics, ErrorCode.ERR_RefAssignNarrower, node, op1.ExpressionSymbol.Name, op2.Syntax);
op2 = ToBadExpression(op2);
var leftEscape = GetRefEscape(op1, LocalScopeDepth);
var rightEscape = GetRefEscape(op2, LocalScopeDepth);
if (leftEscape < rightEscape)
{
Error(diagnostics, ErrorCode.ERR_RefAssignNarrower, node, getName(op1), op2.Syntax);
op2 = ToBadExpression(op2);
}
}
}

if (op1.Type.IsRefLikeType)
{
var leftEscape = GetValEscape(op1, LocalScopeDepth);
op2 = ValidateEscape(op2, leftEscape, isByRef: false, diagnostics);
if (op1.Type.IsRefLikeType)
{
var leftEscape = GetValEscape(op1, LocalScopeDepth);
op2 = ValidateEscape(op2, leftEscape, isByRef: false, diagnostics);
}
}
}
else
Expand All @@ -1573,6 +1581,25 @@ private BoundAssignmentOperator BindAssignment(
}

return new BoundAssignmentOperator(node, op1, op2, isRef, type, hasErrors);

static object getName(BoundExpression expr)
{
if (expr.ExpressionSymbol is { Name: var name })
{
return name;
}
if (expr is BoundArrayAccess)
{
return MessageID.IDS_ArrayAccess.Localize();
}
if (expr is BoundPointerElementAccess)
{
return MessageID.IDS_PointerElementAccess.Localize();
}

Debug.Assert(false);
return "";
}
}

internal static PropertySymbol GetPropertySymbol(BoundExpression expr, out BoundExpression receiver, out SyntaxNode propertySyntax)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
Expand Down Expand Up @@ -35,6 +36,19 @@ public static RefKind GetRefKind(this BoundExpression node)
case BoundKind.PropertyAccess:
return ((BoundPropertyAccess)node).PropertySymbol.RefKind;

case BoundKind.ObjectInitializerMember:
var member = (BoundObjectInitializerMember)node;
if (member.HasErrors)
return RefKind.None;

return member.MemberSymbol switch
{
FieldSymbol f => f.RefKind,
PropertySymbol f => f.RefKind,
EventSymbol => RefKind.None,
var s => throw ExceptionUtilities.UnexpectedValue(s?.Kind)
};

default:
return RefKind.None;
}
Expand Down
6 changes: 6 additions & 0 deletions src/Compilers/CSharp/Portable/CSharpResources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -7181,4 +7181,10 @@ To remove the warning, you can use /reference instead (set the Embed Interop Typ
<data name="IDS_FeatureFileTypes" xml:space="preserve">
<value>file types</value>
</data>
<data name="IDS_ArrayAccess" xml:space="preserve">
<value>array access</value>
</data>
<data name="IDS_PointerElementAccess" xml:space="preserve">
<value>pointer element access</value>
</data>
</root>
2 changes: 2 additions & 0 deletions src/Compilers/CSharp/Portable/Errors/MessageID.cs
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,8 @@ internal enum MessageID
IDS_FeatureRequiredMembers = MessageBase + 12825,
IDS_FeatureRefFields = MessageBase + 12826,
IDS_FeatureFileTypes = MessageBase + 12827,
IDS_ArrayAccess = MessageBase + 12828,
IDS_PointerElementAccess = MessageBase + 12829,
}

// Message IDs may refer to strings that need to be localized.
Expand Down
15 changes: 12 additions & 3 deletions src/Compilers/CSharp/Portable/Parser/LanguageParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12753,23 +12753,32 @@ private ExpressionSyntax ParseObjectOrCollectionInitializerMember(ref bool isObj
{
if (this.IsComplexElementInitializer())
{
// { ... }
return this.ParseComplexElementInitializer();
}
else if (IsDictionaryInitializer())
{
// [...] = { ... }
// [...] = ref <expr>
// [...] = <expr>
isObjectInitializer = true;
var initializer = this.ParseDictionaryInitializer();
initializer = CheckFeatureAvailability(initializer, MessageID.IDS_FeatureDictionaryInitializer);
return initializer;
}
else if (this.IsNamedAssignment())
{
// Name = { ... }
// Name = ref <expr>
// Name = <expr>
isObjectInitializer = true;
return this.ParseObjectInitializerNamedAssignment();
}
else
{
return this.ParseExpressionCore();
// <expr>
// ref <expr>
Copy link
Member Author

@jcouv jcouv Jul 14, 2022

Choose a reason for hiding this comment

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

📝 This case and the dictionary initializer case above remain errors in binding, but the parser now tolerates ref (more graceful failure). #Resolved

return this.ParsePossibleRefExpression();
}
}

Expand All @@ -12793,7 +12802,7 @@ private ExpressionSyntax ParseObjectInitializerNamedAssignment()
}
else
{
expression = this.ParseExpressionCore();
expression = this.ParsePossibleRefExpression();
}

return _syntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, identifier, equal, expression);
Expand All @@ -12805,7 +12814,7 @@ private ExpressionSyntax ParseDictionaryInitializer()
var equal = this.EatToken(SyntaxKind.EqualsToken);
var expression = this.CurrentToken.Kind == SyntaxKind.OpenBraceToken
? this.ParseObjectOrCollectionInitializer()
: this.ParseExpressionCore();
: this.ParsePossibleRefExpression();

var elementAccess = _syntaxFactory.ImplicitElementAccess(arguments);
return _syntaxFactory.AssignmentExpression(
Expand Down
10 changes: 10 additions & 0 deletions src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions src/Compilers/CSharp/Portable/xlf/CSharpResources.de.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions src/Compilers/CSharp/Portable/xlf/CSharpResources.es.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions src/Compilers/CSharp/Portable/xlf/CSharpResources.fr.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions src/Compilers/CSharp/Portable/xlf/CSharpResources.it.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading