Skip to content

Commit

Permalink
Bind and emit lambda attributes (#52178)
Browse files Browse the repository at this point in the history
  • Loading branch information
cston authored Apr 14, 2021
1 parent 4463994 commit 9a800bf
Show file tree
Hide file tree
Showing 54 changed files with 1,655 additions and 221 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
Expand All @@ -31,6 +32,7 @@ public QueryUnboundLambdaState(Binder binder, RangeVariableMap rangeVariableMap,

public override string ParameterName(int index) { return _parameters[index].Name; }
public override bool ParameterIsDiscard(int index) { return false; }
public override SyntaxList<AttributeListSyntax> ParameterAttributes(int index) => default;
public override bool HasNames { get { return true; } }
public override bool HasSignature { get { return true; } }
public override bool HasExplicitlyTypedParameterList { get { return false; } }
Expand Down
39 changes: 32 additions & 7 deletions src/Compilers/CSharp/Portable/Binder/Binder_Lambda.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.PooledObjects;

namespace Microsoft.CodeAnalysis.CSharp
Expand Down Expand Up @@ -42,12 +41,18 @@ private UnboundLambda AnalyzeAnonymousFunction(
var names = default(ImmutableArray<string>);
var refKinds = default(ImmutableArray<RefKind>);
var types = default(ImmutableArray<TypeWithAnnotations>);
var attributes = default(ImmutableArray<SyntaxList<AttributeListSyntax>>);

var namesBuilder = ArrayBuilder<string>.GetInstance();
ImmutableArray<bool> discardsOpt = default;
SeparatedSyntaxList<ParameterSyntax>? parameterSyntaxList = null;
bool hasSignature;

if (syntax is LambdaExpressionSyntax lambdaSyntax)
{
checkAttributes(syntax, lambdaSyntax.AttributeLists, diagnostics);
}

switch (syntax.Kind())
{
default:
Expand Down Expand Up @@ -87,6 +92,7 @@ private UnboundLambda AnalyzeAnonymousFunction(

var typesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance();
var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance();
var attributesBuilder = ArrayBuilder<SyntaxList<AttributeListSyntax>>.GetInstance();

// In the batch compiler case we probably should have given a syntax error if the
// user did something like (int x, y)=>x+y -- but in the IDE scenario we might be in
Expand All @@ -104,10 +110,7 @@ private UnboundLambda AnalyzeAnonymousFunction(
underscoresCount++;
}

foreach (var attributeList in p.AttributeLists)
{
Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, attributeList);
}
checkAttributes(syntax, p.AttributeLists, diagnostics);

if (p.Default != null)
{
Expand Down Expand Up @@ -167,6 +170,7 @@ private UnboundLambda AnalyzeAnonymousFunction(
namesBuilder.Add(p.Identifier.ValueText);
typesBuilder.Add(type);
refKindsBuilder.Add(refKind);
attributesBuilder.Add(syntax.Kind() == SyntaxKind.ParenthesizedLambdaExpression ? p.AttributeLists : default);
}

discardsOpt = computeDiscards(parameterSyntaxList.Value, underscoresCount);
Expand All @@ -181,8 +185,14 @@ private UnboundLambda AnalyzeAnonymousFunction(
refKinds = refKindsBuilder.ToImmutable();
}

if (attributesBuilder.Any(a => a.Count > 0))
{
attributes = attributesBuilder.ToImmutable();
}

typesBuilder.Free();
refKindsBuilder.Free();
attributesBuilder.Free();
}

if (hasSignature)
Expand All @@ -192,7 +202,7 @@ private UnboundLambda AnalyzeAnonymousFunction(

namesBuilder.Free();

return new UnboundLambda(syntax, this, diagnostics.AccumulatesDependencies, refKinds, types, names, discardsOpt, isAsync, isStatic);
return new UnboundLambda(syntax, this, diagnostics.AccumulatesDependencies, attributes, refKinds, types, names, discardsOpt, isAsync, isStatic);

static ImmutableArray<bool> computeDiscards(SeparatedSyntaxList<ParameterSyntax> parameters, int underscoresCount)
{
Expand All @@ -210,9 +220,24 @@ static ImmutableArray<bool> computeDiscards(SeparatedSyntaxList<ParameterSyntax>

return discardsBuilder.ToImmutableAndFree();
}

static void checkAttributes(AnonymousFunctionExpressionSyntax syntax, SyntaxList<AttributeListSyntax> attributeLists, BindingDiagnosticBag diagnostics)
{
foreach (var attributeList in attributeLists)
{
if (syntax.Kind() == SyntaxKind.ParenthesizedLambdaExpression)
{
MessageID.IDS_FeatureLambdaAttributes.CheckFeatureAvailability(diagnostics, attributeList);
}
else
{
Error(diagnostics, syntax.Kind() == SyntaxKind.SimpleLambdaExpression ? ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression : ErrorCode.ERR_AttributesNotAllowed, attributeList);
}
}
}
}

private void CheckParenthesizedLambdaParameters(
private static void CheckParenthesizedLambdaParameters(
SeparatedSyntaxList<ParameterSyntax> parameterSyntaxList, BindingDiagnosticBag diagnostics)
{
if (parameterSyntaxList.Count > 0)
Expand Down
19 changes: 17 additions & 2 deletions src/Compilers/CSharp/Portable/BoundTree/UnboundLambda.cs
Original file line number Diff line number Diff line change
Expand Up @@ -344,13 +344,14 @@ public UnboundLambda(
CSharpSyntaxNode syntax,
Binder binder,
bool withDependencies,
ImmutableArray<SyntaxList<AttributeListSyntax>> attributes,
ImmutableArray<RefKind> refKinds,
ImmutableArray<TypeWithAnnotations> types,
ImmutableArray<string> names,
ImmutableArray<bool> discardsOpt,
bool isAsync,
bool isStatic)
: this(syntax, new PlainUnboundLambdaState(binder, names, discardsOpt, types, refKinds, isAsync, isStatic, includeCache: true), withDependencies, !types.IsDefault && types.Any(t => t.Type?.Kind == SymbolKind.ErrorType))
: this(syntax, new PlainUnboundLambdaState(binder, attributes, names, discardsOpt, types, refKinds, isAsync, isStatic, includeCache: true), withDependencies, !types.IsDefault && types.Any(t => t.Type?.Kind == SymbolKind.ErrorType))
{
Debug.Assert(binder != null);
Debug.Assert(syntax.IsAnonymousFunction());
Expand Down Expand Up @@ -409,6 +410,7 @@ public TypeWithAnnotations InferReturnType(ConversionsBase conversions, NamedTyp
public bool GenerateSummaryErrors(BindingDiagnosticBag diagnostics) { return Data.GenerateSummaryErrors(diagnostics); }
public bool IsAsync { get { return Data.IsAsync; } }
public bool IsStatic => Data.IsStatic;
public SyntaxList<AttributeListSyntax> ParameterAttributes(int index) { return Data.ParameterAttributes(index); }
public TypeWithAnnotations ParameterTypeWithAnnotations(int index) { return Data.ParameterTypeWithAnnotations(index); }
public TypeSymbol ParameterType(int index) { return ParameterTypeWithAnnotations(index).Type; }
public Location ParameterLocation(int index) { return Data.ParameterLocation(index); }
Expand Down Expand Up @@ -472,6 +474,7 @@ internal UnboundLambdaState WithCaching(bool includeCache)
public abstract MessageID MessageID { get; }
public abstract string ParameterName(int index);
public abstract bool ParameterIsDiscard(int index);
public abstract SyntaxList<AttributeListSyntax> ParameterAttributes(int index);
public abstract bool HasSignature { get; }
public abstract bool HasExplicitlyTypedParameterList { get; }
public abstract int ParameterCount { get; }
Expand Down Expand Up @@ -602,6 +605,9 @@ private BoundLambda ReallyBind(NamedTypeSymbol delegateType)
block = BindLambdaBody(lambdaSymbol, lambdaBodyBinder, diagnostics);
}

// PROTOTYPE: Test that we're reporting diagnostics even in the case where we re-used the lambda above.
lambdaSymbol.GetDeclarationDiagnostics(diagnostics);

if (lambdaSymbol.RefKind == CodeAnalysis.RefKind.RefReadOnly)
{
compilation.EnsureIsReadOnlyAttributeExists(diagnostics, lambdaSymbol.DiagnosticLocation, modifyCompilation: false);
Expand Down Expand Up @@ -676,6 +682,7 @@ internal LambdaSymbol CreateLambdaSymbol(
ImmutableArray<RefKind> parameterRefKinds,
RefKind refKind)
=> new LambdaSymbol(
Binder,
Binder.Compilation,
containingSymbol,
_unboundLambda,
Expand Down Expand Up @@ -1159,6 +1166,7 @@ private static int CanonicallyCompareDiagnostics(Diagnostic x, Diagnostic y)

internal sealed class PlainUnboundLambdaState : UnboundLambdaState
{
private readonly ImmutableArray<SyntaxList<AttributeListSyntax>> _parameterAttributes;
private readonly ImmutableArray<string> _parameterNames;
private readonly ImmutableArray<bool> _parameterIsDiscardOpt;
private readonly ImmutableArray<TypeWithAnnotations> _parameterTypesWithAnnotations;
Expand All @@ -1168,6 +1176,7 @@ internal sealed class PlainUnboundLambdaState : UnboundLambdaState

internal PlainUnboundLambdaState(
Binder binder,
ImmutableArray<SyntaxList<AttributeListSyntax>> parameterAttributes,
ImmutableArray<string> parameterNames,
ImmutableArray<bool> parameterIsDiscardOpt,
ImmutableArray<TypeWithAnnotations> parameterTypesWithAnnotations,
Expand All @@ -1177,6 +1186,7 @@ internal PlainUnboundLambdaState(
bool includeCache)
: base(binder, includeCache)
{
_parameterAttributes = parameterAttributes;
_parameterNames = parameterNames;
_parameterIsDiscardOpt = parameterIsDiscardOpt;
_parameterTypesWithAnnotations = parameterTypesWithAnnotations;
Expand Down Expand Up @@ -1225,6 +1235,11 @@ public override Location ParameterLocation(int index)

private bool IsExpressionLambda { get { return Body.Kind() != SyntaxKind.Block; } }

public override SyntaxList<AttributeListSyntax> ParameterAttributes(int index)
{
return _parameterAttributes.IsDefault ? default : _parameterAttributes[index];
}

public override string ParameterName(int index)
{
Debug.Assert(!_parameterNames.IsDefault && 0 <= index && index < _parameterNames.Length);
Expand All @@ -1251,7 +1266,7 @@ public override TypeWithAnnotations ParameterTypeWithAnnotations(int index)

protected override UnboundLambdaState WithCachingCore(bool includeCache)
{
return new PlainUnboundLambdaState(Binder, _parameterNames, _parameterIsDiscardOpt, _parameterTypesWithAnnotations, _parameterRefKinds, _isAsync, _isStatic, includeCache);
return new PlainUnboundLambdaState(Binder, _parameterAttributes, _parameterNames, _parameterIsDiscardOpt, _parameterTypesWithAnnotations, _parameterRefKinds, _isAsync, _isStatic, includeCache);
}

protected override BoundExpression GetLambdaExpressionBody(BoundBlock body)
Expand Down
5 changes: 4 additions & 1 deletion src/Compilers/CSharp/Portable/CSharpResources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -1725,7 +1725,7 @@ If such a class is used as a base class and if the deriving class defines a dest
<value>Alias '{0}' conflicts with {1} definition</value>
</data>
<data name="ERR_ConditionalOnSpecialMethod" xml:space="preserve">
<value>The Conditional attribute is not valid on '{0}' because it is a constructor, destructor, operator, or explicit interface implementation</value>
<value>The Conditional attribute is not valid on '{0}' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation</value>
</data>
<data name="ERR_ConditionalMustReturnVoid" xml:space="preserve">
<value>The Conditional attribute is not valid on '{0}' because its return type is not void</value>
Expand Down Expand Up @@ -3941,6 +3941,9 @@ You should consider suppressing the warning only if you're sure that you don't w
<data name="ERR_AttributesNotAllowed" xml:space="preserve">
<value>Attributes are not valid in this context.</value>
</data>
<data name="ERR_AttributesRequireParenthesizedLambdaExpression" xml:space="preserve">
<value>Attributes on lambda expressions require a parenthesized parameter list.</value>
</data>
<data name="ERR_ExternAliasNotAllowed" xml:space="preserve">
<value>'extern alias' is not valid in this context</value>
</data>
Expand Down
4 changes: 2 additions & 2 deletions src/Compilers/CSharp/Portable/Errors/ErrorCode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

namespace Microsoft.CodeAnalysis.CSharp
{
internal enum ErrorCode
Expand Down Expand Up @@ -1932,6 +1930,8 @@ internal enum ErrorCode

#endregion diagnostics introduced for C# 9.0

ERR_AttributesRequireParenthesizedLambdaExpression = 8916,

// Note: you will need to re-generate compiler code after adding warnings (eng\generate-compiler-code.cmd)
}
}
2 changes: 1 addition & 1 deletion src/Compilers/CSharp/Portable/Errors/MessageID.cs
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ internal static LanguageVersion RequiredVersion(this MessageID feature)
{
// C# preview features.
case MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction:
case MessageID.IDS_FeatureLambdaAttributes:
case MessageID.IDS_FeatureLambdaAttributes: // semantic check
return LanguageVersion.Preview;

// C# 9.0 features.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6247,6 +6247,8 @@ protected LambdaExpressionSyntax(ObjectReader reader)
{
}

public abstract Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList<AttributeListSyntax> AttributeLists { get; }

/// <summary>SyntaxToken representing equals greater than.</summary>
public abstract SyntaxToken ArrowToken { get; }
}
Expand Down Expand Up @@ -6352,7 +6354,7 @@ internal SimpleLambdaExpressionSyntax(SyntaxKind kind, GreenNode? attributeLists
}
}

public Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList<AttributeListSyntax> AttributeLists => new Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList<AttributeListSyntax>(this.attributeLists);
public override Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList<AttributeListSyntax> AttributeLists => new Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList<AttributeListSyntax>(this.attributeLists);
public override Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList<SyntaxToken> Modifiers => new Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList<SyntaxToken>(this.modifiers);
/// <summary>ParameterSyntax node representing the parameter of the lambda expression.</summary>
public ParameterSyntax Parameter => this.parameter;
Expand Down Expand Up @@ -6663,7 +6665,7 @@ internal ParenthesizedLambdaExpressionSyntax(SyntaxKind kind, GreenNode? attribu
}
}

public Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList<AttributeListSyntax> AttributeLists => new Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList<AttributeListSyntax>(this.attributeLists);
public override Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList<AttributeListSyntax> AttributeLists => new Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList<AttributeListSyntax>(this.attributeLists);
public override Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList<SyntaxToken> Modifiers => new Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList<SyntaxToken>(this.modifiers);
/// <summary>ParameterListSyntax node representing the list of parameters for the lambda expression.</summary>
public ParameterListSyntax ParameterList => this.parameterList;
Expand Down
Loading

0 comments on commit 9a800bf

Please sign in to comment.