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

Handle synthesized delegates without refKinds #58802

Merged
merged 5 commits into from
Jan 13, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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 @@ -359,6 +359,9 @@ internal static string MakeDynamicCallSiteFieldName(int uniqueId)
/// Produces name of the synthesized delegate symbol that encodes the parameter byref-ness and return type of the delegate.
/// The arity is appended via `N suffix in MetadataName calculation since the delegate is generic.
/// </summary>
/// <remarks>
/// Logic here should match <see cref="TryParseSynthesizedDelegateName" /> below.
/// </remarks>
internal static string MakeSynthesizedDelegateName(RefKindVector byRefs, bool returnsVoid, int generation)
{
var pooledBuilder = PooledStringBuilder.GetInstance();
Expand All @@ -375,6 +378,12 @@ internal static string MakeSynthesizedDelegateName(RefKindVector byRefs, bool re
return pooledBuilder.ToStringAndFree();
}

/// <summary>
/// Parses the name of a synthesized delegate out into the things it represents.
/// </summary>
/// <remarks>
/// Logic here should match <see cref="MakeSynthesizedDelegateName" /> below.
davidwengier marked this conversation as resolved.
Show resolved Hide resolved
/// </remarks>
internal static bool TryParseSynthesizedDelegateName(string name, out RefKindVector byRefs, out bool returnsVoid, out int generation, out int parameterCount)
{
byRefs = default;
Expand All @@ -390,39 +399,43 @@ internal static bool TryParseSynthesizedDelegateName(string name, out RefKindVec
return false;
}

// The character after the prefix should be an open brace
if (name[DelegateNamePrefixLength] != '{')
{
return false;
}

parameterCount = arity - (returnsVoid ? 0 : 1);

var lastBraceIndex = name.LastIndexOf('}');
if (lastBraceIndex < 0)
// If there are no ref kinds encoded
// (and therefore no braces), use the end of the prefix instead.
var nameEndIndex = name.LastIndexOf('}');
if (nameEndIndex < 0)
{
return false;
nameEndIndex = DelegateNamePrefixLength - 1;
}
else
{
// There should be a character after the prefix, and it should be an open brace
if (name.Length <= DelegateNamePrefixLength || name[DelegateNamePrefixLength] != '{')
{
return false;
}

// The ref kind string is between the two braces
var refKindString = name[DelegateNamePrefixLengthWithOpenBrace..lastBraceIndex];
// If there are braces, then the ref kind string is encoded between them
var refKindString = name[DelegateNamePrefixLengthWithOpenBrace..nameEndIndex];

if (!RefKindVector.TryParse(refKindString, arity, out byRefs))
{
return false;
if (!RefKindVector.TryParse(refKindString, arity, out byRefs))
{
return false;
}
}

// If there is a generation index it will be directly after the brace, otherwise the brace
// is the last character
if (lastBraceIndex < name.Length - 1)
if (nameEndIndex < name.Length - 1)
{
// Format is a '#' followed by the generation number
if (name[lastBraceIndex + 1] != '#')
if (name[nameEndIndex + 1] != '#')
{
return false;
}

if (!int.TryParse(name[(lastBraceIndex + 2)..], out generation))
if (!int.TryParse(name[(nameEndIndex + 2)..], out generation))
{
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1621,6 +1621,61 @@ static unsafe void F<U>() where U : unmanaged
Diagnostic(ErrorCode.ERR_EncUpdateFailedDelegateTypeChanged).WithLocation(1, 1));
}

[Fact]
public void Lambda_SynthesizedDeletage_06()
{
var source0 = MarkedSource(
@"class C
{
void F()
{
var x = <N:0>(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8, int p9, int p10, int p11, int p12, int p13, int p14, int p15, int p16, int p17) => 1</N:0>;
}
}");
var source1 = MarkedSource(
@"class C
{
void F()
{
var x = <N:0>(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8, int p9, int p10, int p11, int p12, int p13, int p14, int p15, int p16, int p17) => 1</N:0>;

System.Console.WriteLine(1);
}
}");

var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);

var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;

var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);

CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>F`18", "C", "<>c");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "F", ".ctor", ".cctor", ".ctor", "<F>b__0_0");

var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));

// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };

EncValidation.VerifyModuleMvid(1, reader0, reader1);

CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F", "<F>b__0_0");

diff1.VerifySynthesizedMembers(
"C.<>c: {<>9__0_0, <F>b__0_0}",
"C: {<>c}");
}

[WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")]
[Fact]
public void PartialMethod()
Expand Down
48 changes: 48 additions & 0 deletions src/Compilers/CSharp/Test/Emit/Emit/GeneratedNamesTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Microsoft.CodeAnalysis.CSharp.Symbols;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit
{
public class GeneratedNamesTests
{
[Theory]
[InlineData("<>A", true, 0, 0)]
[InlineData("<>A{00010000}`8", true, 0, 8)]
[InlineData("<>A`5", true, 0, 5)]
[InlineData("<>A`18", true, 0, 18)]
[InlineData("<>F`1", false, 0, 0)]
[InlineData("<>F`6", false, 0, 5)]
[InlineData("<>F`19", false, 0, 18)]
[InlineData("<>F#3`19", false, 3, 18)]
Copy link
Member

@cston cston Jan 12, 2022

Choose a reason for hiding this comment

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

Consider testing

  • "<>F{01}#3`1"
  • "<>F{0,1}`1"
  • "<>A{0,}"
  • "<>A{,1}"

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Just to confirm, you're saying these should be successfully parsed? Currently two of them fail to because RefKindVector.TryParse doesn't like them, and the other two fail on roundtripping because RefKindVector.TryParse and RefKindVector.ToRefKindString aren't really round trippable (Parse will parse something that ToRefKindString will assert on).

I'm happy to fix all of that, just wanted to confirm, and confirm its not overstepping this PR.

public void TryParseSynthesizedDelegateName_Success(string name, bool returnsVoid, int generation, int parameterCount)
{
Assert.True(GeneratedNames.TryParseSynthesizedDelegateName(name, out var actualByRefs, out var actualReturnsVoid, out var actualGeneration, out var actualParameterCount));


Assert.Equal(returnsVoid, actualReturnsVoid);
Assert.Equal(generation, actualGeneration);
Assert.Equal(parameterCount, actualParameterCount);


// We need to strip arity in order to validate round-tripping
name = MetadataHelpers.InferTypeArityAndUnmangleMetadataName(name, out _);
Assert.Equal(name, GeneratedNames.MakeSynthesizedDelegateName(actualByRefs, actualReturnsVoid, actualGeneration));
}
Copy link
Member

Choose a reason for hiding this comment

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

Duplicate blank lines above.


[Theory]
[InlineData("<>D")]
[InlineData("<>A{")]
[InlineData("<>A00}")]
[InlineData("<>ABCDEF")]
[InlineData("<>A{Z}")]
[InlineData("<>A#F")]
Copy link
Member

@cston cston Jan 12, 2022

Choose a reason for hiding this comment

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

Consider testing

  • "<>A{}"
  • "<>A{,}"
  • "<>A#"

public void TryParseSynthesizedDelegateName_Failure(string name)
{
Assert.False(GeneratedNames.TryParseSynthesizedDelegateName(name, out _, out _, out _, out _));
}
}
}