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

Add CompilerGeneratedAttribute to record members #58542

Merged
merged 13 commits into from
Feb 8, 2022
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.PooledObjects;

namespace Microsoft.CodeAnalysis.CSharp.Symbols
Expand Down Expand Up @@ -55,6 +57,15 @@ internal override void GenerateMethodBodyStatements(SyntheticBoundNodeFactory F,
}
}

internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedAttributes(moduleBuilder, ref attributes);
Debug.Assert(IsImplicitlyDeclared);
var compilation = this.DeclaringCompilation;
AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor));
Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor));
}
Comment on lines +60 to +67
Copy link
Member Author

Choose a reason for hiding this comment

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

I can see a room for refactoring, since this block is repeated in many places (not only in this PR - but over the codebase)

For example, we can have a virtual property in Symbol:

protected virtual bool SynthesizeCompilerGeneratedAttribute => false;

and in the already-existing empty virtual AddSynthesizedAttributes method:

if (SynthesizeCompilerGeneratedAttribute)
{
    // Add this repeated code block here.
}

Let me know if the refactoring worth it, and (if yes) whether you want it in this PR or a separate one.


internal static MethodSymbol? FindCopyConstructor(NamedTypeSymbol containingType, NamedTypeSymbol within, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
MethodSymbol? bestCandidate = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Symbols
Expand Down Expand Up @@ -73,5 +75,14 @@ protected sealed override (TypeWithAnnotations ReturnType, ImmutableArray<Parame
}

protected override int GetParameterCountFromSyntax() => 2;

internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedAttributes(moduleBuilder, ref attributes);
Debug.Assert(IsImplicitlyDeclared);
var compilation = this.DeclaringCompilation;
AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor));
Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
// See the LICENSE file in the project root for more information.

using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Symbols
Expand Down Expand Up @@ -60,6 +63,15 @@ protected sealed override void CheckConstraintsForExplicitInterfaceType(Conversi
{
}

internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedAttributes(moduleBuilder, ref attributes);
Debug.Assert(IsImplicitlyDeclared);
var compilation = this.DeclaringCompilation;
AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor));
Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor));
}

protected sealed override SourceMemberMethodSymbol? BoundAttributesSource => null;

internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() => OneOrMany.Create(default(SyntaxList<AttributeListSyntax>));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12896,14 +12896,16 @@ protected virtual bool PrintMembers(System.Text.StringBuilder builder)
Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), // R.PrintMembers
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(21, TableIndex.CustomAttribute, EditAndContinueOperation.Default));

CheckEncMap(reader1,
Handle(20, TableIndex.TypeRef),
Handle(21, TableIndex.TypeRef),
Handle(22, TableIndex.TypeRef),
Handle(10, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(21, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,279 @@ internal class C2<[Attr] T2> { }
Assert.Equal(new[] { "Attr" }, GetAttributeNames(typeParam.GetAttributes()));
}

[Fact]
[WorkItem(46439, "https://github.com/dotnet/roslyn/issues/46439")]
public void RecordSynthesizedMembers()
Copy link
Member

Choose a reason for hiding this comment

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

Do we have tests validating the behavior when the CompilerGenerated attribute is missing?

Copy link
Member Author

Choose a reason for hiding this comment

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

@jaredpar I added the test, but I'm not sure if there is an existing test already somewhere.

Copy link
Member

Choose a reason for hiding this comment

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

There seems to be a legitimate test failure with AttributeTests_Synthesized.AttributeIsMissing

Copy link
Member Author

Choose a reason for hiding this comment

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

@jcouv I'm not familiar with PEVerify issues/failures. Should I skip verification or there is something else to do?

{
string source = @"
record R
{
public int MyProperty { get; }
}
";
CompileAndVerify(source, symbolValidator: validate, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));

static void validate(ModuleSymbol module)
{
var record = module.GlobalNamespace.GetTypeMember("R");
Assert.Equal(15, record.GetMembers().Length); // If a new record member is added, extend the test with its behavior regarding CompilerGeneratedAttribute.

var equalityContractGetter = record.GetMember("get_EqualityContract");
validateCompilerGeneratedAttribute(equalityContractGetter);

var toString = record.GetMember(WellKnownMemberNames.ObjectToString);
validateCompilerGeneratedAttribute(toString);

var printMembers = record.GetMember(WellKnownMemberNames.PrintMembersMethodName);
validateCompilerGeneratedAttribute(printMembers);

var op_Equality = record.GetMember(WellKnownMemberNames.EqualityOperatorName);
validateCompilerGeneratedAttribute(op_Equality);

var op_Inequality = record.GetMember(WellKnownMemberNames.InequalityOperatorName);
validateCompilerGeneratedAttribute(op_Inequality);

var getHashCode = record.GetMember(WellKnownMemberNames.ObjectGetHashCode);
validateCompilerGeneratedAttribute(getHashCode);

var equals = record.GetMembers(WellKnownMemberNames.ObjectEquals);
Assert.Equal(2, equals.Length);
validateCompilerGeneratedAttribute(equals[0]);
validateCompilerGeneratedAttribute(equals[1]);

var clone = record.GetMember(WellKnownMemberNames.CloneMethodName);
validateCompilerGeneratedAttribute(clone);

var ctor = record.GetMembers(WellKnownMemberNames.InstanceConstructorName);
Assert.Equal(2, ctor.Length);
Assert.Equal(1, ctor[0].GetParameters().Length); // copy constructor
Copy link
Member

Choose a reason for hiding this comment

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

nit: you could do Assert.Equal("....", ctor[0].ToTestDisplayString()); instead

Copy link
Member Author

Choose a reason for hiding this comment

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

@jcouv I addressed the comment in last commit.

validateCompilerGeneratedAttribute(ctor[0]); // should have attribute.
Assert.Empty(ctor[1].GetParameters()); // parameterless constructor
Assert.Empty(ctor[1].GetAttributes()); // shouldn't have attribute.

var equalityContract = record.GetMember("EqualityContract");
Assert.Empty(equalityContract.GetAttributes());

var myProperty = record.GetMember("MyProperty");
Assert.Empty(myProperty.GetAttributes());

var myPropertyGetter = record.GetMember("get_MyProperty");
validateCompilerGeneratedAttribute(myPropertyGetter);

var myPropertyBackingField = record.GetMember("<MyProperty>k__BackingField");
validateCompilerGeneratedAttribute(myPropertyBackingField);
}

static void validateCompilerGeneratedAttribute(Symbol symbol)
{
var attributeNames = GetAttributeNames(symbol.GetAttributes());
Assert.Contains("CompilerGeneratedAttribute", attributeNames);
}
}

[Fact]
[WorkItem(46439, "https://github.com/dotnet/roslyn/issues/46439")]
public void RecordStructSynthesizedMembers()
{
string source = @"
record struct R
{
public int MyProperty { get; }
}
";
CompileAndVerify(source, symbolValidator: validate, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));

static void validate(ModuleSymbol module)
{
var record = module.GlobalNamespace.GetTypeMember("R");
Assert.Equal(11, record.GetMembers().Length); // If a new record member is added, extend the test with its behavior regarding CompilerGeneratedAttribute.

var toString = record.GetMember(WellKnownMemberNames.ObjectToString);
validateCompilerGeneratedAttribute(toString);

var printMembers = record.GetMember(WellKnownMemberNames.PrintMembersMethodName);
validateCompilerGeneratedAttribute(printMembers);

var op_Equality = record.GetMember(WellKnownMemberNames.EqualityOperatorName);
validateCompilerGeneratedAttribute(op_Equality);

var op_Inequality = record.GetMember(WellKnownMemberNames.InequalityOperatorName);
validateCompilerGeneratedAttribute(op_Inequality);

var getHashCode = record.GetMember(WellKnownMemberNames.ObjectGetHashCode);
validateCompilerGeneratedAttribute(getHashCode);

var equals = record.GetMembers(WellKnownMemberNames.ObjectEquals);
Assert.Equal(2, equals.Length);
validateCompilerGeneratedAttribute(equals[0]);
validateCompilerGeneratedAttribute(equals[1]);

var ctor = record.GetMember(WellKnownMemberNames.InstanceConstructorName);
Assert.Empty(ctor.GetAttributes());

var myProperty = record.GetMember("MyProperty");
Assert.Empty(myProperty.GetAttributes());

var myPropertyGetter = record.GetMember("get_MyProperty");
validateCompilerGeneratedAttribute(myPropertyGetter);

var myPropertyBackingField = record.GetMember("<MyProperty>k__BackingField");
validateCompilerGeneratedAttribute(myPropertyBackingField);
}

static void validateCompilerGeneratedAttribute(Symbol symbol)
{
var attributeNames = GetAttributeNames(symbol.GetAttributes());
Assert.Contains("CompilerGeneratedAttribute", attributeNames);
}
}

[Fact]
[WorkItem(46439, "https://github.com/dotnet/roslyn/issues/46439")]
public void RecordSynthesizedMembers_2()
{
string source = @"
record R(int P1);

namespace System.Runtime.CompilerServices
{
public static class IsExternalInit { }
}
";
// [ : R::set_P1] Cannot change initonly field outside its .ctor.
CompileAndVerify(source,
symbolValidator: validate,
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
verify: ExecutionConditionUtil.IsCoreClr ? Verification.Passes : Verification.Fails);

static void validate(ModuleSymbol module)
{
var record = module.GlobalNamespace.GetTypeMember("R");
Assert.Equal(17, record.GetMembers().Length); // If a new record member is added, extend the test with its behavior regarding CompilerGeneratedAttribute.

var p1_backingField = record.GetMember("<P1>k__BackingField");
validateCompilerGeneratedAttribute(p1_backingField);

var equalityContractGetter = record.GetMember("get_EqualityContract");
validateCompilerGeneratedAttribute(equalityContractGetter);

var get_P1 = record.GetMember("get_P1");
validateCompilerGeneratedAttribute(get_P1);

var set_P1 = record.GetMember("set_P1");
validateCompilerGeneratedAttribute(set_P1);

var toString = record.GetMember(WellKnownMemberNames.ObjectToString);
validateCompilerGeneratedAttribute(toString);

var printMembers = record.GetMember(WellKnownMemberNames.PrintMembersMethodName);
validateCompilerGeneratedAttribute(printMembers);

var op_Equality = record.GetMember(WellKnownMemberNames.EqualityOperatorName);
validateCompilerGeneratedAttribute(op_Equality);

var op_Inequality = record.GetMember(WellKnownMemberNames.InequalityOperatorName);
validateCompilerGeneratedAttribute(op_Inequality);

var getHashCode = record.GetMember(WellKnownMemberNames.ObjectGetHashCode);
validateCompilerGeneratedAttribute(getHashCode);

var equals = record.GetMembers(WellKnownMemberNames.ObjectEquals);
Assert.Equal(2, equals.Length);
validateCompilerGeneratedAttribute(equals[0]);
validateCompilerGeneratedAttribute(equals[1]);

var clone = record.GetMember(WellKnownMemberNames.CloneMethodName);
validateCompilerGeneratedAttribute(clone);

var ctor = record.GetMembers(WellKnownMemberNames.InstanceConstructorName);
Assert.Equal(2, ctor.Length);
Assert.Equal("R..ctor(System.Int32 P1)", ctor[0].ToTestDisplayString());
Assert.Equal("R..ctor(R original)", ctor[1].ToTestDisplayString());
validateCompilerGeneratedAttribute(ctor[1]);
Assert.Empty(ctor[0].GetAttributes());

var deconstruct = record.GetMember(WellKnownMemberNames.DeconstructMethodName);
validateCompilerGeneratedAttribute(deconstruct);

var equalityContract = record.GetMember("EqualityContract");
Assert.Empty(equalityContract.GetAttributes());

var p1 = record.GetMember("P1");
Assert.Empty(p1.GetAttributes());
}

static void validateCompilerGeneratedAttribute(Symbol symbol)
{
var attributeNames = GetAttributeNames(symbol.GetAttributes());
Assert.Contains("CompilerGeneratedAttribute", attributeNames);
}
}

[Fact]
[WorkItem(46439, "https://github.com/dotnet/roslyn/issues/46439")]
public void RecordStructSynthesizedMembers_2()
{
string source = @"
record struct R(int P1);
";
CompileAndVerify(source, symbolValidator: validate, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));

void validate(ModuleSymbol module)
{
var record = module.GlobalNamespace.GetTypeMember("R");
Assert.Equal(14, record.GetMembers().Length); // If a new record member is added, extend the test with its behavior regarding CompilerGeneratedAttribute.

var p1_backingField = record.GetMember("<P1>k__BackingField");
validateCompilerGeneratedAttribute(p1_backingField);

var ctor = record.GetMembers(WellKnownMemberNames.InstanceConstructorName);
Assert.Equal(2, ctor.Length);
Assert.Equal("R..ctor()", ctor[0].ToTestDisplayString());
Assert.Equal("R..ctor(System.Int32 P1)", ctor[1].ToTestDisplayString());
Assert.Empty(ctor[0].GetAttributes());
Assert.Empty(ctor[1].GetAttributes());

var get_P1 = record.GetMember("get_P1");
validateCompilerGeneratedAttribute(get_P1);

var set_P1 = record.GetMember("set_P1");
validateCompilerGeneratedAttribute(set_P1);

var toString = record.GetMember(WellKnownMemberNames.ObjectToString);
validateCompilerGeneratedAttribute(toString);

var printMembers = record.GetMember(WellKnownMemberNames.PrintMembersMethodName);
validateCompilerGeneratedAttribute(printMembers);

var op_Equality = record.GetMember(WellKnownMemberNames.EqualityOperatorName);
validateCompilerGeneratedAttribute(op_Equality);

var op_Inequality = record.GetMember(WellKnownMemberNames.InequalityOperatorName);
validateCompilerGeneratedAttribute(op_Inequality);

var getHashCode = record.GetMember(WellKnownMemberNames.ObjectGetHashCode);
validateCompilerGeneratedAttribute(getHashCode);

var equals = record.GetMembers(WellKnownMemberNames.ObjectEquals);
Assert.Equal(2, equals.Length);
validateCompilerGeneratedAttribute(equals[0]);
validateCompilerGeneratedAttribute(equals[1]);

var deconstruct = record.GetMember(WellKnownMemberNames.DeconstructMethodName);
validateCompilerGeneratedAttribute(deconstruct);

var p1 = record.GetMember("P1");
Assert.Empty(p1.GetAttributes());
}

void validateCompilerGeneratedAttribute(Symbol symbol)
{
var attributeNames = GetAttributeNames(symbol.GetAttributes());
Assert.Contains("CompilerGeneratedAttribute", attributeNames);
}
}

#endregion

#region CompilationRelaxationsAttribute, RuntimeCompatibilityAttribute, DebuggableAttribute
Expand Down
17 changes: 0 additions & 17 deletions src/Compilers/CSharp/Test/Symbol/Symbols/Source/RecordTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1804,22 +1804,5 @@ static void Main()
CompileAndVerify(src1 + src2 + src3, expectedOutput: "C { Y = 22, X = 11, U = 44, Z = 33 }").VerifyDiagnostics();
CompileAndVerify(new[] { src1, src2, src3 }, expectedOutput: "C { Y = 22, X = 11, U = 44, Z = 33 }").VerifyDiagnostics();
}

[Fact]
public void EqualityContractGetter_CompilerGeneratedAttribute()
{
var verifier = CompileAndVerify(@"
using System;

record C;
", symbolValidator: validate);

static void validate(ModuleSymbol module)
{
var member = module.GlobalNamespace.GetTypeMember("C").GetMember("get_EqualityContract");
var attributes = member.GetAttributes();
Assert.Equal(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(attributes));
}
}
}
}