repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest/SimplifyThisOrMe/SimplifyThisOrMeTests.cs
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.SimplifyThisOrMe; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SimplifyThisOrMe { public partial class SimplifyThisOrMeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public SimplifyThisOrMeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpSimplifyThisOrMeDiagnosticAnalyzer(), new CSharpSimplifyThisOrMeCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] public async Task TestSimplifyDiagnosticId() { await TestInRegularAndScriptAsync( @" using System; class C { private int x = 0; public void z() { var a = [|this.x|]; } }", @" using System; class C { private int x = 0; public void z() { var a = x; } }"); } [WorkItem(6682, "https://github.com/dotnet/roslyn/issues/6682")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] public async Task TestThisWithNoType() { await TestInRegularAndScriptAsync( @"class Program { dynamic x = 7; static void Main(string[] args) { [|this|].x = default(dynamic); } }", @"class Program { dynamic x = 7; static void Main(string[] args) { x = default(dynamic); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] public async Task TestAppropriateDiagnosticOnMissingQualifier() { await TestDiagnosticInfoAsync( @"class C { int SomeProperty { get; set; } void M() { [|this|].SomeProperty = 1; } }", options: Option(CodeStyleOptions2.QualifyPropertyAccess, false, NotificationOption2.Warning), diagnosticId: IDEDiagnosticIds.RemoveQualificationDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_RemoveThis() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = {|FixAllInSolution:this.x|}; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB2 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB3 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x; System.Int16 s1 = y; System.Int32 i2 = z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x2; System.Int16 s1 = y2; System.Int32 i2 = z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x; System.Int16 s1 = y; System.Int32 i2 = z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB2 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x2; System.Int16 s1 = y2; System.Int32 i2 = z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x; System.Int16 s1 = y; System.Int32 i2 = z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB3 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x2; System.Int16 s1 = y2; System.Int32 i2 = z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_RemoveMemberAccessQualification() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { int Property { get; set; } int OtherProperty { get; set; } void M() { {|FixAllInSolution:this.Property|} = 1; var x = this.OtherProperty; } } </Document> <Document> using System; class D { string StringProperty { get; set; } int field; void N() { this.StringProperty = string.Empty; this.field = 0; // ensure qualification isn't removed } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { int Property { get; set; } int OtherProperty { get; set; } void M() { Property = 1; var x = OtherProperty; } } </Document> <Document> using System; class D { string StringProperty { get; set; } int field; void N() { StringProperty = string.Empty; this.field = 0; // ensure qualification isn't removed } } </Document> </Project> </Workspace>"; var options = new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.QualifyPropertyAccess, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Suggestion }, }; await TestInRegularAndScriptAsync( initialMarkup: input, expectedMarkup: expected, options: options); } } }
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.SimplifyThisOrMe; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SimplifyThisOrMe { public partial class SimplifyThisOrMeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public SimplifyThisOrMeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpSimplifyThisOrMeDiagnosticAnalyzer(), new CSharpSimplifyThisOrMeCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] public async Task TestSimplifyDiagnosticId() { await TestInRegularAndScriptAsync( @" using System; class C { private int x = 0; public void z() { var a = [|this.x|]; } }", @" using System; class C { private int x = 0; public void z() { var a = x; } }"); } [WorkItem(6682, "https://github.com/dotnet/roslyn/issues/6682")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] public async Task TestThisWithNoType() { await TestInRegularAndScriptAsync( @"class Program { dynamic x = 7; static void Main(string[] args) { [|this|].x = default(dynamic); } }", @"class Program { dynamic x = 7; static void Main(string[] args) { x = default(dynamic); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] public async Task TestAppropriateDiagnosticOnMissingQualifier() { await TestDiagnosticInfoAsync( @"class C { int SomeProperty { get; set; } void M() { [|this|].SomeProperty = 1; } }", options: Option(CodeStyleOptions2.QualifyPropertyAccess, false, NotificationOption2.Warning), diagnosticId: IDEDiagnosticIds.RemoveQualificationDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_RemoveThis() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = {|FixAllInSolution:this.x|}; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB2 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB3 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x; System.Int16 s1 = y; System.Int32 i2 = z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x2; System.Int16 s1 = y2; System.Int32 i2 = z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x; System.Int16 s1 = y; System.Int32 i2 = z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB2 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x2; System.Int16 s1 = y2; System.Int32 i2 = z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x; System.Int16 s1 = y; System.Int32 i2 = z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB3 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x2; System.Int16 s1 = y2; System.Int32 i2 = z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_RemoveMemberAccessQualification() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { int Property { get; set; } int OtherProperty { get; set; } void M() { {|FixAllInSolution:this.Property|} = 1; var x = this.OtherProperty; } } </Document> <Document> using System; class D { string StringProperty { get; set; } int field; void N() { this.StringProperty = string.Empty; this.field = 0; // ensure qualification isn't removed } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { int Property { get; set; } int OtherProperty { get; set; } void M() { Property = 1; var x = OtherProperty; } } </Document> <Document> using System; class D { string StringProperty { get; set; } int field; void N() { StringProperty = string.Empty; this.field = 0; // ensure qualification isn't removed } } </Document> </Project> </Workspace>"; var options = new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.QualifyPropertyAccess, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Suggestion }, }; await TestInRegularAndScriptAsync( initialMarkup: input, expectedMarkup: expected, options: options); } } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/AddParameterDialog_OutOfProc.cs
// 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.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class AddParameterDialog_OutOfProc : OutOfProcComponent { private readonly AddParameterDialog_InProc _inProc; public AddParameterDialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _inProc = CreateInProcComponent<AddParameterDialog_InProc>(visualStudioInstance); } public void VerifyOpen() => _inProc.VerifyOpen(); public void VerifyClosed() => _inProc.VerifyClosed(); public bool CloseWindow() => _inProc.CloseWindow(); public void ClickOK() => _inProc.ClickOK(); public void ClickCancel() => _inProc.ClickCancel(); public void FillCallSiteField(string callsiteValue) => _inProc.FillCallSiteField(callsiteValue); public void FillNameField(string parameterName) => _inProc.FillNameField(parameterName); public void FillTypeField(string typeName) => _inProc.FillTypeField(typeName); public void SetCallSiteTodo() => _inProc.SetCallSiteTodo(); } }
// 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.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class AddParameterDialog_OutOfProc : OutOfProcComponent { private readonly AddParameterDialog_InProc _inProc; public AddParameterDialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _inProc = CreateInProcComponent<AddParameterDialog_InProc>(visualStudioInstance); } public void VerifyOpen() => _inProc.VerifyOpen(); public void VerifyClosed() => _inProc.VerifyClosed(); public bool CloseWindow() => _inProc.CloseWindow(); public void ClickOK() => _inProc.ClickOK(); public void ClickCancel() => _inProc.ClickCancel(); public void FillCallSiteField(string callsiteValue) => _inProc.FillCallSiteField(callsiteValue); public void FillNameField(string parameterName) => _inProc.FillNameField(parameterName); public void FillTypeField(string typeName) => _inProc.FillTypeField(typeName); public void SetCallSiteTodo() => _inProc.SetCallSiteTodo(); } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Classification/ClassificationExtensions.cs
// 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. namespace Microsoft.CodeAnalysis.Classification { internal static class ClassificationExtensions { public static string? GetClassification(this ITypeSymbol type) => type.TypeKind switch { TypeKind.Class => type.IsRecord ? ClassificationTypeNames.RecordClassName : ClassificationTypeNames.ClassName, TypeKind.Module => ClassificationTypeNames.ModuleName, TypeKind.Struct => type.IsRecord ? ClassificationTypeNames.RecordStructName : ClassificationTypeNames.StructName, TypeKind.Interface => ClassificationTypeNames.InterfaceName, TypeKind.Enum => ClassificationTypeNames.EnumName, TypeKind.Delegate => ClassificationTypeNames.DelegateName, TypeKind.TypeParameter => ClassificationTypeNames.TypeParameterName, TypeKind.Dynamic => ClassificationTypeNames.Keyword, _ => null, }; } }
// 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. namespace Microsoft.CodeAnalysis.Classification { internal static class ClassificationExtensions { public static string? GetClassification(this ITypeSymbol type) => type.TypeKind switch { TypeKind.Class => type.IsRecord ? ClassificationTypeNames.RecordClassName : ClassificationTypeNames.ClassName, TypeKind.Module => ClassificationTypeNames.ModuleName, TypeKind.Struct => type.IsRecord ? ClassificationTypeNames.RecordStructName : ClassificationTypeNames.StructName, TypeKind.Interface => ClassificationTypeNames.InterfaceName, TypeKind.Enum => ClassificationTypeNames.EnumName, TypeKind.Delegate => ClassificationTypeNames.DelegateName, TypeKind.TypeParameter => ClassificationTypeNames.TypeParameterName, TypeKind.Dynamic => ClassificationTypeNames.Keyword, _ => null, }; } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./docs/wiki/images/fig7.png
PNG  IHDR hSsRGBgAMA a pHYsodIDATx^ `T'>oyۿ>Oyo_bA< XnHhmKŅbRj+l$$,dOf& "nIs~gnnn&2Ifs=w9wܹsG7mr[q>|&fӺu:fGևnѓ>UV0vPنfc{gD=̣Sk!GP/~ٶg/n}cTV0sqӿ7jJiM>vqh)3S1VJم5]SKEc$XAhQ735|zeHUfiN״)Xx {(X(fVשu)=22=q.IlP|E 0Z]aj^wDNh'"ŤomphdPg@Bc&48nQK65~D{b Y۬mZ뤞Fi:34dR#j+gLHmzpfYmzp*r,UY/sދtQ%'PUp2Cm6  n^F9pBӚ!Uh&$| >c}tFalV[nZ"pf$Uf D8AH*zj s#nImnZ"pj6eę>#%YB-AO&MYeEpcCE n3S&mPKڌ۬%N!+AZUmPK٨͢'0CS fL@-50;Yv 4 ҘیnW*F`[v~tԄ{]I >2td 4颿̹ﭭ1ڬ63I|Vy7ӃIb(5bMU0B#,55U%f6RZ*Ն\ MHciIJJR)WVV];e 1\a=ILm>ە*ׯW(((P#mqu6GvC5EHg}{,3-FڵKMcY<~ ^=jrZ/)-ՍLच/ZPISz܈vŽ=C;Xx*W"w˝t,Sϊ []R*u6[5U,j:t{I5O%%Y1O'ojMCD%5h^;U^$Q sUZ{{vY]]KM`*$ 0h5{`ޔԌ\Q#Zrct: j n6͊_ݽgݧS 55Z4.=v;Z.119HSf|q c4hS)I2"YQ__GfTCmj܄*]ȟL dfVJjT `nٲ9>~K|||BBBbb b(3N4eUk7nlܴ&E`YY9&2֬m+5hQQkٰy-7ǯݴf t닋@[:]Tu6SX h3$ ߂i9Uș(Alr|kcҖ6Q oʭ]F~a>צfj34,HE;hE-Ml,<;fVhfM~b@?T9CAؼ`֓ۂ3G4mоF<J .Q}90k\Ĉt:}֬v k āT%q9\NWJu{-rr9RN81ֿk-yScEr/ --M1|Yvy,P)`_]vnRRu$TWW:EbjhhEZغuJu\ظq7lؠRvVU*S8M`j7;#2u TRRFZc Vzܧ[4g<P^'QETUEeKJ.R}D͝;/6&n<+VF`EUTʸ?N1ֻۛzm3,S>>X{彯<w/SU9f<=7^kBBMm5eqצ*~)'םl1/UoENvdgoWE#/_pt7d|̸Lcg11ːnltcZru$T!cv_MFUjX};bڪr;W -|{ήc,|fi:_.^n?;ftkDAl3r׾8;p@=hS@%TFL~P3O?4,r %LVL'?wÏi3쫅(L6f*Q1>d_ڬ}3CD>5]Vl"}9mbhKӥ)_):' YJ/^qIm5jjjՈ/P=YBej/E[?qIn8<q/͝@4-۶mSpC6Gr:w;xu݅ VnvZSe$D!&S]xȮm&n>=n=!hj-AGmR4r%>Qv ־r` b"r"!^L˕W +BYZˍs; efFENTxjsrݗҥ&,'@iH#G|ˍ H@&mjnVԹj`E.%>6s"r9km<N K|tzWȖ(BNdÒ>h3qQsa+ qa#gjK둁CYwٲeJ̦MT*wmV^^~uWkT-/Yr!HkdqU_b)Mr!Hlnjǭ!Gk3CBVmƄfY =BnЃ,6 =BnЃ,6 =BnЃ,6 =BnЃ,<CnЃ,6 =DBK=fl+'DD=.}I[NbxxC&Lu2.'!mFoIӳ<o>_Ъz*"ˀhT:iOqsc72m_4$u8laqi2|aMj+E oIٲeofM4 jTMCiq6XVƀ4-3V5iV)z卍:tFO`k(sqI,Rmfs9#rYΓo6vn5z |"v@EoI'0nbE+qòFjjXF'^JH3a6Nd/Fe@!-CTb(gh3,6 =BnЃ,6UV%tGT Yry颡QsLu@p*6'~nooo@y$n^ڠP%f~B*6UO%dqYpcЩ~\۬fNJzjNT Y3lpůR6cGP"j.Cp*jw5f >}+n8YW vu P>jNnS9 jN>}DqÙp*hX-7bcJzj}<rsȘ{]W1ޢ|&P3tmۨ}Ҩ/L]_t^j|֙帬"Ζ=21IW-Ol=U{= ~t=5O&Haubg_wV3 ]5MeffTmmRRJܹSc AԾ !4j6ۺuJyi Y[U* O 96op~s;e|63Ɠ~Rg~ۦ ?hwU;N{Si3I,b@rz-9P`BӠ5F)fsَ\ϊ:G#.9^+s~Wm66ca6цyibEZDgی ~ˡߗy&l Z˖fYzvR+IO׵n]qZj]rkkw*D5kҍ3TN# 53'%cgjFNjF@ߙf"mօT66MZEWM]e(rr=x ]5LlI;`mmU[[W%fh .UU*`<(UXWWG0ϋܲ-> j0 Y c[&vqffֶmbwdefz˥k-[lO9ܲ MOObvǖ7j͚o M"enRkYkv㌻k$'ٸy6oYqMs5?ed`8Sc'XVd۫k6l֭ٸiM.'o;;</}-"9rXD}BQ)o\U.K0^bːʕW 5 ZVR<a5DɧZG%JKJssQm_ִ6[@'T_Qk䀹UugJ{\5^Ե6s:Ye!m2Cy"+#b mֲs\wѮ2 S11}E.BHվwDխkZ(pu-q?"UYYEq@=6 NLi+UB6V.!v4%j1%kfj)m1@lInvDW+W-T&v+))DFB(q9XkQ9Ou`7oܹO{11TF'/(TE1-5}Uu*W[x%)$dѣr.5^tI$.nN\Yѳ絬<IlNLm|eJIiUe*gm.z,j3,ïz'//;]uz+N/0UTUO{5zNmm:m[6[v=?[^q6&&u1g/;eKZ(6 U_~M5kyrq~܅g#11 olTgS[ܼl%ƼUW\Tڋ/~k/Ͻu"iߞ;oʼc+3\x'H7,u7dN_4fb'1;Դl+*jrթ ?~BeCáêhGK2%Xm#㥿kpߵ٦MTyyy*563yX[rTѰ_QLgG6^j}5I=Rh=<ۧ40lذĮoGZ>4Mjj1}f# 6tDpm&2!-luYktmfp\} L5e. -5uvWQfsZQ+nk6kYaCjZ)D ]&:؀{4 oCTxm&>|li,, ̀LF!>]{J|Q%4b+6+])[4W M LG ֶ|nRLex1/>>kE2ݠBܟp"jV¿k/;x񝭿+@9Xw޷6IM7m-l6G}q =d)5::hȅч3V$䇌"%GWTA1,\Bo Ζ.6UUU]-[Tn<뗷^ʅ pa/+@Xp|I4uq_]]>qj*62fL?,hfLmzpfYmzpfYmzpfYmzpfYmzpfYmzpZfԘa7-r#׏y(j"O;E !1micF~m2ͅD5C4K/KBkCv 0SM;2<_;??f@$U"%ΟҞAQo{Ӡu)[E-v5MC77mn.~ݢkNqVY:j)ߏ ߠQf-1D3 =̔O1͟8;G{ ];a'^):=jO=Yq8bܴSac1& L)ȏbD5_XRk ]˰,VU-&!d>Sgfwf>~nX]}tߝ(Le0mq6ƕ`["̬S,+Hjf[wAyV \ V{ J*P<WhK(:tF̜, ьgD9$乸/YN9SJ.<`^~e,ju"\R¬ڹ ,I _;o4xx衇Qr+HTGQ|ټyaԴ+Q̙;v45QhEmKl{!0cuYmŒbT;0AÌa3 :f t8&p1aC3&l#}áQ<dvLB0c x0cu '4(WkÌ [!%quz(pxD}zWL/:fMVc FO,qTa tx0cuf35(_3&l#J\tƠ9]:\CbvzP:8̘Aaf5aƄ-tSA "p]GJJ- /fLBG裳.Ӊ050a}Z/fLآ`7m 5aƄ-tz*\؂w}`IC*LۍK90x_LOp OkT.#>t1j&\#OPA50ìRu1uʧPA5L=ImtKU#_#}¥=]^S S&ԅ3r1Kx DKvO?y0 Tf&Q> f%%%j˶mTΝ;UKEEJ%33ԨqO#> Lg_ʧPAafSSSՈ/TmLg*UPfq&h= 4=EoifnȧPAap ݵkJuU/YYY*unZ7Z*wEZ:Tr@?.,mC ace=;0^QQ6$W%UbdCfӷV ޷JWܻwowD7|npHe>t! fN~5MRZCǍ+3I7t ɻc=@Ҟ㵭rHWϽwC\I+7U弔zkQmޒBSyW*'ʊ8qTc럪0i af:MRZJb_]gZQ+7QTTV P[TA&?Z˃rI%<d*[.q8Nyi)@=z"Hп34jБE9EG"]10ja.]Fu~1v5{yKF?<? R͏R.8"xjk?.gpe85C =`&&&Sn#U9T^"!xݬE}7 v\0*k $20TTBNH gS%% V@0Į'C)a:4oo߾jLԃFi=AM`b~~>Κ@FnEq5b{חY?–x?ӈ[b8 Yj\K(]TBD B1C b(Ձ 0"-fAJRe<{;S$*~%$'FhCe9tu,%5{ys͛;gbc>=o옘ٱ'zVttt ƢgώT$bf!'nNl,R(3gnM`}m?ٚ%ƢhHhHhYz~*,> x{ @{HfTݣFXn,Z,-bE"üACc#pA1`kEKa czҢ?9i2XbPY &|8bU?׿:D\[4;_q(p_\(9ke8r䨪}Ygڬ#g;'ķֻ^c݇H.ue 0a*iTUdwXnW[%L,>DŹJ:XW:B?}J2< Nqr9&;yæ7dj=uTf{ôTN"Nf5)Stcq<C{1qqCh@pcff 6ӂbAZ$j'0oC/@f&ek5Ol 9<F=. p! QI!#ML!936oN\ȍԼXL1L4cDѹ͙;m9U%5pTy05HORj~[  B(ed |od*Ip8:jWqF%xX[gfd\,d; Vy_5UO W`wD0++kݸ O*!D+ORQ xttqwKUB:g..cj:Kg5EjDՁl*;jу*((#ى , -'N> -Dh@aa!uhUUUj-Cvqd0WBĎ:ff" нuXS,S1kܠ$--M"*B(hVC|ڬX{ǫpruHߟ_WhU@K? 6dff^ٴETN4͆\;jΖn}|]XC\SAdff΀٣?,^\\LAUhbjH- F~y E;R Y^M6#;W_h(mjyqv)_u2;QxUN926ZBQmG쪘9p,Fb8iWg&ļ'c UpٲŇ#!Ӟ↡sG<HPǀQ[avGc ì?k~5Fy_n8yǶ?(I_66ʙ|Yvvx/7'=6>1l>>xTQ /_9z<ͫ2@ظ̙b|v"uЀ %|Ƥ.Ќr9VV۽WXZ,HO~KԶn,ehZ RӉl=gyvӄeVNդ719?孃v S 11Ξ5Ϟ=]HϞF]wͨj ϾYR *8̺IrrJ1LTPqG^^^AA }vЙ fo#_vM6yyE4ϖ@zNi˅:&QA5ÌniJ@u?Pw;HOnuSDŀ.њ.jU?Fg,5UL(#^a BƩ^}|(³zx/ꨠ⾙Zvv T!ė) ODzXӉ2~2k. !3v`r233$i =4#V  TPw(EPPBx4f1&O;jEyPO"FĜ5YYY޸2*abk֬'u0q.,8JL/*,⩈!OoyJ6hH`T{TjUU(펜,Y?2Ԣ~uMޮ4b`"_9"[<o$0Bס܄Vܹs׮]2} 3mUE=ӿ\:=99ABJhoZ 61e{u<Fi|=8oq ^/SB% uc Hh:rGGb,#֭:ӺqC5AX#˂Kƙ?9+уj*۝bqO~|AӾ>?ꪸn6d`DN" \J,-3Aꯎ"ɦM" $USTP-Ӓqėbpx_B.qAE~C ={!yeẖ֝.Q^j޶0! ~s"4NgPgTP16lEQVVRLBY{DE W^'-j"SwPu1 *Pa6<Yx#FX!cA{rE>_xȩ\cip|!f$^P4(2b.O;?:wt W|X2?8/ _̟lʜwbcR(G"*8n?S~FAkV^_wY^Tf <TP 3^ 8j6i3 :f t8&0mc&p1L0ca0AÌa3 :f t8&p1L0ca0AÌa3 :f tDc&p1L0c쯫vX IY*Ɂ/}c 99ǔ<ErmS|í?-}9RHO;mX1i׌yqu(._|K];66IcGMSf ŒQc&mygߺx#'G:|7y&\]֡ =j}ht!XH =3k{ѣ[#>*<Bq`(E)̂jcoyWo}7;jc{IO>?QsF1޽XMTbe,!|0kc>1 hx*]{=S0Ca񌣲pc4 CaD[ZY-}٨ t|^43_oyC;SGchw~Dڢ1ۦ^">{g ?96[6G#GtO|뇓+œշ2X&x#D 鍛E)N+4yH !}A-Kӆ9"s 4|7M,VHIkOdZcҲ1MeBD}cHʰ,VHXq3S;ך>^ܔr;21gjߝzˬ1 @(Y^$#W͟q;di=X0~_Xe7kn]F3?Ӱ"Ƥ(Ɛx(6$b̔.5ƵaX-׊N>ҴPփ Wi]:b!W}W؈CgNF{. DEXUoWRY5}$\qBb*?e)߿2s dGm{*~aQF~1 m1'cWcVnX2d|I* !c<Q[q0r5G!$CCbsH(|+(Y"_@qFD;Bw  Ra,LmM5`-ZblJk^mdIcDcuYb  &#bL-ҋA6qX1BUO^@TOnV{`o9jg9$SjDQ[n}lYC榦M DIQ&hcڨ%O2B1Œcucsr0xe `B ._+"Z)u/X,VGR1 4c \8&p1Lpc10ca 1 .c \8&p1Lpc“U 9}%^8Ƙ|ߡ VCGRk]74jtn7TgQkc O1D҈411+{/F ^8Ƙw>62f SVYcz^8ƘD}Z/cLx@1&<Q{Ѵf6@Z/cLxB1l8Ƙ Z3ں>I1\CwAPlh}n騅4Wp1D }2)~}CE 1fB1@t!xcP ITkc O(^8ƘDAF)~H36cb? rc [>8Ƙ ŀ s=nIz,1&?={މJLp1`1 \( $d51Ƅ'}Z/cLx c21j p1 @Q 1 (>!Q4=2UV5"V)c*ja^8Ƙ@ϙ04ꞡQN%<[@L۝>JȸrOϹB.mA<&aȾБ14 c@P Ng9FycF- 3xcuITkc O(Mlk8Ƙ5A}0>IiQTk0(?oDŖ1fA1N%̧B{~Bk]lqk$=}P<S\,_>]|n*p1@1@?MdFp#>N@:rb Xi3(-/k&,hMVcLxVc sdе"nj @QceM/Ov)T2 ~JB6<S<*v5*?#ȏ{"䁘9}qS1jBGO?OSc'"B,nIXzzP 1KC!?%[~V|%=L>#1D t_"$TlykIZS&kIMH}nkz H$AϪ(ҋ5m (SFPcc=!~@APLZc[{?gϞjU5Ϡhhv5")))QٶmJ`֭eeejSdLcYYYUUUj@g-RSZZ8ӋP cP#\S.hONN޿gXauӍDq~ɴWhmcV clDO\l66*333//Fe0VF%*ԝwq}*+Řݲ.ZH輛V Lb fR#CWkSSSHP:0;;;''N+GiUC+*@1>bпVĉ_. 6j ^&`t.D]ꨳ;l.^6r8j0c Lr +/̴$qT,STYYŀnB,8VÃS҇M25Fhga٨|?ek2joFblStJ}Ȁ)LR xNK`qrFawKx$#5mPAUU0 c21G á| q@oh9W Y1&pn$*=-#OUd@-qyhT!TUSZa*qB%9UֲnК/U1y A⪶0bS~cs?$)9:1ohyq$!yr':kO~b]ų[G̘x~q+t?"c"1 1cYKeO <+>ucUS^)853N@W,\j~GvWpK!ለv_ oqS#Y3y^uuIoCUd\T!:?^e 5UCV[ueEEfFFee%͂x#sӡ! o-8j)|=6tO'ѣghAPYWlY=H7{6&n6Rdd槧wQ8Pl\Q|ZmV׺u}zWdeښ;~֣Un'bJ+++P)QXA1U!p]M9X;}u T*Dرm?[+,os"<m60t50}EĬV+Nyyy:$gbB+(Zλ.8bi@>˅8/hcB( $P2Qg?9O/52r>{BoB1D jD=䢢fuvÇSRR 279233hijl#yRbǧ=Eg*?WIERZZZUU\~ t4MD2B E h:1# n=X__YYKy rPiG3m! @1n i*4XvNNG\;P*sz$ F%.8cuɽ2DdRQxKopjZt0ՅDyGUŵT{pwH+q;+3 BÌ eJTZ'%mھ3۷+bGnߒe <'$o޴)=} 2l۶UW"j5-XqiCBu7I\:k6\m{nU@Ee嚵&ZmʁE%B]Vc=cf7oMYnúk7m^qmNToc̈ 7T7o߾QC*s1ڮxنDVBBjӚMWqV֙ϩAˢJc _~xQLkjn$/cϛ=(Erϋ=oϙ3̜93fvЬٳgP(z91;3g̈ ";6.EhW\Y1㫖%Fӄ,lmA~>ɲuYjU9O6eZQ\٬t+,5얈ٚ6 %VӢ53{s{4|@M'0DǁѯF  "ڎqZVk':{ c2R1ࠠK@Ud`Ѣccc7}Xt곒#Q?}0f<=)b| o!ςTxw[|ℂGj^q>\eĀ!ӧ4 ]Oe4_ZQTiZkZeHL-mZM,Uե4Týw@tH+`5o}qs3byehV O Qs WUdb .e_9 jVZҥOhzW?7 NG#gC5P'cOAhP7AS:cq-Vj<M1q1Dy bL{-8]Ę.uuFkу K~G2KDث:Z6L{jHGk] 3ueĘJEUd@2ǘIrPGblũcQ?1<1Z]ZGͦ=,/ WκB"f *-/t[ j^FLR{$6V 7nYZ}23+**(`j/(ƚ<M0)zDO ][hjjlj4ƛfxSӥKbzΎQ͉CJ΅Ɗ:oΜyzgظ9m^uл߈86bEGQ4U U##Y|*uWS};MԞ jR6-Ũm~EaWóuR/4oʵl:q;OԻ J5m=Cr%-f\!O .lu:9򻹈1rJǘfEXz͐0Ik.-s!+I莭JL&da5vM<\p[W]sޡczUwzjj8\Es`h}"' SR%Hc+VYsՋFQ{#i`Z8ƺ;UBqXyQ#xxID2НU3D8j:S>I9r$99 l&O8C,NHJ+ebBkvޝ qC4Hii $;1֣g@ɴfEap#Scwl1!4$.VD<Zs*M`%`\i&}cAD6ZVpP"M ZYlqL`OETVT` j}%}^D:r1:ǙDTWlܸZnqj U|SUg;,;HJLLXLѨG | aUU7hWQ1@Z:e:WX)c4j2['uy0!cZ8>,;p٬z \x#UKt߄Yp3Ӂ@ˉV$LžC {jmڴPa~6|] 硒RD^!ETVVKB ȕuVT`jI$!*oq87ՠ;P5s,1{snysCbVAUgS/rSؖc޴J3VK<Ӫh˗/_j-RV.]ψtii9s9g`(w=a\\S+Dzb>5ߢˍ)))NuQ=TE<ꆍ[ԾVϏAc!&bH(ˀ)Kc aU*|a׮]ƐьZ N'b11$c1.qٶnuUg}VmOPhfĬq@$98s &}yr?bs~oG}˗Ŝbc{P)!|c)dz/V^V~54~z"?&&\5j@"&0POڍ'?ʦʿLJp)Jj^: ~@4_\[q=3-!q+-qYəב4/9Dط'rBﹿ(9s^r 9G$UZx_55L&b,ߎEb9o;&gzϜQuI>4=4oχRn-7`e"F%s|TUv w'v76/~턻vHprT-c]kDѥp꣏>Q( 􂈱?yU](xOyz-=+ 14`uJ$f<rucB-8{l$d"R)A1jLQbX:/XO=(Oz1rEHJ1L0"b҈7{j BkaLg'r]˫?1y t 1vłěe[؝g-o݉2(އ'5c#jblo!`]l].`CD 1Qkދ%$*T-!cAe'y ڼɧT9jU5_w((4 C-K$ u =5 ?m>BF/cݢS2fǘ0c'WO1(,,ܵk @~, puMTdeeugv&<_{W]?} Xd/%^SJOo1}Xj+UԴ=2] e8T]ړ0]eRBW<a@jntavO{Nn|U$VxsoF&k&Rc8=k/?$^U-E{l+!4"m1EkӨB˃bTc,lܵ@Ę!Gb@1/Kb̔DpcY;` 5oJvAژXp~2aX 6mӦM8x'E#GҐkmk5ٳ{`0pbLZ]WPl/檪ÇShU^t $"r!J݋] WPC}}=/d:$cL$2D B!c4 * kK"|H ?'^ gh^[~JRjD8ʄ!0P$Q=zʕ+ۧ2DqQYxѓө 1a Q%\֯B26;N!Z1f?`+=`wmr(CCú`ol%F8w68`Gvg$ ӌUJסÇoݚp$,СC2E=)2j+(tJ@%7 2}BXS' !5I-1gݷ\W Ta\E(F3ٟԾ);SvlϢW7"iiiY4 $_'(QDqZx$vJ$@m9f ǚi_ӴZ/=*z'ZdnYI/O_rXx/`ek֬X,WZ6$"kr ~JMbߐhW 1uE6HW& G˕ϐ` Hz(ME0I6t=L1r?Y"<.ro5(;=U?Q P?! k׉= .\~?mG?|ȡQ|Q{u0mb#O8*I Q/.b̸bS9c\_O<}H8K.6ǥ*g@Sc2*!B_B!>| G[CQ&~D1@c"'&SjyL?Wmٝ?y*~'1ĵb…q]b2Jm,OjڬAH[b5/"*S3O*A ѓj!X,zP*R$F._Ř<h!Q46II] NίpӪ׻l.(w7d2xqj:GY[笮:}*#ޟ? n\R")?p]8=Ee\urF mdz1.] )nӋQz7 ?3U29zի>tHfPU݂c1r"AD~҇c2b_] {cv j2ˀL :k9ry \&pu?tu_fZv~{^c'S}ZWwʕ>~2 *c@{h&ڿ/x%7h""R%: aBοcGH\21pu*}br6";'#e",M GDlV򓲗1#MzAfT@LҡHe50%&%.5H>xntzYSC@1aRc29zýOPk`AM8zx<Stw./x˻#UӋp1Lpc10w18&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca1<iQ㦲XcL(_\qw(}aQޚM@Fb8vM6j6G#Qvnr-Ӈ0rܔȱBN&S3uiM7m2!fytVϊ/߿~ !}PՎ#F]m˷r2Նz4|`,i-=o2;2>6ŔiR+& iҖSz3⶟P難zlmkK_~d-?nݱ?M=baL9ѓ7o&׍vݸ~w#cH?zV\qW2QNgF Cc?w<L@/fQ ݊jbtUPSck@z<zc9"*!7Z{\@NIbHcV׉!CJޭe >t[\YKn_47=E57_^o?|RsQwE,4bφѢY, jds[R fun%SI3f ;i+26@Vb+'z!1yQ-*-cM8ٰۦFOK};aOaM72麻}i'#n|47ylpG@D©ac^777}n2?tcً&a),u[M!06nOaa=|ݸ"ljpᑓ>8%OuDd>5qȟ2ơ:=rToCn-SsRX,Tuda?cLSn?mO;u8ܴN1~,rNQXfDqZQA4|t51ƥX,+N& dX:QƨiX,+(N|aqɨ˘ @>3Y,8YuWc􍚩}הcM?̺b))Sh^S&4ͤ̍ ~qY,2Fi̛А iL]7Q7 C`\P^R&T9͵fTtT e).Fyg}^`T$S>LHƍgX,Vi q͔og՞̫˸,  X,NRNUSS=+S,<|;Yu;6=U[wf9vO' S}+olӽ/ס3+3ie\xɼy8T(z¸i=zPz,ldp<:)t\,/޳rcLPUYANE'j綗ZLCX"gE rG ꙝ6Ll޸%tЧ5혹ItN6Ci.~ u2]p28{s5dm WᲿf NV]VWClhԄoE>'[yo!'N濪uIO/ljK1֏Xb\"'٘'io!M3вQ%Fi311SkjXF PgђS"@'MTc)^?Ym/ TbX?'#+(i9UVO>vzPp/|J^|wI Pz,lu'czJs2jdꊝaaBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2aPDm|;1 Ä>Pd 0:{q.Zau#q`-)}*om'0\@t* FMoooXkCov2aPBڽu¥)L{dH` d'Qd 0:0Ʒ;0L(N N0 JS{sDREa uj}`TGd 0:{9S<>SO5ޚ9Tk}1̅'>}tJw&1 ԩ5Q'䈇1$';0hLuLV⟑1'AGL3 AafN(\Jd 0uj}a(>Pd 0:>ru(Ua&PFa&<Qv!ѯ8S\>8c$'^afNLTOÊ >>]'ʧ|$)#f?]LzzD= ;0EڽoUG`BdZ4!aR贽 4p,a{^'3~ SĬvafN;0Ejہa&Pv`'c %ԩ=9pBmR;EaDCv2a:{џ-tO09@H<O?*T.}dh=o-8 dȘ9EJd W.z䜄7b0j0_!a(Ew2zFGGs*adxu_K'_H0D1*AK&Cd~zNuj>y'v2a:w;>Ԉ v2a:>01 Ä>Pd 0:>rd 0:>d 0uj7p*aJ/O|a;0E ߨ[~E<./~EO3Kh4=Tb^XxpT=9UKu"GU5z^_mv2a:wΙ afNCq2 0 uj`Kya'c %ԩ=1u|Je'c 'ԩ=Qi~a'cǚ3ej}^^p<sZa5{#]UYW4NOMF֏aΣN^*`*K!;uK!py Q {`9 rZ&Z>g?B?B?r-E?ׂF!Z*fr2~ND+'xξAۛ<ՋIMf}ͳXk%=U |,N0Aڻiއ '{OS!!ϻB_{0z@ ͋+˜$rW3 '(}[$P?SΫN0ACv2& UB;SCml+pUv& L9&XݔcU;L9hjUkf߿۶m[n˫P:>ru(Ul@QVVKرcAeOeeejj鈝;w_vQ8B999*awlZ,́[ഞRYKLLd:YYYj@뙜YPP0a:{q. M3==y G<yH}ϡx ;Y著Ss~~>[B UUUjKtɌ:jݻ޽ZM`l@Zoc5RXzz7}呠gQX<X/_r!|ަO*q2΋5W/a'7-5mEEEjtt"[n ~ҁ"*?Qˁa-dlHPPl@<.XڴVX݅KAޅ2>gO`+r<a\v爯G_#QXm)--E`ǎ=(..^~=:=:8l߾}ڶπ hvhh'`WsƤqacPD@8}Fav2Sf>ʂuQξCn۴q{bΔ={;e?>ՔC٩E(.IO'KLܵiӎk={ HMMݶm{Ķ(ַ41-gkΔmeNۖ+%5/9%/5 SRwef//9lְ4ds; v23+6̴tM5lڴ [k^_',5=y56SVl^jixK*!qZvMAAAff& `:ggam44q-~IE4j˚&eib^;NLvݘN|wC59NS#֬5zz[~s6m`Zi}JJKM+lmޒRЅm/Y|K\5(tc-v<Ç|{>tGx ;m?{lG&/6{f; u\q$SgE8הy_fq'wRӘm 4}"^LFg/Z1TznКξ;&ʿqf.:Jn-s;ԫOy!/R;Z>X NYHg!ϰDH# B$DxNl 3EWL5,"lL'==߸KlJ9yLl{'HLg!Y".GXjNQꔉ$"}QLA62_o}`> N1^)>y9Oq,l0;ri,ڥ<(+g`amޝ#g{ee01t'r8#m3$ː 踽/\:á/:zK(&.(G--\4ȔOGO%pU9nYFhv)-Oj%d-TTT$%%/2k%mTuuN};aC4˚ PW;<WL͘YmZ/bOx6ʄa`2x /!_<Yr9\´ZNSx]!''^fmҪT1D>IPBe1:F'sL'0-YD9Y=2kduO9 a%ůѝLHɬ61NfS_?i[T(M|[{NnGC|^qj0 [N$5 W]S#Ät. CXpl߾===؁bTĶM#YV]kW5$ F}-]YmeKy g'u`' hho>N!0&r^|X^@Cߣs[L%(rVuuΝ;);v(//ԥ2yie: @`2-:>|xQm$ܜ ݷ.d=Kee%wj$`S#!BdaH 92[MhQ%3)!H, b#݊D>rJ𶌌{W) Z[5dtɂ'ñ㏎` Plr]aRCCr/!\iԀ+M\ff&NgD B@TR_sr8`EC]v_1rf=Z8&0ra\1NzRRRГF 9r'ֳ֓V:#)!;|²j%=dn?% yp|, -[0+;29U`I:TJ.S 6b )۫0MBU8"!g S<'(Nzݺu6mU%nJoSnc}js|Co 6PqsՊo??!Qvk87Jtc!4*zy!d<TJT^n}*ijYbW%-ũ2:0KzɨQ)~TKP#&a 0unڴ lX"a-KBsIp*LӃ ",\bz>T D[_a^Zrָfb5*Ϊ 7LeBr  QYݦGlLG_C5oJa$U[H6]ᤏ/|]} WB83+%a8ꗈm -..޾}{ZZځt^2ER26 ;!chNp2{ӎP{P֪*5ԩ=SҶ=dY۳0iqA=<(IȁD1147z.7z._܈?|$J#e-QqWT aqf=g͚/9sFtYg͞5k v11ѱqOLllLl(iq(i1c␏,bvY918~B&@Ypݹڣe E{RאB9OĠ'#LOC:{M\́AZ݃ڴ9oZ66 .yĥeuT}ߵZ"C!H<&8`Z -^3 $B^zLpctϞ=))) /r8Š熃\3^3$fYEɝ]'Č됏 __qin/@#whN<̄셶'SӚ/7?ϛE x2ao6~ÄI/`N {LFwQVhF|w^p1ua8dupd/7'nv,>01s͋33:zΜsfy".n.4Ec>09F(M›Psbg|y11ѿ|f9ODϞ'll9@Yqs3N%$媭ݛE$h‰@3xJ%yߙ\o4aQ 7{DAΑEө@ 3o8"6(:B,V#LQ Fq@'{m޸yݚ7OIN֞}AFifg~A)_^GB3d3b!~Å"E +33:d`m m;N&MFK_Ycm}:.ݽ5y8hͿPرA+#"FaƯ YT- wß̘;;;7;/5<7zԃQ#G:[-ZfZƜSų><șPr>YG˦O񋋯H`ꢸ/\n}LtjX!NG۾Tֻ\Ǹ?<F2jm,24 z{^8?R>9H|~Rd9rꚓ~ID?l:vsfH;y |ϛE, FQ /ߤgq 3ezN&>ӲˑBNFV8SmXr"DO e%b K;\/1;M@1x'ulJ`W,=-&]9sq8aeut,u!lL~N!GrRPPCm^8MjBK['0*1/KKGɮUXKvW,G߂2(D8qv]p27°g0`Wd%r,\t( 벯c#'ala`(3PuQk㗶Nf9ߖ62TD'~j}S!N檝l1N5MaQw{=. {cސ&'k<#ƪz2Ore'LY㨩s&Hx έ0:Gh#V 1eLhENV_b WHU>P'ًr2`XLuؙ1d"`)ߤum =Vkm+OeGGhim{f=WSxI8g~eytY$]B'zlƦ/=͗'fM6 x<PEe4Ț($2m9:648z뭹s̞'?c!bgΊ5#vsΎ-> C-ngbfŊDGϝ1;nVظ1s0ѳ1qyscf̎*0wL8qϊQ rKWt mHFNI+qm3#Ѥֺ?Vonx۴ʬ\h?=ɓųbjӚ[j38m/)# ,hOj)?щ!{!N跉~";Qt"npҥr{_3kuXڦN]?k+Ǟ'oSU`}% kMe[cTUUѻv?$k#M"@}kEj%=dhVRZ %e d,\. 2eR z'䗋gOSYYyyER2H>TXy* J~YjЭи0v9UUuuⲲr9,;PVzvAEIQqQ~! z(:2%%III)) Fa S&Pu CוX˪+eJ[Rť ,/æ^qQ*ʷ&o1:=+AȥBzUU^e(.AW+-W@Iy ȗ]Uc OB'%%@{ Np 8p +++55lN&.TRg:)GrE/ ˈcLyi HVĚۋko,]"Oa , e@܍kŗY1"bh qAN8Ů]HWUAqHp_8$Q<= ;tjĬ58蕌CfPX8Ԁ0AZb ]h913v b:Df;NV̍+\'@><v慥aOgyQu"Q1KNNw}\#z?tboeP GzzZ*6V<[mQ r2?V#^̤tm*!MyDBt!,EEEg |0O%a-G,k*3T;I!f(9VAA]Sdi8pE x( 1TH@ anG$}dtڠyTPwZ*t%ѐF~Τ44Ny9DN 0/l6$.`_vTE.~4a_aOsd! b#o 9VkZZR8Yqqu EmIݻwcU+**ЩO=^:;wBq|1IH|E~޻woii)v&OM F?ӑؓjqlavQ:vM@[`u󾮮~ㆍk֬?4;:NDm}Q9JBtusv$<Z31rխ]nÆK.o!S=fyl8AbDءCmسgoffVjjb1|zBV."BnLc=dZIL6X7 ňvee+WZۓG  v%ے MLL& DdEF x)_1P6߸a&h˖7o9MjӦ}iaڼ2 =zM:2sشf妵҆jع+o^ 6oIW`BiY!=}[ZZJo- ct[zfzz^ؿRSSSRq^RRa?4]Q^rxun߸aӦ[6n,rCdTPXX=뱒X3SӥZmI-JaAٹkwZz&)5-CT%3`z8qٳq񔟜j:{AIɴtdE^)pR/R/fXA}LlޒV/oex_ꔾT-~Y~#}ANnrrvSrss23; f͚3g.HF9sm8DhތݒRgmݚZ3l(ߢ'ګ455={kKUj?Xw>sF_~P J`'= U;HN}%fϻ`n~Wg"s)uP.jĖ-?&pՋ3LuSOfzG$XOILWcbRcҹWeccʼnH1rr4c윞O9&=';;j*.zo@ + |";$*c Jؿ~|BVa0F.:k=&&6=Ecjq$b0AitBEcbK|@Qıwc<j2w[,{߯ƼUFeƼ JX}(fA[ wŋ-tf,sϝ2/KM'n>cwJڠA6ְWT>>Zp]X.vzr/6edr4z!ȧ zyçOŬqGksE&ͱ&O˦ĸ1 z3R (i͈LԶOkQʬŊ.8U~VxZ 5"2Q2>Iʳ;#&R K['Qu[xk g|P7X ꚓT=Wm^:03,xU9򊳰(I=8%c)Yi1DkbF:Hz{_ZcMD&CO-8[AQ$8>QCћV꾈QjX-N(q֣%]p,+9ᙳv\$d11`jH/#'[V'; 8  PL4悱ds0ljrÁXVO( j[H9VOA M;D9bwR=H@rc(`4.8;W,{' |Wh|ߞ{l=>0 n83QFӐ&_ČD :j*D?*)蚓QNJ_nM8 23{Mirvh?Pȱg3ԃDs\ zu ra˖~f=~?˹F2-dLOI_!hRל邓ud*myTdL邓u rjmbtGv^eͪ)W_]V#6o C7t|6} L>ٻZn߫һZVDGU#vz'jz^ZؾWO?-tȾ_~i^?ߟ_/9;~iH\\χ>ɘ>`׮];vP# 0݃{vޝ 0>a'cOOOW# 0Nw轫μka;]KH)..NNNֿd 0v2THHC>x1<W+ʪV@7gr )dteKjn\}5k0OW{SwsAjWwF 3"Z$ht~1ZS=ʻ<HP=gSg~O%Fڿ]ɾꍢ=Nz\.EۧxliҮ<.ߡu%?Ek:G^K/ZSCS(i7zP?jw-ҚjSoa'N7L'Z:?,&|'C#Daj%<ۧ/,:+FCMbFdH(pr4|o$'&  iɐ5`d `'c\$z['j%r@i>WJ^r )dLdffvK}BEE֭[EE1a> o}}]8&:+, VRRRyyE>12.f! )$5R8#<ŋWi]UUQݽP;_!E%*+>>C!ȧ QmL'* Dևa>,9ZU61y 5O T/ax^:@݄ f'CR]BiT;kjj*:0 ;Y8Pc%ցR8L Á3XVFSRR 鞺rFB2,%t“jV; 9X3 .݆S?9u˥c(**T scBeddڵ+'' RX+ZyY &dCxΨ*`!B޾SDV uir:#I3Q 8qST&;JeJEq1]8o]2cK4 3m{f28N=-= ˅YGUudlWD0LN8ش?qϏ-qo1 F^0z,/`FMݨ;ŠKʅ :0a::jЙ::6n[?/O;P-cpHCX t˭Ғ7l޴iG9NN ?OG?G;B]wM㮻 E提$GTP ݉9o Qnaq2;<bF ܍yׄ; 0ꞻk w^z]$ ꅿx ?wfK?<0a;Y8+YfFLEk,L!F)'ZD[㚽`v1=8tiC4,fGIr)b5mfvZ56.GA faM a,iCPY2#bTJkn]M=mPQyE׭ ,3-]ֆ U- 3a' Vl6#=e]'MAlNN0J3SsA]Nɭ7Q]MX?D,&d/~'m|)5vIMe;dMԞDO+L#~=DDsڌkMƦj'SIr2ˏ~ oqR x6*8Le.|7闢 7Bmb2r0rDyNfy5% %)-jb2&O:OlB̅i떈#!ZYw>br/`' \2b ImpWMVq-DOMw#;Hsgt$E-uk˴:ɽb'c,:Mz Z9îaEF>w}{>}kC<YZQrԺj.0U!!?&O!*NJGn~u=w5ϿVaĈFL\/q v:V9rddaQÆERaC(22rH|Q4e({f~u()*uUGE0vmc#D1PX%UR&ZHޢnoP%%-y|oFtJ_pʍT 3a' {K8fC54&;1Dy6xV9.{M悽8"_~K^c[5V['yFOcx>TcI5Ho`Iy| Dk&"`J0:}UY] =}_ @uH(*mVK<NliV5 g*VZP]--x߿_ivN⴪7nL~2< _Vj ` @I#*Oa'c@`' M[BTr/qV&@HVTT7w v2 vn֚3KHH@;; 6ω^aӦMׯR ô;&TR ô;-|)Daa@?$=wؾf-jm&|a'cETpuvHuVfҧ\_;cv2[lJT[YD\PoJ8"KNEXxDq|cZDdhDy$}I0fDydT4KTR *pX"}X. TR+iX%2P#KG3TL=]uL]hcs}V)"pсPL Nc<|ds/}hG?X^e/_vtHS ݕPrؘg6̏b9IF>rA& ;3`'cEdp 2^ }ޯUnN ɘnʟ@\m_~生 jm&|a'caBv2a&a'caB9_|90 'Mʥs2a1 0 ;0 ڰ1 0 ;0 ڰ1 0r&1 0;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ('v2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caB'cX,+tN&y`/߿~K?6&dj_\q^ثknnvG~e6nJ丩7z 7mXd|ĸi׎r1)rCrbR㑖 M.45J1vmFrim#=g_\Ma/6 445 D4ec&Ɔ{dmo ?äagS"NfԘ)cdQE>l&0nr؇FzNϊ/߿~ Gt&'*7/`oecںÔ6yЋ9vx) S)ǧnӿ5a,:.YW^?'gnp'_;#E"LqOq۔aGny rܤ'=?|eHYq_aS8 Nf0lcq|JcI]x SfgusʔVe66|c&wWTvsw{57bo{dm6瑣'0vꍣG|ؘQ~ݸ;emomƶӳ/߿¦6FC33 5 ?NA~o3i$4Ȩ>&դ-o]a.Qrh8iKMՇaNc-i0 R~ie?gQxnoLO]76?ûYuƵNo^t<-Lw7_=Io0rHYq_à^$&MK1د.%ILE$) r&r)[W3E}e`9duTVFJ4;R]uicQ2p օ!Ik" ȪO=frSc mr1wo<w] /ް8 Ky͟Z\pPo>!]Y[oϱ?1@,ҕzs)%I<QӃ9 lIrl%„|y-NxGb*ocSFrͥpGΝ5;ou'K\pWzwM5n.g]D-;׎zUǾۃW>4/F>P9bzGl?~JUEץNƦ<M̎u 2$fTCI1/h&{c&u5ۦG:{lϣn6'1=qS'VnmSț^~C7/>;\s[n4l#f,bzAl:ImH^N[[c;2߭2<s#o}q\sǔ1uc|o7cΘI#?4|׏y˔S|6KaX,VԁAϜMa"M1~ʍ ^?nxCLz0rp/F 9qBs(J|'Z|L< L7/bXAS6.<eQLۦG¥+9Ta ظi2+qgRؘ3`8赣sb.bM},1^ES㧍@ N6v:lO;^ GM>%zl-`X,VP5{cFDѵB|A["A٘)·s& #99cX,Voh@ۘpsH갌*ZX,+6|aqI*^>b 1d2Ʃ$,  e\bݎᲔ4jT,aw g0F \gY8[4n<bB]-66Sɴ{4Mx1& f2}t QtXu:c.j)"ݰXԀ2&S5< ͸XYnGǿ+v 8 ƳX,+J_}0  lCx%"3G%(ilzydcrTiW QÎǿᲛK>o[eLhY,2zbcT%fe`4Tr;k!$ i8z](@9*olLS) 1 C %Lrb|?A&=uʊLμbXP!ۆ]в=@LJƍgX,VwobX/ecV)bBNlcS {VY,+x_6:tƔkz卍`SKDa X'%<X,Voʧ)9fٚkOArZ躪kѫ-RSlcؓL]%f/Ab_s޼y4`cX,ac8fb8ԕY_l6<aXldPy i^=֭C\޶Of۫(\lc,7rFO펍Q6Ithƚ!=D'oUG $IFS{mI ^bO|<x 1Q4mJu cmb|IK<Γk!h=z2Y$r/w)-|qP,bpo- r0J6#ېm(7U!$٘sSbYHj V p;䴷D^m\"߂ҷbH+qSukX6.$!1sGSSӎe;DehhihX'%t ~0ІaҨ%fhj*Xޔe;n<J+r±DCGEz۲EZI6)NLƪ׿S0 s{G ȇl S[zc=mqT;"[oX L('acUL6ƚF-ke-$^dlLMX43L1[l'*Q^Mbg$mbػ>-Y//kҺae[3`c4ۿxQ͓|uODc3. dc>EaAi1d4oaOZ٘ Z@'œDgc`0 \JtQL?6fX'%t!.lQo G-QDKt3NE6bzSɼ~MɂwW j10O>^lG0I ݁Sz]6bzSluBSfJtMd1tQ; Hy>[X,Vo]c+rzJ!uSlc,76bX1uaaB 1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a`UBv`c pB??`c |60 ma&4hkcK]QFMvH@V{DX#T,uEz簍1 Ä ~lGQ"ja.%> *@6* pcrba˯ Hb)`c :YEQ =3!'0ؙC'3y`c :76f草6?9d:lc 0a)ӻbCES>#U290Llc 0aۘOaB11 Älc>ac 6PTma&L3Ӵf?bc 7|60 ma&4hkcw~÷r|S>W4ש)HmafƢ:wP<s|sG|gJZ2>aTdcKAjH ac)4z"oaJ[IuϹ^^@! h,ByQ>1* "'H1 8bחDЯht}r4l sc^+)!D *lc 01S60 3hat0`cp鍅lc 00E%a„pac |60 dc ƴ1 Älc>ac |60 S K/抖Mamm^lmc~0 tژ[|{W赊K&n]bƼo V]$;S|mK&{Kz= lc 06FuIҦ7όo3!A{cd~##ӻwz=4㰍1 8>rh?b$ s_GP,ZvC2E>l:1agi7ޠ a~l,`cpu(*60 &0L61aЀm'lc 0A8٘c0lc 0aB٘ڪv`c 7|60 ma&4hkc,5ޚ¥TkMjK1 8XGFM9-HQ}a9⭉o~ Suaj'71Rɡ_H/·6F?*A 9ZQ0̀=%]6F1 Ē34g Swad=FP%:lkaۘz=ZH@SaCGmz]3ǐ2㟉^P9*$$r^BD~ >acp._/dQC1a#6FwԁQw`cp`oacpu(*60 &0L61a ltЧ$0Lf61apm'lc 0ۘOaB7W)^S;jԷ5ЂzMK&R0̀go8~7"G{5|Ugacp1ttkANǼ1_qKی70#^ntw-b^b1T+^,Bv/˂60 3kc6dc7֫QL]aXoOa^¥uՊ:S.3QZ|ަ0̀CuO6&/`W\QE yKC~[C&pDyϰ1 0icCggfPacBO @X?maff6֡dm ɵ 0L"l,pj%mⰍ1 Älcma&Talc 0J8٘c0lc 0aB٘1apm ,v{Iii?Z'a `@ٚtU321 yؒ˖o>S#ZGJ'y۪Pzq[˨L/o46tj5HO&֫cz<^Bo;+j~x)zt  z7-^2uFhc-?]>]$^L Dir,,G G̎u@&rL1PRZjg1 y|:Fd$^;Mv|z/M eId6Vt&% Ƽ9aF*FKքfxR`cdIt6F>:U 1It3vc >Ba(^f/ %<C^"RƘdczkMH=b*4Oboҁ<$J>{ҷ=dUfot65ސS6t\z!rk=dcLo}1|\XMGd׮`uɉG&;%<f2tۘM[6t@[ͼWbc"CN{6&k'bc_u {2'}ؘmazƘG<&3PTmlR^^n#Oc󄓍;1Hkى;v(**Q0Lź׬ͅy^D{ۙ3QWxrss333 a|N6fSTml bwܙZ\\e***H;tXIeeezz6X[n۶-??f 3 33߮i-ݻѭ?uYYY`]vjҦ,݋Q5alcm,ؿ?:.8Ɂ娑T^TTFhdtmp*5a16यFS6FVWWާn7gffwR Eژxozɽ݉{_*ʹ**>؇wm,L())7|::m]ľ};vذJϘLJB1sDm,@~tm,)++KOOlj;TFDl^0=K{1z/@Lrͩk¥ax!LWCyV#bc}lc!Feee U˷mۦFAwl(,, ƆkzfOOm3`=ە ]LƼ' a?zI ɮǨ19'C=*)lc!Buu5\xԍ/p^V#fuf8YHtpAF QSjjUkǤT1!N{1 LHĪm?uW)vIp81sdԯ_B} *)>肛m{@' 55*'@IIIj' }Dwl2=XB_Z{MKKWOWKMTRLzo7{;{ lذ"11ǻ8öl٢{ cUVZ>/#V'c' Qdc}B 6vtm?w;ծN4p25Leo}vv} 333ܵkCM5.ewٝuBv2Eꪷ;X 󱍅.afc܇I)--)wܗB r[z~0es&%JKgTRҹOۛVi;rtfgf姧+%'ٲ%g̔zfOEEEi\YVV}c73)mgRZnrڮyivJNKIݝ;5-/=}OZΣG Bp@8>G1,_e enKAi+JO}6mܮY<}-WDG๛Z o*o߁!C6֭<̌uд}7ӣiإM IbEW6+-٪h5Sh6{ca2N)7w}؎;"Lқ Ӳ49uJoW TTT{'`DCնLUK&ҨY.kBe!KePs7v)[d' U'#?'crN)99EK7 &kMW &gT-~y {SppuՂCݻwضmۆN0ސ?aQ6JE| iKؔ]HEkh 3!K8٘c0B_N1٘ܡRf1NƳO/m,ٺu+llÆ 999&3](<ݞjg٘xQ%a>Xgc%\zڤ.Rw/xK^y޸ ?uƎ|v mSW&/m̳Hkz6u\bQs 1٘kG{Mͳǃ!:vHAfZo93]EacdEO\C7`]"N o{YJk/6{}HgmRwl=gNjyN$ƐԾ!JRW\jmLcsVO㙤5h}r_N,M~]=cb҅G. Zzzok<Gy'QX12Bĭ21,9偐6IQ ac`i", 6&sdEؾWvpPYL6VHU_^rAy?Go %LK;I\plG׷#m<qCݱ1H!m1H1aKu =´6F%uuƄ{p/t˾85!my eVjcH$Ð^6~R{i<kM'1H1|K1 17}2CtAZ/q:RNog&PL; r|)ޅ(^(r*aJ(Ww ^ h8pzclct)ƄyЧT-~ƺOO5 xC}&hQ@?HHHoZGyaVf&->)MfYE} >ޚx:)HAZȌZ+O&0:RqX>*Ӟq 00ꊑ3^mh86(q]^{٧wIɦT-~y"ӊUԂÈI6aK1EtlrlYy՝VgYǃj-߱}{fffAA}=5ꬑ GVcz6F"cE 0ژ[ژd 6 &N˂7)Dw wڬ!0qSXܹ+_15FUdO+?aZ _~״jꥪdg-Z*|q%~OͼGci_Z΂t:ctA W;pӐ i! ʧF( 6m,ZK$Mœȧ̻Fl,~=6dȤI z+-6v^|U⳱g }GT<C***/rݳKRM9@a:RSrԞ='#'˴*84!)!a֭MlƍM9$mȰ\̔])9);S3wZ-;5#JȅRJٶ?)#jk~A6RX]]]}}=j*&|̨{6}MZUlhh_ ~זF0@? ߆vi 946n܌QG zOBGf7jjkȽUG K$$\EIHP 4J9LY+QQ^uAtg:L6рݯa *iiipW uVHg%sNWFF&p[Nt0C#“01?ltS۷ohDt cF*FX_ar,:Gb_&ƂDAAA?[棣c520? S2`۶ei(S,iWE >2 -gr),,޾};\tQB3zZtgc?裁2tL88Sk251xxˑ?sEȍ0Dm2J@/泥B8X 7*X_&z4OBg7u c0V!^ҴZY4vQYhH`*z&@[߿^rii)P>Y-!l_&z.u6G{"oEZdGҩEF9H`X]]k.ݻѦ(&ge:1z7&wF)0J\."_ƷT\i\EJ#ES"Ct䊫51N+@SC|g"莋䔅=Fyt+D2j\B%uCO$\g ~SSSj=tX= SZ *`LC@g 4#B7F 6=%>&anw +$L`&f4rA,EZIda` ???^ӱH6$;:EG/pdeeaQ9/y(j[CYQbC!!Jci^4,b@hי*lcgl=:X$,Ll@Z[email protected]^~, 6 kj8XZ=C9Xvjk͛6lP^^5cx* 6_w8"zfHtowq"dj8q%fDlv:Z$uQ!.3$H(@%HP)-' âu {eY^7a=`c'"?`|[0g=lnrޛ\H{/\$B/ $$iڦm @.7ErfV"b1 cky{fvvVJڕsΜ9sfym+5iiKKK1'brDJ5Lh M& R`!H,[ lǎ])̾uv%/NO]z8(ǻ.%5e7Poddd`2_X LA֭[WVa^=u u'<$5c1ݛ;f|/ƿziA<op?dqx4荄["ٞ*fXRp }BxCu`k4F[ká`Eze=a-Zr%1CK]\} <!Wp}nf;N;j]^ z_-B7?>\o/΁F Yŋm7iz^M6L\= c}]`LѸs"CQ}8.\0Dgi fA"z7XCŹZ~ %ZՠB+ ,c0DYʫW3jZjW1Ы0˟2\bظa#Q %%HQ5Rs3֧aFLߠ[߸ itC %("nvvիSRR WXK{V\NU @ _UZfZ l U YaM;z#x ޚW.YjJ˔/ZrޒТ+}sbVEwnsm_] ټy3n+6l,|saVrUHA0k7BZne.d+ǽӝSlEVd9I +ѹ.~s2$h@he&gcCmmG *:ƒZIU@Kj\`v@lCC* %F`.q![V78._o1FNeJX V/)Tx=>]Tu c03uuz"a #om=ڊGZւ%ӊ 8e+ET> ŭUBEl)bSp߬5{VRrRRRԩSCDB|\B<O( dP!>.DJTxފ6@kIC-%&}Q>wpLu !Bzҭ<]B7>^fK 3=\lyL{tqt]k|:f1u+B-|C֦lꈉ4Hnq15%1u_z"5mG(ڸ~c2+*XHr QuЪUtV?6[qcxQ1c To1ҤIɎةGM>?ӶEsd/'a1^6pz"a,==:D?E,D'ĶL: {"W 5pk˷hdK~5~4{ZZZzm!Lx I3mڴ3fSRL+> n*T |ԩqSi8ijĤ8ȩdXAup)t tո\)b刏IVRB -tYʤ?9 \B-Q>:҆䏻fV'g(AA.&z8=2rWo 7 ʕ 3sV\\LIO/ܶmkRS lϛ~^,<qXB,*Oo#f/{wzpL:~$^k:NR^xՂH50j$M칔3eE+P2= WAMINmdeexݲ1utIdࠔ}P6mZDD4*O45)>)UIPC؂!˅qHH8%qz\fLON"FގOJ\bZo[c$qp.U.ջ27fÁwbgl'Kֽ<;,Dy|=:3RCE a$8@<i'㮫BA&vͺ%.^8sKwS5էqN#pT}0x{Nq0eۉ2jw 08|0 c)F(A):ri: +\*s()K /x;[C鏄{s8ս{6d=eޯym>PS-|nNYXbP`Vӹ|‰?Xx;-{6z&fӈ|4{0'.~ME<s=;tlBT !Po8M-M*=NLqSɥF\z#OQ@8i*{-DwgO238'7auR%^Sh#[+ohɛtE{d}3߰.I?bs:s.A!"އ#EXR84b:>cCh 5/3_> ט~cx†>;Qs AbPR<yqnD[:t#ȇ%C#(ծ{>G4}'dׇ8X[v cw߻1Sʭo~cuyXճ0;>Kc/z--(׿N4Gk>@o^BPﷆJ0Da̫Øi1N(KSQH7{bbq_{YcjM^ K4'Uq?Lԑ(؛lڭ1SÙ|*ұX>3>KRь?N)+ c0:%UV b!!.iE!&a8D!!zR I-̿ȍyk1lH-lж{ ˜ #Ӄ01O6|BD#ĭIApVjbζ< *h-%haa q{!D#ɦ܃T5-oW=vc@C wP~Yz}, qa cMɶߍվ/hCƉ`|j`\4f|UrV_'RyK$CΤ3(E1X`[_8QQ1}&Q-_ppA筣@Rcv 09 c)& E0,1D#,;n(DedHڰ{`7FƎ[`Ucǎ !_ crC4 $P>,B. X!CC8<a cW5FE:/[u,0f/ Ve~rcĉØrcʢn &_1s>{1=\:c+SEV͹TOĜg+k*=ʓ ?+ 4f;3cTUo7u3 SUQTa ^Jm -gUa@UK].n,L u vca!\Ƭo-C&5ME=cUXsV w7][]2Rsz%a(raюay mןusԼsn?̼3q;] $uщOQqJqe2D s<곹[s˭7o+,t_i 8aAUĪtb+g9i;ʟBTx3j!U큖Tz䛃-EEeuuFII-ܢ>0@R $L051F- Eq^IqӒQiS⒧zb|B2 ԧ gO0&`O¶ɉI+Vj]r;񎊝8j#/ h>%(kP";c=aTqqH߿u[ 7\}L]D)æ Ũt9n,&n CY5&vQ/{SCO§0F_}P c8VOp&9Ov ;tv#L~Il<*ʛs<^G};Ńrmؐoj" #a *" =i:FA:]oL֖Z64UGKZ FLK/DKN!TRr2bN2Y}'LKN"Iu3%ᴤiӓMCJzCI?``zw5jxxcG}*;'A76b=ܢ랺A7>^^m/!*μk &O dO缲5[Cԟ\7яx뼍ކG%f[c(7 l7"/GEyY7nCs QjWͳCjw4^~~ttwc_Jpr^Nr }mo-,*<Uo<`ƍ[l>t?z&)}ކ1rUoN2l%-+!٠j*h[xsI5+Cq~U HJY Ue.$N Wj.=/G=|n]^VQah{v"er#apt:mR2ݜT\Rb+iW@Ǹjj[ 3Y:7=جP(-(C%eК)xC\NUo஭q9ssrrs.'1A E2ok<ʲJ:]+(/.ؘAgWS'C)@j́ iD,~{zoxXjYL}. tWR͹! Nt=E-t ᱅ &\QkOʨ@V$r(JHЃ-E!3"i裣\rZ36gPu3 x3::Տl@ F0o}]}WKhdPV7ةk5{FtӦ5Hcޢn;QjpBjTgR@\V[·7%46[XPG?GA'RTTe K38@jTNIIAl'^15Ì gt}-Mx큑 yZG5 ?4oSӑ@N'Z?]V65ͥ_꼩(%555w1zq:u֡9Q=]]+* qwÆ D㗆 tF#u|yb>ݺu+2<eM$zG7:VH!baFA5[P-u}u0Tjκ1ieggsRQV***233׬Y .tI_ǻ淮t)N۠CRU >e  R^M,M[XX3]1 a `VҩT4#OqhЫiZjSe0رc^-[+ ˿ UQpA9#QpO T }Ԫ2= u4Tӈ˂͛7WUUYۙ쾼|ӦM֭ӥB{*E jd-Po]==Bb R cWw)"s`R-4SS-̙28bbcOgVY9Ϋ*++q& w9YHIII"?"H` B.HEC] cu{BJH$7FB8` # DLD5^o t>bT#!z!P0m `;|[email protected]rS\\wuPEXd#y -).ƛ?ZYg@1+(]1 a* /U  &\$0c4WSSq/k Q:a}>  s0kvs),'PgB zk֬F}b9ba,ZGxԿ xw-E8"X; k$6otׄ0d+yiBAcKsbiV6 ]TO#РL#*++_ǻ,//Qm|_Xǖ-[oߎ1^Ulܸ7AװN@իWD*V ֭i 9ll /H#Hfvp|&/ xD5 0™póGjj*?L<0և Bًr媥KbY]]D<I,//D/Y7|' *uﱌzLުE-YX~;!_OϮDcӴr5Ͻ 3p'[1Çٮ`C,X07\>K@=ß~=ڑ0WY~/Q>ܥMaBDEWVV566|k^Wj7{P*UˏWS[񌩇 } Wqx32jGgٚK>`Bb4bLm^ aT eզ:^{ i+TCat;Ђ)QBU#Zl92CkѴC;k5kbuY OD¾]!aѪ@r<[͡H=E Yr/_ƸBT|P} @];0Ž̒3́.| $ݱc粥|xTǬߥ9-Q0f}MBDjUʒ%[6441u.㍠! i\!Hs]io H{:cC*PG˦+D`6+">X¼N;gӦM ~(++۸qczzziiu+WvB z֭+VXxiHZ-!-^d2L ˖ĴT,]2tNYo7co4wކ@v^FN.}-DZ4oiś +WNQ?hnּii$Y(_F6@ε.mݺקܹӴbvSRR/[QJcU%x"K PSGtA$7jIIqɆtcRS8iiӶdn8%7eOZ~)]X(..FHCLECLSD!j._6Z˖/hK/c IIIӦAIJӦO6cXVyuܥ).n{T|Az{ Wc橧'zd}wp P mR˖~,Rw}FFF/ච;wq$%Ĥĸ8ɣds@<MB4̝;NrxC :I ,ɺe+7kv*7|IMpҢ~|x@!̤_  c}]t:|I0DDY.)*UHM=@SMޘ<Fn)Dӧc x衇u?:ok.*ú[ `lūшNiDiXhK8ZE JqOv1egg(ԿRؿ'%[Prbix$p$!x񲩩[XhwB^϶p -}t E[dB c؅>AaLݻw[aLPԃ<I^cg@Yp{ Ϝ}H c3Jv=ys֮Kӯ@ al _EX ˢصo*NMNbϗql='to:M. sYVduF7 :]U5ZL:;v}MZZ>F:!a)ԮFأxk~x ׏{8Z%r/Gºsot>0Eªu^|X8@gED[=Tvgjs==/r地;)Yٹ&DQ63ḘF*POD6AvEcr.QPc32Cup?`z'G?+RSOnVrrru:ƚ[A1hޱ2!%4r`}ݒ<X]ر<\Ɗ|DX?a c OOLzWԔwKpQ[BW߶~gBۯ>H`-Sg<k>8(یOk3?wBI4!ѽ[Q_BԾz,N3h\Cs.UsG_hʍvՔni m=csݚ7<?jmiVGa},հw~~d`~'Jټ~SAS `(yv*DtD /U5F }B7<\ytW#P%bZr?E1l6<>vدvrPSڸιꀿ;ihYez8WCKHli~3G2PX^{VhFElJkP,w4GYu?DDl1RwSlaMW"Veo-_\9gE26d/(&ƚ E1cp&HvGs9hbdw0&LzwGz cVݗϻ1l̻8f8Djo܋BD&d)8& ϋM/OCh 5o?eMzWoY!V+{ D51 QAˋ9- al_(A96AKuf{Y};B k#n a A'!  kEw|lưD h Be<T8yMto:D}[GSr9*Bx !!]O,06yS7x9Nvx?/@a"Gg&EuEg( %d cH 1B<0fn Hma c.`j>ꆛV"aBB4B0CUȢYlÁ41lH#?Z&*\YUC\zU;$5qƐh~/ ;U1{X$ ې0ѝ蔎_al2g0*Yx8EH6hQ !b!!yūKxMLD!.E/%*ƌ UWs0 ܿ{1DCPG7a wWDP[߬a A%ǖPa V0gc5p[’h cZ`u ؆sn b-! أOnE>nDMBb^Tc0+k9KC1c7v4!҈^-_쏝<菊Χt7UL50򖏝06ܘ` ch^ [!Ae;r3 ]`؍oZwxdQx9;r&,3Ɣ91DAApxO=/0@RpcXARՐEjii1s"*6P?*|a 3 cz_į;ʈjҐ1$ Aa G^"36.=c6EZZ1tOcƌ@!*#;v?>˹ vcU0vV!wYjQa "Q ݑc\fkv&BX` cn,\t͍u:zokW=cVa4[){nݛN6@Nt-3= c!n,\u|c2w|: 3fн锅rm'\0l[ں~K}y݉N}7p=}d֬;SwS6na %]]2?=lk[Y6r?\cH'***R IIIkBnEt]p[p Qn+fLn-8|X y@8p@aQMlڔ1m4}Hrr򺐟>:tEqqfV ^c~ '|Z  cB05YYYo  cB=1555W]!\HzEwØInnMtFHzErRSSKJJt^HzE/ØI~~~zz7~D0&p1Y8OL HzExØIaa!Z @˜+(mO cBXf͖-]f/)--Ŏn Hzŋ`tٸqc^^Ԃ HzA;X۷oOIIq:ػX4AHzN;.a!aLK]ߊs{JVު{oplTsfG(!r06)=?qcHB|ۆn=a06ԙ7mOC`m9 N70&B/06Ա1ro-:Uc-u`5|ԡ V1Kδ[--.~{=Şgm{~/tAh$ ula"SipGH=:Zp 6D}1|Ec>WT]z>p)}_f Ԓit'5޴_8B١=v϶"!1:>!!=>ZFC 0&N[7  ٺ9~D mbG|e0%V#\32˩uϐe$w0`(U0! A5FxC3m~dUWQuƖ6-HDP7 cuȄn Tk9ݛ5~amnY$}C=c`́0Fk?%v%1*n~KSn,M*'s:ƍp1Ɣ!KEP(D5=n]ču,8fu*VYȊ ǟ 0H\>Y.蔛o6Xy{g 4Ƅ'zчm3u_먣ZhRVVyιoZ(df 0HrmܸQg"\銕+WTWG! `E˜:1TUUv1YD D.; WQQ^SS55xA]__ B:4ɺ֭[αSqfPΘiA c<Ac@%_=Z1A&EQQQFFQЀCM,?Dz͛7s<^" c f$*v90YcFZ%s0{:ߦ 0x/j%uA7],l˖-#B!a, E1zM*0H aFYSw.ΚVaaaVVVii)E b$tx1#UUUfA$E9A9[tJE2fI<AcvH9}Xj?Ak0_ٰ_Hp wp˜mM8mӹP~FXtG!ĜH=Q}`,0# \n7aLx)BUT=?D"Pk @RRRQëLxU-a+VAޖCh#u։9~FXt0 |d9̨B$ Q_MEfVa3F7Wi[mAʇPNT-jbHCB>r,ںu+*#*p .ؐ7ESUkRW+͢ X%L cэ EO( P!,effcݾ};t[í081Jdϣ>WVpkT aYTT]VVFEuuNmp1 fYVKZl5kPvUځtX`p:/B a,dL.f^3%6z <q+W?>["uaq21,!ʚMT!qZKuf-:+)-&X3~aW(r i@ASLpn` -Q5܁*,,LKK !Hn|&மs"VxNԫ*ܾJB)h᪥[6ecVWQ1\V@DNࣿau_EfZڪQ>oߚn͛7[~ . ! YUB5*a\PT]"-_U0ڧDngP=&9Ȑ\ B0xk˷zދ>o33vg!:3g>nig?pyZƩcVÜ>O]vQ宸{;~EƌyXYci9:s3Ϻų.zv6ܲ| x}gIL J3g<.8‹.",.| ߅^!} Pv!_SQ1c󹐄.9ywCۢUj 5TsІfV+n .8KKIۂ]@HCv%<|/sOee7(覴w1qԭ-&)dc4Ygv͎:;Nszzeat r6_}yEE˓T=ʱp6goڒQRNSPVݩkǰaða2@&(b!u ހkbZTLuQCn#Fq0`)1=nQ<Ƣoc} 0qǔx%$咩1:{cg?o}pCj8sz<x4՟<\72bd\㓋Դjjjk8~qG!VKP?Ge}x| [pt+00aTprNCԔɱQב/X1:@o^B0fd[[չj==Զ:t!@s#61, Q7b)6/ z'b9"5aÿs`:XGubrwh/Ço8P#vw}K>oj)Qh b'/haGƪ  ף];G˜  cM}SQlDil%VznSvmC\^hj޲NӿW߶bA:ՆVag;?nΟVݥFgoۿЩG)KV+W_p-tY[!nFZaKKˁO=?N{VϓP~М(Okl%V wvoz@?iiݽ3 _5ϵU܅[X kZ}u8-dQiU-5d֎25Ј:`w`6GuAH'ܲ>N<9&_}d-tY[!(;f=s0ijx?XSoٿOVyjDYXXr[U c " ^+c-G&DIJ?Ci9x%?UB>}q8{el :6vpVmY̐Ua=dޜDUt~Ջ-tY[!X7|qkڿ]O{ᘵiH_4\06kzGE ?a,fDABCܘ$N cX? ]ih!tyƬ:l#RSbGvP9!0*,m*݊ y$E7ޣnUNh3Ri "0vy^hQXxABL [L:0z#a ]VVa#a,q6V_4%Tg|B}4?1ԧeuz/=MQh۱k'8np$)o)vZDGl#f{SmΊ%FO=wC]<쳿[O)W8þp 7*ՍGObXE۩?HZ+c#v~_AuNFF5,uKsnE<ƢZ|{\5f8GF@#=4 G<;˓gtm_ZB<|>lK~ux=<n9aĽ'{CO%9i&_z5NSm߾k=z􈑣GEihGĒ4rHCH#Q45BU5r448)tMUoQI#G>qP4z4 PeD>456+ں5_[Wb!Oꖮyrbq" Ƣj_vz<Foc#eݍ$ u&Rȹ3aMFOz|zP_`訄v !U{5KC]hiE=ǃ:v=O'꽴D mՁUƦ;֯__S]vXPXjZD^L̵hJ`ͶmtJN0)_m1㢟Y!# qRDju^=>ixjQHkcu<.wcG" {Q UZu(bQl?ZZw@HZT[PP[$v˂~y(G: ǶMV0z-^k4BUއH0 d` O&z ]zVaL)fd#Ev GP(ڎ*S 8A,YGQJoZ6C ݐĶ cmCC#lSYYyYY L{ ָ%Tn°"aLBD s*gV!ӹv̮vxa>SdMf@ (!D$ CT\ W t°b:-0333WF$ BHۜ@.1F l׮]wE˜ 1!a+zrrrڇ1!D$ U]]]SScF˜ 1!qaxY&55u:/BHD,IҥUUU4ʁ\yA:F˜`߾};f|8lzuԂ#*..A:F˜ZBg >Q8Ƅ ;c W^y >X;LO۠" cB)..?L2wʕ$AHzȲe>5j>NYp&1H coHz-;X>TgT:6&vs8FٵZGZ:ՆT/8ffN):Ӄ0RՆ%W$&RNΚL]!aL Hz-QL?9G;%cLfE/+F&$ƨ(;Q+#жZ[}B^P GT8p`_p*j ;=e6:^:*L#!rKyX?zk#VKk5kv537I3ʂ>nݎOLl9~'oyȢڎV&%Ʋ$c*_{VH1a( aL!;@1/ىsB f@Mäݘư-1 0kC6QY{f\>Gp!-aO)0n(i~#!?n?mׁ {'aL HzH_CLҩPP1{cdF:k$ C cBYbڇA4$ =ROCzX]NG;нA1礥ϘqۭL"z7B UVK/007o~YY j$ Q1A!0& D1A(F˜ HAnoA!5 ڗ}  c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!06+uNA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ P:' Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B D"H$:0&D"QJ˜H$XDZ#Ͼ2d<duUp:*Dll"\C .[![ByV!e<duUp:*Dll"_Ǟ|iqacs~sUՉc1&5'FzkFZO9Q;Ff #N8~' 1^=rܵ3j5h T$蚑Ff4jhiulkFxYO9;zęW8Nr2Up:*Dll"\C .[![ByV!e<duUp:*Dll"\C /[E@c~E߂(d9yտ0cgN:qμ~O9zQg^q˜:J8\DK75ahXrkJGrb'iWF1c~u'jWs nr2Up:*Dll"\C .[![ByV!e<duUp:*Dll"\C /[Eݑl5{'^Zxek!(*kUK1h-ȉ1ʢHEw~u'“.3~qaUs5z0WWx3SN=oo8n#sҙ̫N͈1W闟8]q9[N>Qcq'qZ}hX>n{% ؈Zל4c5\܉tc &ӯίzY>N.'#[ByV!e<duUp:*Dll"\C .[![ByV!e<d_LVʺtbVO4\~ïXW_39:c`6F޴w߻&x~ȱ,|/z,bdWuBGdNtŊ֎Rogג/:>~1q5dv9N9y3 9Ѕ?q_FFN}U2u/?|_~}DxL1k)g&17̫N:μ3=~so8kO>>W?>x∱W8ˉg]ukNwͩc97rl,{bBByV!e<duUp:*Dll"\C .[![ByV!e<duU|/ ]12۪!dfN(.w$ke. E#Ǿ2,=:IDATa+mZMN'`ta7 ?Q&ؗ 5ݑy}2VtOj8ض>e6fV*w X̽3]'6O{_sx1ן|an۷7__g%>E<wf.xጋ&y</w9w\vM?SOdf֑x:λ_{Ÿi'߼fug༿GUyGw$kis=Xl"\C .[![ByV!e<duUp:*Dll"\C .[![B!.V7ꨵvOO0Եn<gއ_1kBzuUboi] f؞vW5uݕi`^XK Ա췓cU&*[f/F5⤱N?Mh呲L8y̕9׾mn'={3>+O=cם0_zq]8/yzW O7wj¹W>z`:{=3g|ziy:RK//μ1W;m<sNU*J?+jCcHel5Y]1o.+ku_&v:yˊir6VUUzGR6 3T%AeF( j|aQΛNUωe׺Y*Ǯ߱FH3ړrC9_믧>|eSŋuMϹq#μvm9G{9:r ]pU7,y+ܫոko<-Ly3.}5ϘvٓN?Gbę7ܫN: r۾}D"H$DC\]l߇ߐu͕}rGzBs`ДؘfUpPD6 D>|üp>]1càruhlhG\hY]V1axȳ9Qg失W2~ c&Ow ;a#Ϲn{OU?>sՈ&fm;cჿ:S~w֯-v5꟏iNċ?z̯Ϻᔛ|hi8;1&<i` 9a~A]xCy1GvFβ[wE"H$DC\.ʀfdu6ud3g]M~xg_F?ixԱ7uʸ^?z'qbiO8gԩȎ<Ϲǝ&;gMy{cI\߿rٗr'r~Gvoߍ<~_'1akO:lI㯸+O8/>?7g'?›Ko8ˎ? ϾӮ;+1c"H$DA1ՕT'N!~ ¡\w4w?Qg_7 '</|oǍ>{Gϑ/9g0juN=n&pU߹9G~׌>ʓ^s9'^yOwco^~ܸ+{3'SιnY׍ȱWs%-M<iܵOu6rhc뿞z֟Ν0c.\$D"H$$ENgElm]qTFyͨ׎>g]s+G~7 Sն^4aX+.fx%$E1]ԕ> BkGv8z\>W{v::tWx'PMޑH$D"H4x$~l$.c`cEOr'}`D\X׌׌ JY5a#¿M1n"TRv_lμjکmTaxM<鬉'u-ވ3qU'Ү5H$D"hHIc&`4I9t\UeFj? $2N^Uc#NF[^ʏY-lưV}NN+GȒ[gYq]" D"H$ *bD鱆bҕZX2ieTSFK2tqվ]mh$dԆj[]SUTD"H$;śA)vl5;m[N'n}H$D"(J$~l|'5u.VmeorGVeH$D"(z$~l|2Mр+Ď٪D"H$DѯXss2>_`[wj)y=\*̸qOVo5^]gNƥL>h]BdQUB|ȗ"H$D"Q?FvwtKMA}Ǵ/RH[BmV*ve|E"H$D"Qc?oϔʽ[I*f*T~vyvEnw{YW{P|;%h70*m GM v*SIm4`Lw.vb^U+-D"H$SOm Y[R}g *4nF)k.3E5q-loU`/ҝYۦPe0z^]ۥVm+=v?2_iH$D"H k׉"y qs k4Q[w=g ʲ#G҂i'&vRNʹJY@vhTo\ٶ(H$D"H$4uqR?<^Ow|8~$ŏD"H$DEWZ$D"H$EďD"H$D"Q+ȏ0?UW$D"H$D}-/c"Q8K#PN+taH$DA=n߻n;n}4]Ռ ut[}Sp((ZxAIU]cZeSAW!a[BG"v D"H$uÏw㖢ԴmN؄B<m6@3κ{[ZC"kvBbK®?pӆuTۮcz! ďďD"H$Z"](3 6nmmyL߆e;Q5;:.cΛĶ!Kv/7> ~ᤤm%Xr˭(autscG l7|{T%c'f /+WgM? E*s܏x>t)Allg]?哓#sBKH$DA1]W7py[oӑӉ%pZ]l=J6`^VWf=tRi{ǬmY] ĬB_<gZSpsynW#(Ѽ'S\̏2Z 2hm͘B^UtIvBc-Dh^KZedYVM7e\tlYm+c"H$:} ތ֢"clB6lSWA-1mj|K7 QڒMKR:t-V%Z󸚥tS|o ۪Pt׆?>Q&Y4T9=^i-\hȮfLaUdXG~ j׌AhY E+&;ڌYB[*=$t]ue)nyJ~̨N5KSAl;IH$DA1w?qkhqֽݑہzpY^PD~nmK}66o膘at:o֎:do뗔Uf:Ť$ȽK{0cEmU'^ 9AՂC{Lg}^?h&l13aBGymn ފ2QQ:D%['!ՏQIY2yi|rV57JH$DAmn^Nĉ㡫]^[%rte5gb1˼KFQ,v+٦i$m3crܷXaF5cd2 ,wG^aeդ!kB`)lUHcݕ-?^D"H4(ճcm2s誗,ȎAm~G==DU>PS #,6[ d>{ezs?9KNB3c?~KH$DA(%P8;FmPĀ.: @XďD"H$?&H0<.[E"H$ďD"H$D"??$   %AAAc   1AAAA    ~LAAa`?&  00AAAď   AAAc   1AAAA    ~LAAa`?&  00AAAď   AAAc   1AAAA    ~LAAa`?&  00AAAď   AA!_SahZ=B   cCc  Y:AABA   D]}%O^0լ~aKܸ(in޳2Qfw=v[Ur%]:s.lޓZVF=j?ws_yc+E!V|0AA!Sf,௬tPM.0E%1ls'ƈAAȢ/mrM'tUz0s?'㞛+k1AAA,zչL.[@/7:vOO0Z?&  E~L4AABA   DdžAA!?6t?&  i{an@   D"vSǑK   D"c  0$?AA!A(~l{u. g]n>,zQhYoLwN۟jď  K?36,{V&Qj^37LX%~LAAP5+ys5n^5In57+V+kcT򄹨Tp1ՌB=Zw`D~lWBAAL{eNz0Ț.˚:"bY .4q[؞Ɓn*G`l̊1AAAt5LdgծC6Lo'e3m1"ec_l٥`~ұKzYoTԀa.ď  [L,Eۉ|ď  g~LSď  @XnAABA   DdžAA!?6t?&  5K7g ~LAA" c)G%~LAAc1AAA@ď  K?aKxfsJ>g %ByKg\I󞔩F+AAaHХ#3 ]:ۼF=Y<yyœԗ.urVHq .Yv{a`m:vQcc@5^զ?A   c&)2]۞0UF Xbfjɬ`x9=luMXZ&iצ?\9*?&  C.Uhd3F&G^|f^թ n*ZשFdTH/k5@   B?fż[BX?&  C1e~P ď  gDŽ>E   ďE z/ݜ1AAA,ď ď  Bd!~l ~LAA" cc=n@   D"vSAA! ?AA!D   cJ<al@zCtsNU:yOTޅ3l쫹y'w6L?&  Cc:#`.q<· \`37:c  0$zu(~Ye7hk6ԨxhQ5u3Jۍ)vw)kǰ-ZnU칹[0mB;L􇁦Gʹ6%!"~LAAc~p1=afcQ1Avd^hOJ"X#1VsE.Q5k-T5>؎3@f>mނO]AA!AH~2TtoJ.{P"=r50xZVwՌ:v?40<S̸|T2njoFY@F{5$AA#c9?3Æ2Q &"ݏ?AADď  @XnAABA   DdžAA!?6t?&  5K7g ~LAA" c^ ~LAAc1AAA@ď   D?w=ҙhnWMtG47Y|17tˋ\ͼKz^n좏?&  C1..EN u.Ԅ2 $-XSff f Ǟx`ʦڭLVPmwh7{bcYǂv7+k_ YWuYgAA!A\f!]1j6Ɖ}m[ئ}2֏mnS6gl~>T!~LAAcM=ca_؋ <;0H;c{W͚? ԹkY ҏۦ̸m^e14y?c   tE~П4Q'^3?&6ZÁnKÀ1rV3~!}R3z?&6@% & c9x7   tT拏3k_67uߞ:AAA:@~$~LAAcCc  Y@l;tsAA!?rc  @ď  @X"~LQYYhqK/guwwnYSse% N~y_ɓ;,W47Y ?,z3יC i|>ItHj6Ў:@VEp!cې/O^ď /}puaZ_x1t& HH~)3n!)wҟMZ_w,6Lٳuɍ\̀edq\&Zo?&~L\6!jWFVO  #18a_w=1eWo+ɡ[L.*U4w5u?~;'  nM )賉PP<N.ښ:.;4! rf<DJ 0PǴ oc9Xu:Tܬfw0yusz[#/~ѲyNal~̸?fMw1A@g~,ƿlk?PoO'Z%v(Eh}_, ,7R~5^ď E~{R +Ə)륾DžrInywC?FL;5<ڱ1VZl=a+hsi?\e@rNpx_[ v*~LA~ ?Vύl(U-]x H&u[[7^ R ?pI;TӆتcSuhGjj[lnud̸:ɿؤ&~LA(c y'et~H"~L0Х{B"Dz NRj }5 ;KA~K>,ˆ:3=~]̛iܸ_՚>.W$~LA("͏ @ a ?B\Hly4MYqm^oXwǨWTrȿUTcM<c B$#~,a7{ ď Bď 1AZx<ȰQ8.3sKYYҧOAcCc0p=KfpĆo:ֲJ}pe۷o߲eKZZի׬YiӦ]OAz1Ax<XuZ;-!Y :M`2334>v؊Bۍ7*WUUYYA:BXbX3?&۷_e˖-al z,Gzz:ڬ czǬU^fdd8N]˃뒒 m6^n[A*"vStGa0K|'|\ه[OhCqq. c&4p;W.((EQEmm-N8N ^̴4x6XMq\0rMa#~,?&]B+==WpbzuME}CjWTTA^ <n`sssaqສ m@ď %%%[l6 n%>8ק~ \ eZ$cIUcé[m F~y_ɓ'u577+~Qfcn&w<׼ҙ[&/F]uO({ 0BknO>n#4+~L۷!tB /٨`ͫ~c&. $55T mpBp* iii(A=+ 'es%]l+(UrYv>,zOFKy7.BTG.vO^v}j+6 Pzuv!~ >FKOO~k/sq+7ߏYy+Op֏Gfdd`TLa K~ i @{W2Yw`}6f ;xG6ȏ{'Tux.ԻtHda>?ŧ~٧͟} ?&a fퟯxu2Gyy.֏ǫ.BF{QQHPͬ):ܱ鬺 7z-I#A1}[J3 6qF +x2[`eU?vL߬T@MjZy#OSc[nwqq+^09|ohJ@ouQdfff¸br8i^p=_O\+Wt==Puی֏yL?zWI~K?{ma0?c&tfP~?1A X,-W"ײ+V*шW%/LϥK.6(,,+"Rp -[,ryJ0].G ӎxR坬hTBXkǨdʛ3%B~,\ ]'_4ܧrLRQQ_JIIxIdS]] 'Ɩ&55N ײz]ăkn9 .T `Ƹiii?618xE-**˜7?w.?̃ezjndA>W-\ %[(76oa[YY5ڛ1Aȏ >O?yPpYիWWpUWG֭c{`WG8 T0l0`)?9=?wqbYj}zw]Kתk}nwtעk*+kjk;w6x몼}Z~k??>䓏_͟QZZ6قiO聋/}aGzꍧ׬Ymҙ`+^)))Vt\Gs/9uޅ潹Dp\׮G;Tw3^}eza"'hk[&Mv{[C/]60?f-X?j>y}Zs\{mՄ.: {>};ߟ/.>}磂ҹ&U>_J>8o{~ |qKla 3^MH~E cfcBYzɱӏϚr}秪 L|. QW 05짟/[Y^S\\Bc5⮑֮Н5g|{|` ".?񿰰NO/--'kQϿc{w8ZԲ*\\ b-éڑ篼^[p]^zJ #147+67DŽ˅g?gsJwqFa&*ҝ>o.᏾y!{&׬:f16?lD(߾[<Js`'}!\TUUoݺ 0eeggu%Ŷm0}-[ Nե{[.H1G1Qxr ;vd#1(9#1!xb[bb$ G ?Cu>Ta.Q}X п@l;>}g~N?&ct? jjjJKKu'w|\.f 6_L7 :c>,V"8#d8Zeqeaj99 B#dwm嫭Êm>YA">?Ͼfŏ =s?fVE~³'j=mJo.uyi[m{o_۾[|r6N}b=aZ>_G^??6oZު<ɚm=> T A?@#V2v=֗cEqqesrr.vqƤJ;hSӪ??2ZeZ2lXX;ce55ʏѓ<X&#U"B?lUvtʟ4_?&.؈,-mo0~򥛛) >i|w?򖯚ۼi_ܬc;ˢe~Cc _"m[,* `Ÿw[:N QvM?rel_K Ul 5\e]ׯ~,bL}qY;+gUi6f' w4K3=UfQ?zm~`]}fuzٞpo=T/oV/A?5ʹ /66at Y,}*~/ˏjӬ~L*iFj c4~ֿW *;; ?@~,&X,؃NgӏU㲫- cSYnSN-|০;x-ώoQ&͟~)YB؋a.vUkrY(y=ZxLϕ-?fz$mYb`x`u؀}2z{*m13Ktr?thm~z)ٷS³c12+\V)^w fUm Y}D1ub&Z|Y'?(,m& ^W~9+ ?f3}9+cQA~~?f?t bi 1͚+?6JbcZ ?Ì sŠZv͘RO&ݢK?ּ肞SfnF.;QZ߸L-47Y|q۟xS!?!mT`vx3 Ī'557ia ?<C119_Xo}K{ͱ)qiiܦb_vlcf% 1ldU~w~csv_1uNobS1w%t}9Q>ز?u@SYla[1Κpڭ~,plF1UISz c\Y|'hW\XT+ǐ3-5mǚZ84<eX,5 ?6q7f<5:q\7BOH¬Q ;aGJ`:A7rS?۰dffSMM O؊̗lj𔣚uC1cBOo>g&X)f1ZcP~^$QǢxCv3Zw|ql =Sqwa1>`èu0F٬' * ˪J+k*ʶfggA ''#n,M? pK9A,.1:f}ccâ.dMLZ;Anm{*5 i[7n{Rx ǘ~,xAw"ijY=US}a⍫L3f}^(>5xcB/A$.,,|c$vYB\ii7xy2t| }zͶ¢kz~~/.՝5qQ?)'HTW<VkCX6]t[1d9bհluh{β1,x9a}Zuy0OC<Ǎƒ•¡)F(VZYYc Xejkȱ)VƊ@p1E |{010Wftljӈ ?FI,.P/pc-`${ }(m1kM?z;vIU/K+6uyEc?&t B# غuqsY[s?/'sʨ{FΜ5&V/  eN<=F8uxYs232|iNqՒ)ǝ> +v\Us[ᦰ>g;l-zQ=ikA?~%D,u-Ͻofe{5t/ONSY'qɟ:/,:)'4}f{{v4ռUO㯐_!=C{-޺\.d;f0fׯ_|yJJ bǶmPF ##Yyj.AD-;?5˸٥2ifa3X`Kge'X2Ԅ_Џ4hgK!UgFl~*Ǽe۽!f'ڏ ґ 6mљ!γ襪 `FFGuQw_RRf͚|j]>u o]ې!<>7YTB nO]_n4Vzk\;vԹ;6l7x})pBJKԮbC ،1YYY6lذu۷N'ZFi%\^!QH~, d= lUS[5`kM4맟Ŀ>5`6ďY?RPP`|wlm  zSSx+]0'>QzkYP.JP]qֺ<XWO C[[Xk04>d1Ϧ4H(V Ӫ:1e˖ eD%sE ֎뛘mҎ8a+t&5[~&*Pfzf>3?6AOfCc5YYYk֬-E*b`'D(ʃF0;Z>x 6\ZǬU oF~JhKZ"%JU oQJc 3v:%%% /QHὠi0-^Ĭ̘upVcVXc͟ K&~lH(5̆1+" xqX\\Lp l`E<p:OO'ԓPtUr2SJ^JH*kKChSez*΢ 5}ZZZ GqF"Qެ3̅XZ(Ag}٧cr, %HD!~̊4}WUUatݺH<uRDZa kHc 3=Gp>e t dQz7 iFXbEjj*N$Nqe_uC}ee|bsnj?;21}A""ր?fEX배"sCpavHpNuAoQ]"t>v#fiUZaXKiK.ۺukyy9V>6{Kդ޵ 70cǢXF!~̊[xaX*McHj 6]ib=@2 mO 1DR77ӍNf͚͛7íVݣp0?6ig+#="zN,RP<,2AWk"$ -Znm7p7lܸ TUU1zp;ՙ>;X]. ܮKYYYٗA_ ϗuu|Xг7H]ó@,L/9%YE_/A3fkh7,/8H#QPPrJ8a8R8Xkmչ4^#P(t foN~X 3]vt.z:C+k&7s,RXXaÆl$pd~#kM mp6Ph-mmu a*j*`wjQQŋ'-[۶f}AnUN݇W :;j!]>@ D榤^|媕[/󎄰WLx*//Ex/GOvXt)L^7`"ڲe ::%]ԔBp%\g m۶Z /yxŔ[]]s53'RmyodF=sV*NpDFyee4H~H^^?_.m QbWE i0``⤁#*@aG oc׺Z7?6t?S@. R{C d1r!fqܛ6mM=?!?ȎuNF- 5BF׳@!44Qջ`tB7a#*qP[fLzEw[+]TФ\ 5S-,D!$Wi)VpoO.˨΁ g8UD 9^;{+՘ +yRRR=t z^YAM k:x}Wxl 5>hѢ%K,[ qQ</&'u1*TTΏ!K41]~6LA60K%Z WVVV Wqq19 644 j\yC $8*1!YDXUCG&@t*VO6T 5]g Cwcх~,!~L74CW`mѭ oG.K332Vez%%%^_0U566"`c'NJ^:ܾ9SG/C-!X- P9]0i{ m^mK=Pز x ;a^KaMky:su!LA8)E..)F9~FaKཀ-]#[ 8 !\TBӁg 9kj}d0 @D`U>"^)-[ M-b@ރ^„CW4?sڿ9p8k^\Sŀxg%F\,_n-??!T꼅{B#:i%<$}skVb4 0u0I5Oy/rǧZV.oY""׏]M ڡ[@h Or(zPazث_>jd2&說*ӱ`BBԫ 8и;p; ȾYf,ྰE?z iTK+{ sN q"Xsz\ ۋqJqUUJ$]5:oÎթӊJKvxU6^└m#/^lP7n܈K^wfGp9H]RG\!R{\;]. @ݞ:TT`2jNW[ K+*Qªr:Tr54j+=M LeznQD ꕖT (Q,afDDB9H?b \NExCACVoK/ؿюU}:`%91Z>SX]]qa061cV]:[EfaJp!ɬVT1")syKSJ9?]%VL^01 Wt޿o?7С|{|"M~{kX|:(B1":ZAh5m7oZۙP}:T+>~{C_aWTC%Fj޽.q5'!0w*4I|WclфIO?=k;w߽BݣEkfbIo=3gђ(3gB6PSB{Il0s֬\ +yWEKNμY @uʀVsU ;>}w}_0?7/M s<^PWޮ;jkoI{tsϾ_i;?]1Hɝ?TK]?=?9c`{~[3Nt'\E!NE07?:g?Hwg&#s<c91n]$OfenxbgqwwWrqee;Z=nxW]e˯yn/9fU81DSd~{~{1Gm??M/c~r69w~w}l/~۞_;뼮:>UB7kA*%:wY ._á7ׯ__#D>*< ZV>PuB.宁7ĊzoF-ϫjO_߳;~ EWHKU?GJ_jI⑌H~y19߿w 3~yL;}CѺJwEc>tU (s68^!z\?VYYw^ّ#-֖hA[[[(?omEi*J*U MKkkK zGVf#6 Kq60bęӳ.v*TleKĤ3%%'%$'%$ģ0!1$&&&%'c5T< %$OOLmh $aK1ZEۉq ]Mf29>$, TPaZ7-Jj JKA&I^>O]HP2Su{=Z]zu'>q0ǤXT(13r8t,Ee3D *e\.|Gۺ Y0V8E9 w}fK$%wQɏqYE齯tp\p$$dBSDS&0rdG MAjm\@̊w8b7|]UWΥa-.oשl6ap:UUUl6ꢢk!`ƊV^xť%Ӟ?[j8@W$Iة1S1nɑ*]d6w8s |SP뫅% 88Z7RŏE8x T֛Gu> Ë9t .:HSE07䀈aB)B$o}PFo1:c( F;:|TB=7Pvؑ3w \1jnb--+}@H$vvtz%O<ddP4}dxرIq:QkpJJIq $re d5R{ӕQ.(!.))aZ2 wozXs&'?5)ajR"M1kD 6DnQY>e-_\<'V;_ .O9*v0](WB:t$!6>m:ר{FenН<o>{f^z9v"_V^^>ށ7^uw~[_qtܤ̕4ԕM\_a3YaP\ .+D0Fן)VWct/^Dp 6`ҸK ,';'---5%u \kZ*+gKqi1u)ç|7fB 9xb8M6<4PcIʦ8^zeOSuM_5ďE8uBYЛG5k'9_}?푯ߑͭG_~CvЁo:@Zh呏t @#呕C &-Pu y-K+}klD7P~ß}`7G>;DLA[}SgQOUo>#e![hT>#s7l'dee' /Ubοn4yrRr2Yq S&N[oMI.iw:%i n6{=0)9뮞LNm7zԄS>yZr\|RBrۦޕtf$N:=iSfLK>#a ࣦ݊OM4 /!qZ|iIw$'NJmjRoIN@mq>eRҭS<:ۦO8-qj3_t9n,)nzҔnN쏉HH4=!I{e p._O]дo**}U. 3. \QM…cdpI)$_sKGlWbDG̤PHďE\ u{ݦu={LJ<nNr59qKX\"n5gUշmoQqPYSNzEW` ÄC_L+sUw5e˖}c%֦۰qÖ̒r(9LCRQ ~Fш8MG è3Gu׬O%${y&8ӹvOЏ &ďExɴS W@)عŕ rտ{%c_9 OGzv/AniZ -+>YZٽa***~衇.V+w JKZkWͻrzg?ˬ'tUi/}Sϼ6fi'{s3cŊu VCѠʱl﮿{0 coۛu%nlHUy~7~n)r؉5% CciQ|&sk?;}/UjUؔXDQ*I;5ZJūr\r#HeecJ,9xٲWP\1fKtL wv97#= :sWFfMP7Wyԩf [nSO55?ۇ5A Džan&\YC|v5r۩m?FiŨ6x c^2m!~lUJJ#p@oͻ$qre6J4-S ۡޥ󼗲[Iv"զ.+\NۨYXKYo le3^¤}T;ßս:{>7Mضa[ _}YT{9ߌ60iq'{ ֿ_rr ~lK~M=Q͢f}cf5g?vY;oW6f=_|^,Żէ[צ=3w`c0cP1$>1d}_?&Os [_JޡzCU ~,`VUomcmܽo9=z)Jle?36ɸ`H1Q8l5'_w#j-{0$lǏ/ݎFs<3۪Uu<ά 2ToJc;zkӦy& uHjU9O*Bj.oq9)qg K6u8yㅪ2|GvgcJo)]:DT 3d3{ƍ>h[A>iӷAwִRI=~׾rJNl]~cʽ߿C~O?j#-Ok׏YjXwhq=vg3>6gҼ4kK{~ջ{v2t$Pwɞ}\Н>zcov`#H`àp]i/ YlYmϴj u>˴a䲼mcJ V\wvk3l=k6?.ɃMSȭcNkةڏ=1XeMe-݄bN6>H [չ6nXȏNLɼ5 Cc,bG%_ Ҵ}3;SϽRuM_'#3?N~LQň:DKM]dZe钾 `"~c}i"[_p5ٮ͏E"ďƌA܏)E#]`zZ6mKf_B2o2vb&8&:s0N }q敮юu[L2惈|ٲ5:U7؏׼ꪗ/)1:JO_?cC ӁOuLE?xٜ6a@3E~1НRRgn\RZZY]wu>VNZhUpCR#~l~,==p jQW(4?8{+J {**"ߏ=C>{f^~%v"_cϼ 3C'\cz啕6nCQ1PDUNJpz>5AGƌ Q ϾbUu]StN] SOXZBԣ^fܵngYJH?SiP)Kd:+!a's;f؏F.hB^ca }鮡_Cj+*p1~}ذ!=77nvm566Х1(tN ~l~o%TRO!T?(!OJ/|=4-exK DkkKkC~akl*IJ-8]ڝIe\Zܢ*[Q-}]yW\\V_ E7g cϙ>mڴĄxуy U^COWOa,ȒU$oL$K>-aFRz$=HNC(4Ӱ={JNH^'&HLNާ_F qjvt(9@MQE*KHj>jMm-A{=>o}}KS:<<ԞrZ@j4%v.6[<? E?n{f?Խ6ႇkY~'Nr?osۯE4d F_uUZrwFG>!AS0Vfn9b}0= 12.V87;boB oϯzKT~1~4%JbY+:%D5+w~]Ɲߣg$5eÆoÉi@Ꮙ]5Pgcwc ssBeT~wں.g "OOu[>8 n,'''==}ʕk֬Aْ*Xl`:4@F2lސď "׏QT\\ZV" M PY [*h9ZC/xbWmDqj>Xxw֍S /nt}%nkJJ22lnڱs]55NL4jnÁݱcً/3g3g- ӎai\~VI3ƿ&UzNI3Ocst;1S5WzRT%QFM@Ug{_3g ׭_tt} ކzO}.`>8s&͙j)Ι|SL|kqW>qX[1i򫓧Ι2Em{s:ҹ27D6^r#|{ݙ[8' Lqr]|K`u]ߘ9#H;|TVV-XOu[m%i+dtpaK5,M}|}ڿINVDO2HsCM S^25OBL2< Ug汫ng{zs[swhlUWVmڲnݺ|$u!L 31!やTkhB6=uŅ|N럹o@:U Ec44eN\IX{+\ ^haG q :y>q͌|^ZIU;UU*..˜ܺ5t]4$a5 #A}z>kHcí/_|Æ [nݾ};g,A  .=\&i_.f5kj\մ4Ɏ~Wm>>`}Js5܈~t" =| 0٥$`sS퀦jtd\nt,놬ZVt*lS]VԺ=8 zhfZtG BpPـ uiXTUWWT9k0Yz_BSVVx`gӦM8]:#𕯇 BnzpA}SmC& ,tr䂜NL#C*}} ו QME ZgYxSlNvKr O[SZVZUUi36% P0rNBQKQDTW_8=7nWWfNFgFۃUU28aLtQD^Cx=A}S)((.)),q (tbX˜?-W+gd{kW6oe @1E.`Y1 SЖ/((zv6ZdH]tJl>j(TaOEF!N)tWV3cp@mU`1 QR3QC'?EBB;ק1zk. 6ioʪk ȨN!T|OR~ Gf"Xjvz25YBrd1`B1|/'\#_!5ݣ.t:O==ռWKuЦnXmOk(br۶mŝ4$X]be̽ 8.7B@Wx(`41rTchDTCǍÃixM7AC.;Lإv׈F+i@ tÆ k֬ǀ4"aubu MVTTe 4NMMŻ Qr[A 0bFŵLmVfoU0YBsPe<*FO1v fG}Ӡ2PoCq mR@Iگ"9n444lݺp:@"\qfdd_^p0[dvxR"?A4@|/SuesR__%6\'j˜5xS@ K${s~R'5_aII?k0zqab g;vE3^=۠ tpG?J=ԐF<1H8.8%c fu4 ƴ[GKOۍh4Y Rnna;wzo mBD!艮$=ev OkC糽v g q]( É)"USW?7mJj{Z_B[1 ?^[d@ *ғ'Wq}I4 X )xkjG TTkV\⢶V Tpii).7oތW|L]vʨm! @P9=x+ِ!Cӹ~L#(lW=IcTDsNII $)++j< MP;۸qcJJNg% J؏ a{ХB. Bzە~2T|d@SXXzj\P|0[d!I#لeu ݣsk3t.t8|R`n \v܉,>,Y%(;؊f`=n"_0K2fLdiDzNg 9Xzm;aK.ci(ڲeŋD lᐥ- 7QO[KOOs ٟ"c 5_itwA$ }U@"UVT Lyfa avvvjjjyy.c[d!cL:11%x6c c4}5,zqɋ.d}mݺu͚56lpIIy VH2ՠsnW62MX$+^< I"3mTCax08R $Q~~>͛sssj`AO fAfddxDN?F`C޽ Nvq<@d@*((΢pl эBrZZƍOCЏE}#%o#ko=HЍZW`fcpz۶m=~HS}nѫHc:;xHKB{Ӧt^&0eܼAhVcv,A9&0&a~081~Y1=t"az!bFcVIq׮]|͑]TTiT@$PL?JJJRRRrrr0M?fEW<$"pΝ 6== .myb5,SS?컐4QQPP܈'7͑`x[.rNp050_ N/W~xű ڢB HE(1u E~((ā o+oB?&Ⴇ}/իW\r˖-[jUn.=3B:TUU"///Aaa K.]x˗,Y^7پ}&Ś5k0qz B]:F,T^\~m+؆ W)HbccTO&=A\*JKK11j 8F!AtƵ~?_kK_]D:OoӦx`û/V5w뼵 Z@mۆظq#^ц﫯\o.&dĬ6 9G󚾐z윥K.YdѢYYƟ+z Bqa2IOOץCӹb }áqf*({$\ c|vkk6oXM-8yy[U5wBI;Sr%i= ,FpܹV1UWWÃUlXf-Y8;vNE t'\Bg>LJvઝ-g[+RMS CZff&E-[:[6} B9abiy`A,(( j?&D%*T嘈)7!ruNG 'hGWjꚥKeg \qӥf26zܗ_xʕ+"< :?@DZ/]Tz72.q5Shf0ŭ%cu\MoiZZ%K7m\SlG hH38 fҏZVP:%e[p))o1D]3*gT=3O,Km!SS9%b+|:/A bgz-MQnMO5Dq,k׮[@]japT7H_?4}W'%&TMt䤤Clܸ1\G8\jC 8B5DlS'&}&VN׀Xuǎ]\dTrw[|[ ^:==IkD 7ocǙ6oF=@dWN#}"++t:3JlS<X\aH766 NS\-XYN Whtnڹ{ݕ9ٹ+V_dҥ^ܚtaPg]cwא1!NnMT1'sGӎF>—>C^/@x𢘃A$J<H\ʳsk|׳dF,ǎGlv|vNAA+ϕ R5k`WݨrJLPc AY07m۶-\GMLL#ªx`QaB<%'"BK#$tk䄋ッ?8BV+KSVLx%|16u؈FۊԵ=Œ3X$%%͚5{eammۊo{tzݻ7???++ _ ͟=~nj*ةJH Ĕ)qS iV3mVZWB}|7nܤ>{ٓVy2x[R j>gWq|Z08cJrr67w3裏d唔3x U6f.Zry˰_yuP ~Ln8ϟ0@RRr*Q'%'+%M X;0g,Z_|fs>,,S'&wl*~k 5^x|pϞFkMZ--\ o߾K ә%KIJL4JD̙Iw\H(ߝlνFF\:^qΚ9+5uMyyyBY 4* FwLr<x_WdcxYN8"uPtHƑVUU)x;i[a8rV\5~|^G}g!.VgSď ^<<]}"`OR HTtXͮ~`U ^϶{;px9Ѩ{Fen87.#cCgfø{OFfuCݻwgggiիW'Ӎ#L_xFE23(&p*=!&Q!L9e(SRRps9$a1dB^ґeўeG X>!=csƖpC}~KX.;#0cBb",9tcc#&?PSq/Վ68]/?{;ďE;z ]  \4 O|9+Xӣ1yͮ\ cEi{ҪV?f%Z`[999]^ 2xُ$a4 ‚1aRTTk/>=Yp2B>"Nڷ౅X?5EW5HH~f:w,ߗ΄+Vk:cG7_h ]?\߻o+ďY܏󩮯g^ڿ5w6ϢMT1".^-fl ܢC~Õt%Zeo|fלΧ氪i坴nZobn}Vom+WN/UVx{xT}H@l'q쵝n46n}M>>my6q}_c 㤵_i':N67#W$>3IȀ`L93 0+_F |>9hV?{HVJwweeJUzNJ'fQqI f?7S'ev̱ο+yZ]t j* l='jܿf$,})644N&'7|Z9nz,#64w_>?y敵,ím,ylOcoLؕYc+&J?.c'\i/;[OcGaha1,417\c^%KW _n'f[Ap *ҫ&oێ=n4M+7$D19bkȲdfQ[6䓁3NDUxvjQNFLm' Guϴ<fݻ& _H|%U!0yěGƖjautN >c;CջL<ƒ8}TĪ_鴥b4yKo q b1Uënj<:OS$a66hhS" IŐ^֤Oos<fb6N?:Tyˇ?]*~2+527e!-TW:CfXY;~c$VPiK.ipޢĦcF}5jP%8׹yN=nr4HĪ鴥b4yKo q b1Uënj<:OS$a66hhS ):\8sPOǡt:OS>w<c͕}N,t$o}7ުVnVQ3 򺯸FcZ;wS3aLOjw-c+gy ~\ҖĪ_c4yKo iq b1g>^5LRu7<gp w]OG"5K^9`VKۑcst\'Ti&7 ܠVGϔRy}"g7[_xwqwc&M<d'lRz\%<K+7L |L.;˔<6k45VֶRKZ~޹\Swn0]|LFdc:[cN2KSTFӋfX4DG=L1^Z dP7p%D-oNTyu7cL2_>mse1DcfSRqvz^YzL8/ܨcO K*yÒ+3<1'kTdV5ljGuffg&Sd,c:[cN2KSTFӋ<f~\Mmtgn&SN/7y2N?_VKĭ6%ɛ1Ik&hgc<f1߯KksOTKS|̍:6J$eI1|̮|̓ǜeKP>NewX4vLՎ\HL"a=] npy o3b*T;[߱O^XV,]Np/7ylaYtM[Uy Mww~C`ۼ%kylڦssg\rSOg+E"+cfkj9ujρ-FDzu\V^y}"SR<hС7(}=;&)5Km|~/2s #a*.)_OO~o;E=3x.ۿw[yM!#,]ʿ;MG"vV[[X4Fhs|rͫs"&t{M}8媮]g?{z9Yt5:6n?Cӧzf+ tX0o(<ēs|H488XQYysɦ͋ l).Ӏ ֮kz-[֒2z֕d$ٲgiVY_q=#ERٖҌ/YJ*z{gOwwO}C6-ojhlU,.)+,*<.s3mi7y_ںFe|^]/Ş݋N-۞=kg׮]%/[J6<gUUUv)vU]]]YY!)se>A 2l߾BY4!YȈijZgܑ̗<AYooo]]]YYY[[[~`v1>T}}} Z[[l+@Vc˛eٶy .<appP3 i3pc|K臇[ZZ./ y ?6[0IFY[[ij^: fΝ6ma[H$^YYY[[w^UXc(aL^B'+J0ATTUUXc ee\sg{ G"V}CCaQQFޝsa 0(EM'xs{yX,f/A6˖8Ʊ[y @|SaUW"z1eHf¼u/go[mzs-͋Um퟼pf{y eyE y lylSgd!bp|һiZ69vha (9|^PcM7YS教c]vd^5/?)W8n/dO!8QW_}( y ,4lrdWB]'R+:erx)O8ylrE)od̓sr^2`fs&;poMfg:̐^r&L*JIX:[ӓ5EO JV=>lFnf<M:) .G?=yR69H(}RɮML=RLR^y !S>J-i<fܼ{򘮳1:Tu$ج<lcO՜HcLdG|-BvlGfrǞհ̡H*J1SһUgCpX*Mɇs\=;r9+lV8 M/kF3ƧuumyB]΋񟺻{zUX,~C|?()O?808h pI*+-P<Z5u[vo<"Hն Z3x֒7fϧXIffm,dl:[u< ;[^^i1X,UUUU[[{!JJJR544gmxxضsD0/CCCv3MpX<`N$?Hd2) vԴs'9{ =IEJ@ww$՚IbH$eI$gyeigsssOOYvXc"  ý3ve]uAnii$/7gbbe[m(g=qi*dA`0888::*;Jw G253 3\9ؘz%ʗMQQʲLlbbB.Xv{,7W[UfF *}U$IlxxJ6Z}7ijeF s6\aͲeY޽n۶m4$ʵa.fL`3±r̰rF!dr5 $W|-u/nE<mTIsJ– cBY▼ʪ:n[JH3}f6;zkV ɟeN<!DupsiOOgAɂ_c[邑CL$9;6yȔ F ry``\*?{Xlckk*ؒFYʓd0Y*wƒ:${DigfW>Y*̹{Kg6ʬ ,54LWw0>3Tr,ܞp9'5e̳XVͲxbrDݰ۴UxXTcb1&;jUrO=*&IniLiP)nRFvҢPݹsg}}8p@";xu?PsHhI?HԢڢ;)\zƶdF"tQF}pFZ.*s4}Z[[Qڄcnq[\1gP sHg9ICCC^p M_cvb y Ylļ !rQ*'KXa1˫,tKH]vͮߕޔ,;m$SM-Mt;-uM/%'iݬLL^r(Jjfs@#ǐe-rޟ3tPl̲jC{YOc"Uy5oذaݺuɜ9!@<,01g*/V fNhl,≑[?*}2{ɂP!Fr1cǶmUre˖[Jܵ˂7& =#j~f5駷32ۑҍNݒ4eWԣF %MJP1$wIr#~~ *en1 S3]qVEF{Y+s.<n#={JKK7n޼}.s`f>;un>m7g&ǀ\ZcϒH276&͒:~H$U U#2[ᨳza]5qo(2;Ըy-ŕk[f͚&I&rKofFrnT2Uf9EEtUʨH$S?%dP}PۻY}䪨$l3@^*,̼?:=Gڊ "&*2:<t42[IbT\GGGaQ|rMP[;Ȃ08e9.Au/Id֮p1!>KFG}P$wO_WGwGsw[ݮm ]mm m;ڛv7WYnloƆֆ憶FݭqG,4JշJiټaƊ[6E41_RdSOē Uevyli'# 㣒Hrbb|xdu{WuEC}up:T5e*g&Vj)}wIuu5h9kp`h|l_2ݽdg6H6{1d1n\ooowwwMMMyyEʊʭBWTy.KS=Y)+/.UqұLvUTa#zm*J 6%ܪf_=RMDJi(DuuTȦ5TssK__ʍgś*Iv?޾N~{H<cckC~ pg pW^T,rp*YW*ɭU% LYki`U򗬼{ oJ?GI3 b 5OFQ.9"alt_R%nO<˾]/X3%eιM|UiyEo[~;:jJʊ7mX_^[⒒=i_c~z$=ǯ⊀ )/ٍTiWtɺU͆:\8 9m1";Zl'Z6a 5,OPRQJw'4W]uO?s?0688yf\%o]կF-t V𝁐`kyf@p-Yv0Bw_ ^ҊH<WOI$;[715^Wew sѩ,kRӓw2MvgJBK̗T%PPe8l867Y[K{:zyZ̷I0z% S$C=rZFޱ+5Ť2:Z68C8cϳsr=sw.Ɇ 6o+\꺌l<.1>̺Cw=*WC+B*{|-;yLrGH_K6 ޓw #K$\kJ:{K((+GcilLQ?#K]'Gb>jd9p@"Ӗʹ UMet6e&/H:8|K,P(Q\D2P*$1%Xl|||ƍ_B'K*ErP0\ tȇt\@^~@dP@ͰF($?^&{Tg7,Rj|PNRJԫCpn_9XXM;$3LuқsPLv`0Ofe6 p^85[i / /P8,ȓ m޶l)HJ9"; cF\$A4$wɫy tkCYnp+KsSk7gɆM 4o%_EQAkEx%%=]9yp~X~շŪ>X,~՚ϭ R2=yX#~У+B?[.g|d{"/ƾ*y5gQ:hW.>Y|>6<}<ľIS̕fE7}o╡/[#eG(=);pjZr?>f)uoxf+y,HOZAӟ/K*e=y+j `< f&cﻯU|FISQ=|U0Ѵ( hN5''9j<W)ofNߨtÝ:uZ3~tP?9}j/T=tjujsCR*cre/VP'ފ#X;ؙYk.Ex%ş/|^:7|r*{g3Ihnlr/~_^'L3CM"-}#pLʏcN(rH*2<fd\8E fn.NtE_1eFpZj$2 Q*\ y<K}("c_4X1y x|5wm U]yUiS{q,SE]8sh<k(] R.fMJqQ=8~rZs,<l ڻa?0f_1\^w)\Ἧ,yMr(#lkH?x7B+/ K5;=p=)ߺ52'}fg63鑌F##cبoɻCRe09)3=~~pO^w}^&r=LT{T |-bҕ)M#X4GbIaNV_F֮]{׆60N( ~A]P3}p~^=E0/ f|dn ~CI5ʚ #yy]ˡ^Wqj%"2T>j:yE! ]C^!u~GйXsa}ւwqqɕ~$#). Y; @|6t8[ }-``m%÷Ic xzzYPnn o 6%Vmy[7n oܱ4|{xm% 6ǞDX<%wwWqF'ɱK_xxC^%w.Z~yr\ԩu ʉHo /yiޭCyrBaNSޙ@_=;wGbDlDzgL$s{zzJT KvW̼㼔,H Kkl_"]۽6U ' $ՅJ,&/ɗ*1IHPRٔӲ $_,]Y4?򥁥A~8_jjG&ӑ,V^$/5KJ{HVwE W, ,.CK+< X* lաɫk/% <搯:f:Ղflٲ󙚿H$~ˆ|=C+?ls[ y Yr$>7_bپ:Z뚚kjZZ[ۤNVdAZvW#=KmSKMSv]P"%:Zw3$abed{l$UGL21Lcc}Muumu- jkMԪFUMu͵RҭAtyRWCIM3Hݶ]uc}0i~c~:.n*blhhؾ}۶V-u9)Mmj[U%SmQSuTVTTlwӣT#!͂JW63oQn۶JFeKjOM1Y689.Zv5<1O{ϩ*+VTTf4{ј=03 hl(Ehb"OFbG"%.r`褖e4ϷԲ4d2:*5*K_jS<&;9D6H8'ۤWt$E<d\桾w񘌚2GJLUv%c#17g-#8#ѸDp,վ#J&q')5܋ }\Y h}K>nJ:~K؞{zaޮ.m; nYm體6ZQA<%3vpKҥ<My(H␈B\rN䝘eZe#InC+'bⒶd<nT7UE&&LtTL1՝ G>[Q̝nfqHtUVoiN1h(r[zaZjgJ`Ӕ3M3ԜK.| 2,?Ǫ'TO,툆^-kʴ/E 6AMMuI#<ޛ\[Vzbnݞқ<*QVD <S9{fZTMft L쾗 g}O_ؘ_,IdՅFdy ;iRԊm75eV*K''ʍRs8եO2- ]H$رaϞ=c:y>|9 c@N%̚!62%J0)8u#YڼX~V,Vċ/811Q[[k.Մ19Fdy ȉ t O=L 3y̴G_XwwwMMMkklZ}  [email protected]$1Y%ݫB  c@.$a$IFv񁁁uɫ,9{3"9_ 'Onv_򋋋+**zzz|wy\w*cGss"$eEѡ!IbF+((v`4440V]]m[/HH}aE1dJv!Č-%7d\%Vʧ~<UZZ&јSop#ܦo,tu `Ak$e1uu|gV-zO>{Q2Tm=;O}5k'~~$nd[~ y 6oO^ooر'z۶ď6,zk׮#@+_;aaz{q:W˿d(;/o?z1xc{ޙ(g|yx_~6f<3ra<σvP-Gy7}+dohZZ_8z;Vy[qª<p){} Kt9Ӂ՚cgE<GQ>^+cc/JL+jLLW˿eZd *U~oѐJ۩w'^x ;R!ʉW&^8:u[1vMOĥƹсC}%ϼdFuN::d>'чNYf{;}-ԝ up苧Nx3IRWe>d<fQC!Js;+<mPtyssZcCCOܻj}vO `+<ěw_EщH{T=a’Ĥ㿒ɟ␓ X:y'MOIPr엲t^jz:L>oV|Л'N79T6ܺCO KSN 2y GSroVu2Q]RI_}OF I5H^8Xy 9 W .=<.Đ!-i'Z }[y]2jXA+m(QRݼ֧_O5tV咭%J9z>f.ILRM1=%YI뀥IzD3̰Al5%s0QMx&󘙒;H7ԙ< y f~E?Ǎ Bz32StA>qV;g\_)˓܇BG1C}NM}& {eL hb]_jV~G=qjQm<nw?g|; oNSywyA{R=UU' ~Ly'1ϻ;\v3wƹcӳ]rXO(y 6\C,ߞ7_02]np , 1>hjl?_ g?GMM?o[68mTx~6 cQVV/dٱ@}K7'~ʳaxxp<`Cɢo~`coo(Ky bX__޽+^Ч72Hjpp^@1y A$Ktsy ;s)< ?c< ?c< ?cTWR1 < ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?Ry| @n1y A1y A1y A1Gf(((r\1(((<FQEQEQG-ve/m[IENDB`
PNG  IHDR hSsRGBgAMA a pHYsodIDATx^ `T'>oyۿ>Oyo_bA< XnHhmKŅbRj+l$$,dOf& "nIs~gnnn&2Ifs=w9wܹsG7mr[q>|&fӺu:fGևnѓ>UV0vPنfc{gD=̣Sk!GP/~ٶg/n}cTV0sqӿ7jJiM>vqh)3S1VJم5]SKEc$XAhQ735|zeHUfiN״)Xx {(X(fVשu)=22=q.IlP|E 0Z]aj^wDNh'"ŤomphdPg@Bc&48nQK65~D{b Y۬mZ뤞Fi:34dR#j+gLHmzpfYmzp*r,UY/sދtQ%'PUp2Cm6  n^F9pBӚ!Uh&$| >c}tFalV[nZ"pf$Uf D8AH*zj s#nImnZ"pj6eę>#%YB-AO&MYeEpcCE n3S&mPKڌ۬%N!+AZUmPK٨͢'0CS fL@-50;Yv 4 ҘیnW*F`[v~tԄ{]I >2td 4颿̹ﭭ1ڬ63I|Vy7ӃIb(5bMU0B#,55U%f6RZ*Ն\ MHciIJJR)WVV];e 1\a=ILm>ە*ׯW(((P#mqu6GvC5EHg}{,3-FڵKMcY<~ ^=jrZ/)-ՍLच/ZPISz܈vŽ=C;Xx*W"w˝t,Sϊ []R*u6[5U,j:t{I5O%%Y1O'ojMCD%5h^;U^$Q sUZ{{vY]]KM`*$ 0h5{`ޔԌ\Q#Zrct: j n6͊_ݽgݧS 55Z4.=v;Z.119HSf|q c4hS)I2"YQ__GfTCmj܄*]ȟL dfVJjT `nٲ9>~K|||BBBbb b(3N4eUk7nlܴ&E`YY9&2֬m+5hQQkٰy-7ǯݴf t닋@[:]Tu6SX h3$ ߂i9Uș(Alr|kcҖ6Q oʭ]F~a>צfj34,HE;hE-Ml,<;fVhfM~b@?T9CAؼ`֓ۂ3G4mоF<J .Q}90k\Ĉt:}֬v k āT%q9\NWJu{-rr9RN81ֿk-yScEr/ --M1|Yvy,P)`_]vnRRu$TWW:EbjhhEZغuJu\ظq7lؠRvVU*S8M`j7;#2u TRRFZc Vzܧ[4g<P^'QETUEeKJ.R}D͝;/6&n<+VF`EUTʸ?N1ֻۛzm3,S>>X{彯<w/SU9f<=7^kBBMm5eqצ*~)'םl1/UoENvdgoWE#/_pt7d|̸Lcg11ːnltcZru$T!cv_MFUjX};bڪr;W -|{ήc,|fi:_.^n?;ftkDAl3r׾8;p@=hS@%TFL~P3O?4,r %LVL'?wÏi3쫅(L6f*Q1>d_ڬ}3CD>5]Vl"}9mbhKӥ)_):' YJ/^qIm5jjjՈ/P=YBej/E[?qIn8<q/͝@4-۶mSpC6Gr:w;xu݅ VnvZSe$D!&S]xȮm&n>=n=!hj-AGmR4r%>Qv ־r` b"r"!^L˕W +BYZˍs; efFENTxjsrݗҥ&,'@iH#G|ˍ H@&mjnVԹj`E.%>6s"r9km<N K|tzWȖ(BNdÒ>h3qQsa+ qa#gjK둁CYwٲeJ̦MT*wmV^^~uWkT-/Yr!HkdqU_b)Mr!Hlnjǭ!Gk3CBVmƄfY =BnЃ,6 =BnЃ,6 =BnЃ,6 =BnЃ,<CnЃ,6 =DBK=fl+'DD=.}I[NbxxC&Lu2.'!mFoIӳ<o>_Ъz*"ˀhT:iOqsc72m_4$u8laqi2|aMj+E oIٲeofM4 jTMCiq6XVƀ4-3V5iV)z卍:tFO`k(sqI,Rmfs9#rYΓo6vn5z |"v@EoI'0nbE+qòFjjXF'^JH3a6Nd/Fe@!-CTb(gh3,6 =BnЃ,6UV%tGT Yry颡QsLu@p*6'~nooo@y$n^ڠP%f~B*6UO%dqYpcЩ~\۬fNJzjNT Y3lpůR6cGP"j.Cp*jw5f >}+n8YW vu P>jNnS9 jN>}DqÙp*hX-7bcJzj}<rsȘ{]W1ޢ|&P3tmۨ}Ҩ/L]_t^j|֙帬"Ζ=21IW-Ol=U{= ~t=5O&Haubg_wV3 ]5MeffTmmRRJܹSc AԾ !4j6ۺuJyi Y[U* O 96op~s;e|63Ɠ~Rg~ۦ ?hwU;N{Si3I,b@rz-9P`BӠ5F)fsَ\ϊ:G#.9^+s~Wm66ca6цyibEZDgی ~ˡߗy&l Z˖fYzvR+IO׵n]qZj]rkkw*D5kҍ3TN# 53'%cgjFNjF@ߙf"mօT66MZEWM]e(rr=x ]5LlI;`mmU[[W%fh .UU*`<(UXWWG0ϋܲ-> j0 Y c[&vqffֶmbwdefz˥k-[lO9ܲ MOObvǖ7j͚o M"enRkYkv㌻k$'ٸy6oYqMs5?ed`8Sc'XVd۫k6l֭ٸiM.'o;;</}-"9rXD}BQ)o\U.K0^bːʕW 5 ZVR<a5DɧZG%JKJssQm_ִ6[@'T_Qk䀹UugJ{\5^Ե6s:Ye!m2Cy"+#b mֲs\wѮ2 S11}E.BHվwDխkZ(pu-q?"UYYEq@=6 NLi+UB6V.!v4%j1%kfj)m1@lInvDW+W-T&v+))DFB(q9XkQ9Ou`7oܹO{11TF'/(TE1-5}Uu*W[x%)$dѣr.5^tI$.nN\Yѳ絬<IlNLm|eJIiUe*gm.z,j3,ïz'//;]uz+N/0UTUO{5zNmm:m[6[v=?[^q6&&u1g/;eKZ(6 U_~M5kyrq~܅g#11 olTgS[ܼl%ƼUW\Tڋ/~k/Ͻu"iߞ;oʼc+3\x'H7,u7dN_4fb'1;Դl+*jrթ ?~BeCáêhGK2%Xm#㥿kpߵ٦MTyyy*563yX[rTѰ_QLgG6^j}5I=Rh=<ۧ40lذĮoGZ>4Mjj1}f# 6tDpm&2!-luYktmfp\} L5e. -5uvWQfsZQ+nk6kYaCjZ)D ]&:؀{4 oCTxm&>|li,, ̀LF!>]{J|Q%4b+6+])[4W M LG ֶ|nRLex1/>>kE2ݠBܟp"jV¿k/;x񝭿+@9Xw޷6IM7m-l6G}q =d)5::hȅч3V$䇌"%GWTA1,\Bo Ζ.6UUU]-[Tn<뗷^ʅ pa/+@Xp|I4uq_]]>qj*62fL?,hfLmzpfYmzpfYmzpfYmzpfYmzpfYmzpZfԘa7-r#׏y(j"O;E !1micF~m2ͅD5C4K/KBkCv 0SM;2<_;??f@$U"%ΟҞAQo{Ӡu)[E-v5MC77mn.~ݢkNqVY:j)ߏ ߠQf-1D3 =̔O1͟8;G{ ];a'^):=jO=Yq8bܴSac1& L)ȏbD5_XRk ]˰,VU-&!d>Sgfwf>~nX]}tߝ(Le0mq6ƕ`["̬S,+Hjf[wAyV \ V{ J*P<WhK(:tF̜, ьgD9$乸/YN9SJ.<`^~e,ju"\R¬ڹ ,I _;o4xx衇Qr+HTGQ|ټyaԴ+Q̙;v45QhEmKl{!0cuYmŒbT;0AÌa3 :f t8&p1aC3&l#}áQ<dvLB0c x0cu '4(WkÌ [!%quz(pxD}zWL/:fMVc FO,qTa tx0cuf35(_3&l#J\tƠ9]:\CbvzP:8̘Aaf5aƄ-tSA "p]GJJ- /fLBG裳.Ӊ050a}Z/fLآ`7m 5aƄ-tz*\؂w}`IC*LۍK90x_LOp OkT.#>t1j&\#OPA50ìRu1uʧPA5L=ImtKU#_#}¥=]^S S&ԅ3r1Kx DKvO?y0 Tf&Q> f%%%j˶mTΝ;UKEEJ%33ԨqO#> Lg_ʧPAafSSSՈ/TmLg*UPfq&h= 4=EoifnȧPAap ݵkJuU/YYY*unZ7Z*wEZ:Tr@?.,mC ace=;0^QQ6$W%UbdCfӷV ޷JWܻwowD7|npHe>t! fN~5MRZCǍ+3I7t ɻc=@Ҟ㵭rHWϽwC\I+7U弔zkQmޒBSyW*'ʊ8qTc럪0i af:MRZJb_]gZQ+7QTTV P[TA&?Z˃rI%<d*[.q8Nyi)@=z"Hп34jБE9EG"]10ja.]Fu~1v5{yKF?<? R͏R.8"xjk?.gpe85C =`&&&Sn#U9T^"!xݬE}7 v\0*k $20TTBNH gS%% V@0Į'C)a:4oo߾jLԃFi=AM`b~~>Κ@FnEq5b{חY?–x?ӈ[b8 Yj\K(]TBD B1C b(Ձ 0"-fAJRe<{;S$*~%$'FhCe9tu,%5{ys͛;gbc>=o옘ٱ'zVttt ƢgώT$bf!'nNl,R(3gnM`}m?ٚ%ƢhHhHhYz~*,> x{ @{HfTݣFXn,Z,-bE"üACc#pA1`kEKa czҢ?9i2XbPY &|8bU?׿:D\[4;_q(p_\(9ke8r䨪}Ygڬ#g;'ķֻ^c݇H.ue 0a*iTUdwXnW[%L,>DŹJ:XW:B?}J2< Nqr9&;yæ7dj=uTf{ôTN"Nf5)Stcq<C{1qqCh@pcff 6ӂbAZ$j'0oC/@f&ek5Ol 9<F=. p! QI!#ML!936oN\ȍԼXL1L4cDѹ͙;m9U%5pTy05HORj~[  B(ed |od*Ip8:jWqF%xX[gfd\,d; Vy_5UO W`wD0++kݸ O*!D+ORQ xttqwKUB:g..cj:Kg5EjDՁl*;jу*((#ى , -'N> -Dh@aa!uhUUUj-Cvqd0WBĎ:ff" нuXS,S1kܠ$--M"*B(hVC|ڬX{ǫpruHߟ_WhU@K? 6dff^ٴETN4͆\;jΖn}|]XC\SAdff΀٣?,^\\LAUhbjH- F~y E;R Y^M6#;W_h(mjyqv)_u2;QxUN926ZBQmG쪘9p,Fb8iWg&ļ'c UpٲŇ#!Ӟ↡sG<HPǀQ[avGc ì?k~5Fy_n8yǶ?(I_66ʙ|Yvvx/7'=6>1l>>xTQ /_9z<ͫ2@ظ̙b|v"uЀ %|Ƥ.Ќr9VV۽WXZ,HO~KԶn,ehZ RӉl=gyvӄeVNդ719?孃v S 11Ξ5Ϟ=]HϞF]wͨj ϾYR *8̺IrrJ1LTPqG^^^AA }vЙ fo#_vM6yyE4ϖ@zNi˅:&QA5ÌniJ@u?Pw;HOnuSDŀ.њ.jU?Fg,5UL(#^a BƩ^}|(³zx/ꨠ⾙Zvv T!ė) ODzXӉ2~2k. !3v`r233$i =4#V  TPw(EPPBx4f1&O;jEyPO"FĜ5YYY޸2*abk֬'u0q.,8JL/*,⩈!OoyJ6hH`T{TjUU(펜,Y?2Ԣ~uMޮ4b`"_9"[<o$0Bס܄Vܹs׮]2} 3mUE=ӿ\:=99ABJhoZ 61e{u<Fi|=8oq ^/SB% uc Hh:rGGb,#֭:ӺqC5AX#˂Kƙ?9+уj*۝bqO~|AӾ>?ꪸn6d`DN" \J,-3Aꯎ"ɦM" $USTP-Ӓqėbpx_B.qAE~C ={!yeẖ֝.Q^j޶0! ~s"4NgPgTP16lEQVVRLBY{DE W^'-j"SwPu1 *Pa6<Yx#FX!cA{rE>_xȩ\cip|!f$^P4(2b.O;?:wt W|X2?8/ _̟lʜwbcR(G"*8n?S~FAkV^_wY^Tf <TP 3^ 8j6i3 :f t8&0mc&p1L0ca0AÌa3 :f t8&p1L0ca0AÌa3 :f tDc&p1L0c쯫vX IY*Ɂ/}c 99ǔ<ErmS|í?-}9RHO;mX1i׌yqu(._|K];66IcGMSf ŒQc&mygߺx#'G:|7y&\]֡ =j}ht!XH =3k{ѣ[#>*<Bq`(E)̂jcoyWo}7;jc{IO>?QsF1޽XMTbe,!|0kc>1 hx*]{=S0Ca񌣲pc4 CaD[ZY-}٨ t|^43_oyC;SGchw~Dڢ1ۦ^">{g ?96[6G#GtO|뇓+œշ2X&x#D 鍛E)N+4yH !}A-Kӆ9"s 4|7M,VHIkOdZcҲ1MeBD}cHʰ,VHXq3S;ך>^ܔr;21gjߝzˬ1 @(Y^$#W͟q;di=X0~_Xe7kn]F3?Ӱ"Ƥ(Ɛx(6$b̔.5ƵaX-׊N>ҴPփ Wi]:b!W}W؈CgNF{. DEXUoWRY5}$\qBb*?e)߿2s dGm{*~aQF~1 m1'cWcVnX2d|I* !c<Q[q0r5G!$CCbsH(|+(Y"_@qFD;Bw  Ra,LmM5`-ZblJk^mdIcDcuYb  &#bL-ҋA6qX1BUO^@TOnV{`o9jg9$SjDQ[n}lYC榦M DIQ&hcڨ%O2B1Œcucsr0xe `B ._+"Z)u/X,VGR1 4c \8&p1Lpc10ca 1 .c \8&p1Lpc“U 9}%^8Ƙ|ߡ VCGRk]74jtn7TgQkc O1D҈411+{/F ^8Ƙw>62f SVYcz^8ƘD}Z/cLx@1&<Q{Ѵf6@Z/cLxB1l8Ƙ Z3ں>I1\CwAPlh}n騅4Wp1D }2)~}CE 1fB1@t!xcP ITkc O(^8ƘDAF)~H36cb? rc [>8Ƙ ŀ s=nIz,1&?={މJLp1`1 \( $d51Ƅ'}Z/cLx c21j p1 @Q 1 (>!Q4=2UV5"V)c*ja^8Ƙ@ϙ04ꞡQN%<[@L۝>JȸrOϹB.mA<&aȾБ14 c@P Ng9FycF- 3xcuITkc O(Mlk8Ƙ5A}0>IiQTk0(?oDŖ1fA1N%̧B{~Bk]lqk$=}P<S\,_>]|n*p1@1@?MdFp#>N@:rb Xi3(-/k&,hMVcLxVc sdе"nj @QceM/Ov)T2 ~JB6<S<*v5*?#ȏ{"䁘9}qS1jBGO?OSc'"B,nIXzzP 1KC!?%[~V|%=L>#1D t_"$TlykIZS&kIMH}nkz H$AϪ(ҋ5m (SFPcc=!~@APLZc[{?gϞjU5Ϡhhv5")))QٶmJ`֭eeejSdLcYYYUUUj@g-RSZZ8ӋP cP#\S.hONN޿gXauӍDq~ɴWhmcV clDO\l66*333//Fe0VF%*ԝwq}*+Řݲ.ZH輛V Lb fR#CWkSSSHP:0;;;''N+GiUC+*@1>bпVĉ_. 6j ^&`t.D]ꨳ;l.^6r8j0c Lr +/̴$qT,STYYŀnB,8VÃS҇M25Fhga٨|?ek2joFblStJ}Ȁ)LR xNK`qrFawKx$#5mPAUU0 c21G á| q@oh9W Y1&pn$*=-#OUd@-qyhT!TUSZa*qB%9UֲnК/U1y A⪶0bS~cs?$)9:1ohyq$!yr':kO~b]ų[G̘x~q+t?"c"1 1cYKeO <+>ucUS^)853N@W,\j~GvWpK!ለv_ oqS#Y3y^uuIoCUd\T!:?^e 5UCV[ueEEfFFee%͂x#sӡ! o-8j)|=6tO'ѣghAPYWlY=H7{6&n6Rdd槧wQ8Pl\Q|ZmV׺u}zWdeښ;~֣Un'bJ+++P)QXA1U!p]M9X;}u T*Dرm?[+,os"<m60t50}EĬV+Nyyy:$gbB+(Zλ.8bi@>˅8/hcB( $P2Qg?9O/52r>{BoB1D jD=䢢fuvÇSRR 279233hijl#yRbǧ=Eg*?WIERZZZUU\~ t4MD2B E h:1# n=X__YYKy rPiG3m! @1n i*4XvNNG\;P*sz$ F%.8cuɽ2DdRQxKopjZt0ՅDyGUŵT{pwH+q;+3 BÌ eJTZ'%mھ3۷+bGnߒe <'$o޴)=} 2l۶UW"j5-XqiCBu7I\:k6\m{nU@Ee嚵&ZmʁE%B]Vc=cf7oMYnúk7m^qmNToc̈ 7T7o߾QC*s1ڮxنDVBBjӚMWqV֙ϩAˢJc _~xQLkjn$/cϛ=(Erϋ=oϙ3̜93fvЬٳgP(z91;3g̈ ";6.EhW\Y1㫖%Fӄ,lmA~>ɲuYjU9O6eZQ\٬t+,5얈ٚ6 %VӢ53{s{4|@M'0DǁѯF  "ڎqZVk':{ c2R1ࠠK@Ud`Ѣccc7}Xt곒#Q?}0f<=)b| o!ςTxw[|ℂGj^q>\eĀ!ӧ4 ]Oe4_ZQTiZkZeHL-mZM,Uե4Týw@tH+`5o}qs3byehV O Qs WUdb .e_9 jVZҥOhzW?7 NG#gC5P'cOAhP7AS:cq-Vj<M1q1Dy bL{-8]Ę.uuFkу K~G2KDث:Z6L{jHGk] 3ueĘJEUd@2ǘIrPGblũcQ?1<1Z]ZGͦ=,/ WκB"f *-/t[ j^FLR{$6V 7nYZ}23+**(`j/(ƚ<M0)zDO ][hjjlj4ƛfxSӥKbzΎQ͉CJ΅Ɗ:oΜyzgظ9m^uл߈86bEGQ4U U##Y|*uWS};MԞ jR6-Ũm~EaWóuR/4oʵl:q;OԻ J5m=Cr%-f\!O .lu:9򻹈1rJǘfEXz͐0Ik.-s!+I莭JL&da5vM<\p[W]sޡczUwzjj8\Es`h}"' SR%Hc+VYsՋFQ{#i`Z8ƺ;UBqXyQ#xxID2НU3D8j:S>I9r$99 l&O8C,NHJ+ebBkvޝ qC4Hii $;1֣g@ɴfEap#Scwl1!4$.VD<Zs*M`%`\i&}cAD6ZVpP"M ZYlqL`OETVT` j}%}^D:r1:ǙDTWlܸZnqj U|SUg;,;HJLLXLѨG | aUU7hWQ1@Z:e:WX)c4j2['uy0!cZ8>,;p٬z \x#UKt߄Yp3Ӂ@ˉV$LžC {jmڴPa~6|] 硒RD^!ETVVKB ȕuVT`jI$!*oq87ՠ;P5s,1{snysCbVAUgS/rSؖc޴J3VK<Ӫh˗/_j-RV.]ψtii9s9g`(w=a\\S+Dzb>5ߢˍ)))NuQ=TE<ꆍ[ԾVϏAc!&bH(ˀ)Kc aU*|a׮]ƐьZ N'b11$c1.qٶnuUg}VmOPhfĬq@$98s &}yr?bs~oG}˗Ŝbc{P)!|c)dz/V^V~54~z"?&&\5j@"&0POڍ'?ʦʿLJp)Jj^: ~@4_\[q=3-!q+-qYəב4/9Dط'rBﹿ(9s^r 9G$UZx_55L&b,ߎEb9o;&gzϜQuI>4=4oχRn-7`e"F%s|TUv w'v76/~턻vHprT-c]kDѥp꣏>Q( 􂈱?yU](xOyz-=+ 14`uJ$f<rucB-8{l$d"R)A1jLQbX:/XO=(Oz1rEHJ1L0"b҈7{j BkaLg'r]˫?1y t 1vłěe[؝g-o݉2(އ'5c#jblo!`]l].`CD 1Qkދ%$*T-!cAe'y ڼɧT9jU5_w((4 C-K$ u =5 ?m>BF/cݢS2fǘ0c'WO1(,,ܵk @~, puMTdeeugv&<_{W]?} Xd/%^SJOo1}Xj+UԴ=2] e8T]ړ0]eRBW<a@jntavO{Nn|U$VxsoF&k&Rc8=k/?$^U-E{l+!4"m1EkӨB˃bTc,lܵ@Ę!Gb@1/Kb̔DpcY;` 5oJvAژXp~2aX 6mӦM8x'E#GҐkmk5ٳ{`0pbLZ]WPl/檪ÇShU^t $"r!J݋] WPC}}=/d:$cL$2D B!c4 * kK"|H ?'^ gh^[~JRjD8ʄ!0P$Q=zʕ+ۧ2DqQYxѓө 1a Q%\֯B26;N!Z1f?`+=`wmr(CCú`ol%F8w68`Gvg$ ӌUJסÇoݚp$,СC2E=)2j+(tJ@%7 2}BXS' !5I-1gݷ\W Ta\E(F3ٟԾ);SvlϢW7"iiiY4 $_'(QDqZx$vJ$@m9f ǚi_ӴZ/=*z'ZdnYI/O_rXx/`ek֬X,WZ6$"kr ~JMbߐhW 1uE6HW& G˕ϐ` Hz(ME0I6t=L1r?Y"<.ro5(;=U?Q P?! k׉= .\~?mG?|ȡQ|Q{u0mb#O8*I Q/.b̸bS9c\_O<}H8K.6ǥ*g@Sc2*!B_B!>| G[CQ&~D1@c"'&SjyL?Wmٝ?y*~'1ĵb…q]b2Jm,OjڬAH[b5/"*S3O*A ѓj!X,zP*R$F._Ř<h!Q46II] NίpӪ׻l.(w7d2xqj:GY[笮:}*#ޟ? n\R")?p]8=Ee\urF mdz1.] )nӋQz7 ?3U29zի>tHfPU݂c1r"AD~҇c2b_] {cv j2ˀL :k9ry \&pu?tu_fZv~{^c'S}ZWwʕ>~2 *c@{h&ڿ/x%7h""R%: aBοcGH\21pu*}br6";'#e",M GDlV򓲗1#MzAfT@LҡHe50%&%.5H>xntzYSC@1aRc29zýOPk`AM8zx<Stw./x˻#UӋp1Lpc10w18&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca1<iQ㦲XcL(_\qw(}aQޚM@Fb8vM6j6G#Qvnr-Ӈ0rܔȱBN&S3uiM7m2!fytVϊ/߿~ !}PՎ#F]m˷r2Նz4|`,i-=o2;2>6ŔiR+& iҖSz3⶟P難zlmkK_~d-?nݱ?M=baL9ѓ7o&׍vݸ~w#cH?zV\qW2QNgF Cc?w<L@/fQ ݊jbtUPSck@z<zc9"*!7Z{\@NIbHcV׉!CJޭe >t[\YKn_47=E57_^o?|RsQwE,4bφѢY, jds[R fun%SI3f ;i+26@Vb+'z!1yQ-*-cM8ٰۦFOK};aOaM72麻}i'#n|47ylpG@D©ac^777}n2?tcً&a),u[M!06nOaa=|ݸ"ljpᑓ>8%OuDd>5qȟ2ơ:=rToCn-SsRX,Tuda?cLSn?mO;u8ܴN1~,rNQXfDqZQA4|t51ƥX,+N& dX:QƨiX,+(N|aqɨ˘ @>3Y,8YuWc􍚩}הcM?̺b))Sh^S&4ͤ̍ ~qY,2Fi̛А iL]7Q7 C`\P^R&T9͵fTtT e).Fyg}^`T$S>LHƍgX,Vi q͔og՞̫˸,  X,NRNUSS=+S,<|;Yu;6=U[wf9vO' S}+olӽ/ס3+3ie\xɼy8T(z¸i=zPz,ldp<:)t\,/޳rcLPUYANE'j綗ZLCX"gE rG ꙝ6Ll޸%tЧ5혹ItN6Ci.~ u2]p28{s5dm WᲿf NV]VWClhԄoE>'[yo!'N濪uIO/ljK1֏Xb\"'٘'io!M3вQ%Fi311SkjXF PgђS"@'MTc)^?Ym/ TbX?'#+(i9UVO>vzPp/|J^|wI Pz,lu'czJs2jdꊝaaBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2aPDm|;1 Ä>Pd 0:{q.Zau#q`-)}*om'0\@t* FMoooXkCov2aPBڽu¥)L{dH` d'Qd 0:0Ʒ;0L(N N0 JS{sDREa uj}`TGd 0:{9S<>SO5ޚ9Tk}1̅'>}tJw&1 ԩ5Q'䈇1$';0hLuLV⟑1'AGL3 AafN(\Jd 0uj}a(>Pd 0:>ru(Ua&PFa&<Qv!ѯ8S\>8c$'^afNLTOÊ >>]'ʧ|$)#f?]LzzD= ;0EڽoUG`BdZ4!aR贽 4p,a{^'3~ SĬvafN;0Ejہa&Pv`'c %ԩ=9pBmR;EaDCv2a:{џ-tO09@H<O?*T.}dh=o-8 dȘ9EJd W.z䜄7b0j0_!a(Ew2zFGGs*adxu_K'_H0D1*AK&Cd~zNuj>y'v2a:w;>Ԉ v2a:>01 Ä>Pd 0:>rd 0:>d 0uj7p*aJ/O|a;0E ߨ[~E<./~EO3Kh4=Tb^XxpT=9UKu"GU5z^_mv2a:wΙ afNCq2 0 uj`Kya'c %ԩ=1u|Je'c 'ԩ=Qi~a'cǚ3ej}^^p<sZa5{#]UYW4NOMF֏aΣN^*`*K!;uK!py Q {`9 rZ&Z>g?B?B?r-E?ׂF!Z*fr2~ND+'xξAۛ<ՋIMf}ͳXk%=U |,N0Aڻiއ '{OS!!ϻB_{0z@ ͋+˜$rW3 '(}[$P?SΫN0ACv2& UB;SCml+pUv& L9&XݔcU;L9hjUkf߿۶m[n˫P:>ru(Ul@QVVKرcAeOeeejj鈝;w_vQ8B999*awlZ,́[ഞRYKLLd:YYYj@뙜YPP0a:{q. M3==y G<yH}ϡx ;Y著Ss~~>[B UUUjKtɌ:jݻ޽ZM`l@Zoc5RXzz7}呠gQX<X/_r!|ަO*q2΋5W/a'7-5mEEEjtt"[n ~ҁ"*?Qˁa-dlHPPl@<.XڴVX݅KAޅ2>gO`+r<a\v爯G_#QXm)--E`ǎ=(..^~=:=:8l߾}ڶπ hvhh'`WsƤqacPD@8}Fav2Sf>ʂuQξCn۴q{bΔ={;e?>ՔC٩E(.IO'KLܵiӎk={ HMMݶm{Ķ(ַ41-gkΔmeNۖ+%5/9%/5 SRwef//9lְ4ds; v23+6̴tM5lڴ [k^_',5=y56SVl^jixK*!qZvMAAAff& `:ggam44q-~IE4j˚&eib^;NLvݘN|wC59NS#֬5zz[~s6m`Zi}JJKM+lmޒRЅm/Y|K\5(tc-v<Ç|{>tGx ;m?{lG&/6{f; u\q$SgE8הy_fq'wRӘm 4}"^LFg/Z1TznКξ;&ʿqf.:Jn-s;ԫOy!/R;Z>X NYHg!ϰDH# B$DxNl 3EWL5,"lL'==߸KlJ9yLl{'HLg!Y".GXjNQꔉ$"}QLA62_o}`> N1^)>y9Oq,l0;ri,ڥ<(+g`amޝ#g{ee01t'r8#m3$ː 踽/\:á/:zK(&.(G--\4ȔOGO%pU9nYFhv)-Oj%d-TTT$%%/2k%mTuuN};aC4˚ PW;<WL͘YmZ/bOx6ʄa`2x /!_<Yr9\´ZNSx]!''^fmҪT1D>IPBe1:F'sL'0-YD9Y=2kduO9 a%ůѝLHɬ61NfS_?i[T(M|[{NnGC|^qj0 [N$5 W]S#Ät. CXpl߾===؁bTĶM#YV]kW5$ F}-]YmeKy g'u`' hho>N!0&r^|X^@Cߣs[L%(rVuuΝ;);v(//ԥ2yie: @`2-:>|xQm$ܜ ݷ.d=Kee%wj$`S#!BdaH 92[MhQ%3)!H, b#݊D>rJ𶌌{W) Z[5dtɂ'ñ㏎` Plr]aRCCr/!\iԀ+M\ff&NgD B@TR_sr8`EC]v_1rf=Z8&0ra\1NzRRRГF 9r'ֳ֓V:#)!;|²j%=dn?% yp|, -[0+;29U`I:TJ.S 6b )۫0MBU8"!g S<'(Nzݺu6mU%nJoSnc}js|Co 6PqsՊo??!Qvk87Jtc!4*zy!d<TJT^n}*ijYbW%-ũ2:0KzɨQ)~TKP#&a 0unڴ lX"a-KBsIp*LӃ ",\bz>T D[_a^Zrָfb5*Ϊ 7LeBr  QYݦGlLG_C5oJa$U[H6]ᤏ/|]} WB83+%a8ꗈm -..޾}{ZZځt^2ER26 ;!chNp2{ӎP{P֪*5ԩ=SҶ=dY۳0iqA=<(IȁD1147z.7z._܈?|$J#e-QqWT aqf=g͚/9sFtYg͞5k v11ѱqOLllLl(iq(i1c␏,bvY918~B&@Ypݹڣe E{RאB9OĠ'#LOC:{M\́AZ݃ڴ9oZ66 .yĥeuT}ߵZ"C!H<&8`Z -^3 $B^zLpctϞ=))) /r8Š熃\3^3$fYEɝ]'Č됏 __qin/@#whN<̄셶'SӚ/7?ϛE x2ao6~ÄI/`N {LFwQVhF|w^p1ua8dupd/7'nv,>01s͋33:zΜsfy".n.4Ec>09F(M›Psbg|y11ѿ|f9ODϞ'll9@Yqs3N%$媭ݛE$h‰@3xJ%yߙ\o4aQ 7{DAΑEө@ 3o8"6(:B,V#LQ Fq@'{m޸yݚ7OIN֞}AFifg~A)_^GB3d3b!~Å"E +33:d`m m;N&MFK_Ycm}:.ݽ5y8hͿPرA+#"FaƯ YT- wß̘;;;7;/5<7zԃQ#G:[-ZfZƜSų><șPr>YG˦O񋋯H`ꢸ/\n}LtjX!NG۾Tֻ\Ǹ?<F2jm,24 z{^8?R>9H|~Rd9rꚓ~ID?l:vsfH;y |ϛE, FQ /ߤgq 3ezN&>ӲˑBNFV8SmXr"DO e%b K;\/1;M@1x'ulJ`W,=-&]9sq8aeut,u!lL~N!GrRPPCm^8MjBK['0*1/KKGɮUXKvW,G߂2(D8qv]p27°g0`Wd%r,\t( 벯c#'ala`(3PuQk㗶Nf9ߖ62TD'~j}S!N檝l1N5MaQw{=. {cސ&'k<#ƪz2Ore'LY㨩s&Hx έ0:Gh#V 1eLhENV_b WHU>P'ًr2`XLuؙ1d"`)ߤum =Vkm+OeGGhim{f=WSxI8g~eytY$]B'zlƦ/=͗'fM6 x<PEe4Ț($2m9:648z뭹s̞'?c!bgΊ5#vsΎ-> C-ngbfŊDGϝ1;nVظ1s0ѳ1qyscf̎*0wL8qϊQ rKWt mHFNI+qm3#Ѥֺ?Vonx۴ʬ\h?=ɓųbjӚ[j38m/)# ,hOj)?щ!{!N跉~";Qt"npҥr{_3kuXڦN]?k+Ǟ'oSU`}% kMe[cTUUѻv?$k#M"@}kEj%=dhVRZ %e d,\. 2eR z'䗋gOSYYyyER2H>TXy* J~YjЭи0v9UUuuⲲr9,;PVzvAEIQqQ~! z(:2%%III)) Fa S&Pu CוX˪+eJ[Rť ,/æ^qQ*ʷ&o1:=+AȥBzUU^e(.AW+-W@Iy ȗ]Uc OB'%%@{ Np 8p +++55lN&.TRg:)GrE/ ˈcLyi HVĚۋko,]"Oa , e@܍kŗY1"bh qAN8Ů]HWUAqHp_8$Q<= ;tjĬ58蕌CfPX8Ԁ0AZb ]h913v b:Df;NV̍+\'@><v慥aOgyQu"Q1KNNw}\#z?tboeP GzzZ*6V<[mQ r2?V#^̤tm*!MyDBt!,EEEg |0O%a-G,k*3T;I!f(9VAA]Sdi8pE x( 1TH@ anG$}dtڠyTPwZ*t%ѐF~Τ44Ny9DN 0/l6$.`_vTE.~4a_aOsd! b#o 9VkZZR8Yqqu EmIݻwcU+**ЩO=^:;wBq|1IH|E~޻woii)v&OM F?ӑؓjqlavQ:vM@[`u󾮮~ㆍk֬?4;:NDm}Q9JBtusv$<Z31rխ]nÆK.o!S=fyl8AbDءCmسgoffVjjb1|zBV."BnLc=dZIL6X7 ňvee+WZۓG  v%ے MLL& DdEF x)_1P6߸a&h˖7o9MjӦ}iaڼ2 =zM:2sشf妵҆jع+o^ 6oIW`BiY!=}[ZZJo- ct[zfzz^ؿRSSSRq^RRa?4]Q^rxun߸aӦ[6n,rCdTPXX=뱒X3SӥZmI-JaAٹkwZz&)5-CT%3`z8qٳq񔟜j:{AIɴtdE^)pR/R/fXA}LlޒV/oex_ꔾT-~Y~#}ANnrrvSrss23; f͚3g.HF9sm8DhތݒRgmݚZ3l(ߢ'ګ455={kKUj?Xw>sF_~P J`'= U;HN}%fϻ`n~Wg"s)uP.jĖ-?&pՋ3LuSOfzG$XOILWcbRcҹWeccʼnH1rr4c윞O9&=';;j*.zo@ + |";$*c Jؿ~|BVa0F.:k=&&6=Ecjq$b0AitBEcbK|@Qıwc<j2w[,{߯ƼUFeƼ JX}(fA[ wŋ-tf,sϝ2/KM'n>cwJڠA6ְWT>>Zp]X.vzr/6edr4z!ȧ zyçOŬqGksE&ͱ&O˦ĸ1 z3R (i͈LԶOkQʬŊ.8U~VxZ 5"2Q2>Iʳ;#&R K['Qu[xk g|P7X ꚓT=Wm^:03,xU9򊳰(I=8%c)Yi1DkbF:Hz{_ZcMD&CO-8[AQ$8>QCћV꾈QjX-N(q֣%]p,+9ᙳv\$d11`jH/#'[V'; 8  PL4悱ds0ljrÁXVO( j[H9VOA M;D9bwR=H@rc(`4.8;W,{' |Wh|ߞ{l=>0 n83QFӐ&_ČD :j*D?*)蚓QNJ_nM8 23{Mirvh?Pȱg3ԃDs\ zu ra˖~f=~?˹F2-dLOI_!hRל邓ud*myTdL邓u rjmbtGv^eͪ)W_]V#6o C7t|6} L>ٻZn߫һZVDGU#vz'jz^ZؾWO?-tȾ_~i^?ߟ_/9;~iH\\χ>ɘ>`׮];vP# 0݃{vޝ 0>a'cOOOW# 0Nw轫μka;]KH)..NNNֿd 0v2THHC>x1<W+ʪV@7gr )dteKjn\}5k0OW{SwsAjWwF 3"Z$ht~1ZS=ʻ<HP=gSg~O%Fڿ]ɾꍢ=Nz\.EۧxliҮ<.ߡu%?Ek:G^K/ZSCS(i7zP?jw-ҚjSoa'N7L'Z:?,&|'C#Daj%<ۧ/,:+FCMbFdH(pr4|o$'&  iɐ5`d `'c\$z['j%r@i>WJ^r )dLdffvK}BEE֭[EE1a> o}}]8&:+, VRRRyyE>12.f! )$5R8#<ŋWi]UUQݽP;_!E%*+>>C!ȧ QmL'* Dևa>,9ZU61y 5O T/ax^:@݄ f'CR]BiT;kjj*:0 ;Y8Pc%ցR8L Á3XVFSRR 鞺rFB2,%t“jV; 9X3 .݆S?9u˥c(**T scBeddڵ+'' RX+ZyY &dCxΨ*`!B޾SDV uir:#I3Q 8qST&;JeJEq1]8o]2cK4 3m{f28N=-= ˅YGUudlWD0LN8ش?qϏ-qo1 F^0z,/`FMݨ;ŠKʅ :0a::jЙ::6n[?/O;P-cpHCX t˭Ғ7l޴iG9NN ?OG?G;B]wM㮻 E提$GTP ݉9o Qnaq2;<bF ܍yׄ; 0ꞻk w^z]$ ꅿx ?wfK?<0a;Y8+YfFLEk,L!F)'ZD[㚽`v1=8tiC4,fGIr)b5mfvZ56.GA faM a,iCPY2#bTJkn]M=mPQyE׭ ,3-]ֆ U- 3a' Vl6#=e]'MAlNN0J3SsA]Nɭ7Q]MX?D,&d/~'m|)5vIMe;dMԞDO+L#~=DDsڌkMƦj'SIr2ˏ~ oqR x6*8Le.|7闢 7Bmb2r0rDyNfy5% %)-jb2&O:OlB̅i떈#!ZYw>br/`' \2b ImpWMVq-DOMw#;Hsgt$E-uk˴:ɽb'c,:Mz Z9îaEF>w}{>}kC<YZQrԺj.0U!!?&O!*NJGn~u=w5ϿVaĈFL\/q v:V9rddaQÆERaC(22rH|Q4e({f~u()*uUGE0vmc#D1PX%UR&ZHޢnoP%%-y|oFtJ_pʍT 3a' {K8fC54&;1Dy6xV9.{M悽8"_~K^c[5V['yFOcx>TcI5Ho`Iy| Dk&"`J0:}UY] =}_ @uH(*mVK<NliV5 g*VZP]--x߿_ivN⴪7nL~2< _Vj ` @I#*Oa'c@`' M[BTr/qV&@HVTT7w v2 vn֚3KHH@;; 6ω^aӦMׯR ô;&TR ô;-|)Daa@?$=wؾf-jm&|a'cETpuvHuVfҧ\_;cv2[lJT[YD\PoJ8"KNEXxDq|cZDdhDy$}I0fDydT4KTR *pX"}X. TR+iX%2P#KG3TL=]uL]hcs}V)"pсPL Nc<|ds/}hG?X^e/_vtHS ݕPrؘg6̏b9IF>rA& ;3`'cEdp 2^ }ޯUnN ɘnʟ@\m_~生 jm&|a'caBv2a&a'caB9_|90 'Mʥs2a1 0 ;0 ڰ1 0 ;0 ڰ1 0r&1 0;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ('v2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caB'cX,+tN&y`/߿~K?6&dj_\q^ثknnvG~e6nJ丩7z 7mXd|ĸi׎r1)rCrbR㑖 M.45J1vmFrim#=g_\Ma/6 445 D4ec&Ɔ{dmo ?äagS"NfԘ)cdQE>l&0nr؇FzNϊ/߿~ Gt&'*7/`oecںÔ6yЋ9vx) S)ǧnӿ5a,:.YW^?'gnp'_;#E"LqOq۔aGny rܤ'=?|eHYq_aS8 Nf0lcq|JcI]x SfgusʔVe66|c&wWTvsw{57bo{dm6瑣'0vꍣG|ؘQ~ݸ;emomƶӳ/߿¦6FC33 5 ?NA~o3i$4Ȩ>&դ-o]a.Qrh8iKMՇaNc-i0 R~ie?gQxnoLO]76?ûYuƵNo^t<-Lw7_=Io0rHYq_à^$&MK1د.%ILE$) r&r)[W3E}e`9duTVFJ4;R]uicQ2p օ!Ik" ȪO=frSc mr1wo<w] /ް8 Ky͟Z\pPo>!]Y[oϱ?1@,ҕzs)%I<QӃ9 lIrl%„|y-NxGb*ocSFrͥpGΝ5;ou'K\pWzwM5n.g]D-;׎zUǾۃW>4/F>P9bzGl?~JUEץNƦ<M̎u 2$fTCI1/h&{c&u5ۦG:{lϣn6'1=qS'VnmSț^~C7/>;\s[n4l#f,bzAl:ImH^N[[c;2߭2<s#o}q\sǔ1uc|o7cΘI#?4|׏y˔S|6KaX,VԁAϜMa"M1~ʍ ^?nxCLz0rp/F 9qBs(J|'Z|L< L7/bXAS6.<eQLۦG¥+9Ta ظi2+qgRؘ3`8赣sb.bM},1^ES㧍@ N6v:lO;^ GM>%zl-`X,VP5{cFDѵB|A["A٘)·s& #99cX,Voh@ۘpsH갌*ZX,+6|aqI*^>b 1d2Ʃ$,  e\bݎᲔ4jT,aw g0F \gY8[4n<bB]-66Sɴ{4Mx1& f2}t QtXu:c.j)"ݰXԀ2&S5< ͸XYnGǿ+v 8 ƳX,+J_}0  lCx%"3G%(ilzydcrTiW QÎǿᲛK>o[eLhY,2zbcT%fe`4Tr;k!$ i8z](@9*olLS) 1 C %Lrb|?A&=uʊLμbXP!ۆ]в=@LJƍgX,VwobX/ecV)bBNlcS {VY,+x_6:tƔkz卍`SKDa X'%<X,Voʧ)9fٚkOArZ躪kѫ-RSlcؓL]%f/Ab_s޼y4`cX,ac8fb8ԕY_l6<aXldPy i^=֭C\޶Of۫(\lc,7rFO펍Q6Ithƚ!=D'oUG $IFS{mI ^bO|<x 1Q4mJu cmb|IK<Γk!h=z2Y$r/w)-|qP,bpo- r0J6#ېm(7U!$٘sSbYHj V p;䴷D^m\"߂ҷbH+qSukX6.$!1sGSSӎe;DehhihX'%t ~0ІaҨ%fhj*Xޔe;n<J+r±DCGEz۲EZI6)NLƪ׿S0 s{G ȇl S[zc=mqT;"[oX L('acUL6ƚF-ke-$^dlLMX43L1[l'*Q^Mbg$mbػ>-Y//kҺae[3`c4ۿxQ͓|uODc3. dc>EaAi1d4oaOZ٘ Z@'œDgc`0 \JtQL?6fX'%t!.lQo G-QDKt3NE6bzSɼ~MɂwW j10O>^lG0I ݁Sz]6bzSluBSfJtMd1tQ; Hy>[X,Vo]c+rzJ!uSlc,76bX1uaaB 1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a`UBv`c pB??`c |60 ma&4hkcK]QFMvH@V{DX#T,uEz簍1 Ä ~lGQ"ja.%> *@6* pcrba˯ Hb)`c :YEQ =3!'0ؙC'3y`c :76f草6?9d:lc 0a)ӻbCES>#U290Llc 0aۘOaB11 Älc>ac 6PTma&L3Ӵf?bc 7|60 ma&4hkcw~÷r|S>W4ש)HmafƢ:wP<s|sG|gJZ2>aTdcKAjH ac)4z"oaJ[IuϹ^^@! h,ByQ>1* "'H1 8bחDЯht}r4l sc^+)!D *lc 01S60 3hat0`cp鍅lc 00E%a„pac |60 dc ƴ1 Älc>ac |60 S K/抖Mamm^lmc~0 tژ[|{W赊K&n]bƼo V]$;S|mK&{Kz= lc 06FuIҦ7όo3!A{cd~##ӻwz=4㰍1 8>rh?b$ s_GP,ZvC2E>l:1agi7ޠ a~l,`cpu(*60 &0L61aЀm'lc 0A8٘c0lc 0aB٘ڪv`c 7|60 ma&4hkc,5ޚ¥TkMjK1 8XGFM9-HQ}a9⭉o~ Suaj'71Rɡ_H/·6F?*A 9ZQ0̀=%]6F1 Ē34g Swad=FP%:lkaۘz=ZH@SaCGmz]3ǐ2㟉^P9*$$r^BD~ >acp._/dQC1a#6FwԁQw`cp`oacpu(*60 &0L61a ltЧ$0Lf61apm'lc 0ۘOaB7W)^S;jԷ5ЂzMK&R0̀go8~7"G{5|Ugacp1ttkANǼ1_qKی70#^ntw-b^b1T+^,Bv/˂60 3kc6dc7֫QL]aXoOa^¥uՊ:S.3QZ|ަ0̀CuO6&/`W\QE yKC~[C&pDyϰ1 0icCggfPacBO @X?maff6֡dm ɵ 0L"l,pj%mⰍ1 Älcma&Talc 0J8٘c0lc 0aB٘1apm ,v{Iii?Z'a `@ٚtU321 yؒ˖o>S#ZGJ'y۪Pzq[˨L/o46tj5HO&֫cz<^Bo;+j~x)zt  z7-^2uFhc-?]>]$^L Dir,,G G̎u@&rL1PRZjg1 y|:Fd$^;Mv|z/M eId6Vt&% Ƽ9aF*FKքfxR`cdIt6F>:U 1It3vc >Ba(^f/ %<C^"RƘdczkMH=b*4Oboҁ<$J>{ҷ=dUfot65ސS6t\z!rk=dcLo}1|\XMGd׮`uɉG&;%<f2tۘM[6t@[ͼWbc"CN{6&k'bc_u {2'}ؘmazƘG<&3PTmlR^^n#Oc󄓍;1Hkى;v(**Q0Lź׬ͅy^D{ۙ3QWxrss333 a|N6fSTml bwܙZ\\e***H;tXIeeezz6X[n۶-??f 3 33߮i-ݻѭ?uYYY`]vjҦ,݋Q5alcm,ؿ?:.8Ɂ娑T^TTFhdtmp*5a16यFS6FVWWާn7gffwR Eژxozɽ݉{_*ʹ**>؇wm,L())7|::m]ľ};vذJϘLJB1sDm,@~tm,)++KOOlj;TFDl^0=K{1z/@Lrͩk¥ax!LWCyV#bc}lc!Feee U˷mۦFAwl(,, ƆkzfOOm3`=ە ]LƼ' a?zI ɮǨ19'C=*)lc!Buu5\xԍ/p^V#fuf8YHtpAF QSjjUkǤT1!N{1 LHĪm?uW)vIp81sdԯ_B} *)>肛m{@' 55*'@IIIj' }Dwl2=XB_Z{MKKWOWKMTRLzo7{;{ lذ"11ǻ8öl٢{ cUVZ>/#V'c' Qdc}B 6vtm?w;ծN4p25Leo}vv} 333ܵkCM5.ewٝuBv2Eꪷ;X 󱍅.afc܇I)--)wܗB r[z~0es&%JKgTRҹOۛVi;rtfgf姧+%'ٲ%g̔zfOEEEi\YVV}c73)mgRZnrڮyivJNKIݝ;5-/=}OZΣG Bp@8>G1,_e enKAi+JO}6mܮY<}-WDG๛Z o*o߁!C6֭<̌uд}7ӣiإM IbEW6+-٪h5Sh6{ca2N)7w}؎;"Lқ Ӳ49uJoW TTT{'`DCնLUK&ҨY.kBe!KePs7v)[d' U'#?'crN)99EK7 &kMW &gT-~y {SppuՂCݻwضmۆN0ސ?aQ6JE| iKؔ]HEkh 3!K8٘c0B_N1٘ܡRf1NƳO/m,ٺu+llÆ 999&3](<ݞjg٘xQ%a>Xgc%\zڤ.Rw/xK^y޸ ?uƎ|v mSW&/m̳Hkz6u\bQs 1٘kG{Mͳǃ!:vHAfZo93]EacdEO\C7`]"N o{YJk/6{}HgmRwl=gNjyN$ƐԾ!JRW\jmLcsVO㙤5h}r_N,M~]=cb҅G. Zzzok<Gy'QX12Bĭ21,9偐6IQ ac`i", 6&sdEؾWvpPYL6VHU_^rAy?Go %LK;I\plG׷#m<qCݱ1H!m1H1aKu =´6F%uuƄ{p/t˾85!my eVjcH$Ð^6~R{i<kM'1H1|K1 17}2CtAZ/q:RNog&PL; r|)ޅ(^(r*aJ(Ww ^ h8pzclct)ƄyЧT-~ƺOO5 xC}&hQ@?HHHoZGyaVf&->)MfYE} >ޚx:)HAZȌZ+O&0:RqX>*Ӟq 00ꊑ3^mh86(q]^{٧wIɦT-~y"ӊUԂÈI6aK1EtlrlYy՝VgYǃj-߱}{fffAA}=5ꬑ GVcz6F"cE 0ژ[ژd 6 &N˂7)Dw wڬ!0qSXܹ+_15FUdO+?aZ _~״jꥪdg-Z*|q%~OͼGci_Z΂t:ctA W;pӐ i! ʧF( 6m,ZK$Mœȧ̻Fl,~=6dȤI z+-6v^|U⳱g }GT<C***/rݳKRM9@a:RSrԞ='#'˴*84!)!a֭MlƍM9$mȰ\̔])9);S3wZ-;5#JȅRJٶ?)#jk~A6RX]]]}}=j*&|̨{6}MZUlhh_ ~זF0@? ߆vi 946n܌QG zOBGf7jjkȽUG K$$\EIHP 4J9LY+QQ^uAtg:L6рݯa *iiipW uVHg%sNWFF&p[Nt0C#“01?ltS۷ohDt cF*FX_ar,:Gb_&ƂDAAA?[棣c520? S2`۶ei(S,iWE >2 -gr),,޾};\tQB3zZtgc?裁2tL88Sk251xxˑ?sEȍ0Dm2J@/泥B8X 7*X_&z4OBg7u c0V!^ҴZY4vQYhH`*z&@[߿^rii)P>Y-!l_&z.u6G{"oEZdGҩEF9H`X]]k.ݻѦ(&ge:1z7&wF)0J\."_ƷT\i\EJ#ES"Ct䊫51N+@SC|g"莋䔅=Fyt+D2j\B%uCO$\g ~SSSj=tX= SZ *`LC@g 4#B7F 6=%>&anw +$L`&f4rA,EZIda` ???^ӱH6$;:EG/pdeeaQ9/y(j[CYQbC!!Jci^4,b@hי*lcgl=:X$,Ll@Z[email protected]^~, 6 kj8XZ=C9Xvjk͛6lP^^5cx* 6_w8"zfHtowq"dj8q%fDlv:Z$uQ!.3$H(@%HP)-' âu {eY^7a=`c'"?`|[0g=lnrޛ\H{/\$B/ $$iڦm @.7ErfV"b1 cky{fvvVJڕsΜ9sfym+5iiKKK1'brDJ5Lh M& R`!H,[ lǎ])̾uv%/NO]z8(ǻ.%5e7Poddd`2_X LA֭[WVa^=u u'<$5c1ݛ;f|/ƿziA<op?dqx4荄["ٞ*fXRp }BxCu`k4F[ká`Eze=a-Zr%1CK]\} <!Wp}nf;N;j]^ z_-B7?>\o/΁F Yŋm7iz^M6L\= c}]`LѸs"CQ}8.\0Dgi fA"z7XCŹZ~ %ZՠB+ ,c0DYʫW3jZjW1Ы0˟2\bظa#Q %%HQ5Rs3֧aFLߠ[߸ itC %("nvvիSRR WXK{V\NU @ _UZfZ l U YaM;z#x ޚW.YjJ˔/ZrޒТ+}sbVEwnsm_] ټy3n+6l,|saVrUHA0k7BZne.d+ǽӝSlEVd9I +ѹ.~s2$h@he&gcCmmG *:ƒZIU@Kj\`v@lCC* %F`.q![V78._o1FNeJX V/)Tx=>]Tu c03uuz"a #om=ڊGZւ%ӊ 8e+ET> ŭUBEl)bSp߬5{VRrRRRԩSCDB|\B<O( dP!>.DJTxފ6@kIC-%&}Q>wpLu !Bzҭ<]B7>^fK 3=\lyL{tqt]k|:f1u+B-|C֦lꈉ4Hnq15%1u_z"5mG(ڸ~c2+*XHr QuЪUtV?6[qcxQ1c To1ҤIɎةGM>?ӶEsd/'a1^6pz"a,==:D?E,D'ĶL: {"W 5pk˷hdK~5~4{ZZZzm!Lx I3mڴ3fSRL+> n*T |ԩqSi8ijĤ8ȩdXAup)t tո\)b刏IVRB -tYʤ?9 \B-Q>:҆䏻fV'g(AA.&z8=2rWo 7 ʕ 3sV\\LIO/ܶmkRS lϛ~^,<qXB,*Oo#f/{wzpL:~$^k:NR^xՂH50j$M칔3eE+P2= WAMINmdeexݲ1utIdࠔ}P6mZDD4*O45)>)UIPC؂!˅qHH8%qz\fLON"FގOJ\bZo[c$qp.U.ջ27fÁwbgl'Kֽ<;,Dy|=:3RCE a$8@<i'㮫BA&vͺ%.^8sKwS5էqN#pT}0x{Nq0eۉ2jw 08|0 c)F(A):ri: +\*s()K /x;[C鏄{s8ս{6d=eޯym>PS-|nNYXbP`Vӹ|‰?Xx;-{6z&fӈ|4{0'.~ME<s=;tlBT !Po8M-M*=NLqSɥF\z#OQ@8i*{-DwgO238'7auR%^Sh#[+ohɛtE{d}3߰.I?bs:s.A!"އ#EXR84b:>cCh 5/3_> ט~cx†>;Qs AbPR<yqnD[:t#ȇ%C#(ծ{>G4}'dׇ8X[v cw߻1Sʭo~cuyXճ0;>Kc/z--(׿N4Gk>@o^BPﷆJ0Da̫Øi1N(KSQH7{bbq_{YcjM^ K4'Uq?Lԑ(؛lڭ1SÙ|*ұX>3>KRь?N)+ c0:%UV b!!.iE!&a8D!!zR I-̿ȍyk1lH-lж{ ˜ #Ӄ01O6|BD#ĭIApVjbζ< *h-%haa q{!D#ɦ܃T5-oW=vc@C wP~Yz}, qa cMɶߍվ/hCƉ`|j`\4f|UrV_'RyK$CΤ3(E1X`[_8QQ1}&Q-_ppA筣@Rcv 09 c)& E0,1D#,;n(DedHڰ{`7FƎ[`Ucǎ !_ crC4 $P>,B. X!CC8<a cW5FE:/[u,0f/ Ve~rcĉØrcʢn &_1s>{1=\:c+SEV͹TOĜg+k*=ʓ ?+ 4f;3cTUo7u3 SUQTa ^Jm -gUa@UK].n,L u vca!\Ƭo-C&5ME=cUXsV w7][]2Rsz%a(raюay mןusԼsn?̼3q;] $uщOQqJqe2D s<곹[s˭7o+,t_i 8aAUĪtb+g9i;ʟBTx3j!U큖Tz䛃-EEeuuFII-ܢ>0@R $L051F- Eq^IqӒQiS⒧zb|B2 ԧ gO0&`O¶ɉI+Vj]r;񎊝8j#/ h>%(kP";c=aTqqH߿u[ 7\}L]D)æ Ũt9n,&n CY5&vQ/{SCO§0F_}P c8VOp&9Ov ;tv#L~Il<*ʛs<^G};Ńrmؐoj" #a *" =i:FA:]oL֖Z64UGKZ FLK/DKN!TRr2bN2Y}'LKN"Iu3%ᴤiӓMCJzCI?``zw5jxxcG}*;'A76b=ܢ랺A7>^^m/!*μk &O dO缲5[Cԟ\7яx뼍ކG%f[c(7 l7"/GEyY7nCs QjWͳCjw4^~~ttwc_Jpr^Nr }mo-,*<Uo<`ƍ[l>t?z&)}ކ1rUoN2l%-+!٠j*h[xsI5+Cq~U HJY Ue.$N Wj.=/G=|n]^VQah{v"er#apt:mR2ݜT\Rb+iW@Ǹjj[ 3Y:7=جP(-(C%eК)xC\NUo஭q9ssrrs.'1A E2ok<ʲJ:]+(/.ؘAgWS'C)@j́ iD,~{zoxXjYL}. tWR͹! Nt=E-t ᱅ &\QkOʨ@V$r(JHЃ-E!3"i裣\rZ36gPu3 x3::Տl@ F0o}]}WKhdPV7ةk5{FtӦ5Hcޢn;QjpBjTgR@\V[·7%46[XPG?GA'RTTe K38@jTNIIAl'^15Ì gt}-Mx큑 yZG5 ?4oSӑ@N'Z?]V65ͥ_꼩(%555w1zq:u֡9Q=]]+* qwÆ D㗆 tF#u|yb>ݺu+2<eM$zG7:VH!baFA5[P-u}u0Tjκ1ieggsRQV***233׬Y .tI_ǻ淮t)N۠CRU >e  R^M,M[XX3]1 a `VҩT4#OqhЫiZjSe0رc^-[+ ˿ UQpA9#QpO T }Ԫ2= u4Tӈ˂͛7WUUYۙ쾼|ӦM֭ӥB{*E jd-Po]==Bb R cWw)"s`R-4SS-̙28bbcOgVY9Ϋ*++q& w9YHIII"?"H` B.HEC] cu{BJH$7FB8` # DLD5^o t>bT#!z!P0m `;|[email protected]rS\\wuPEXd#y -).ƛ?ZYg@1+(]1 a* /U  &\$0c4WSSq/k Q:a}>  s0kvs),'PgB zk֬F}b9ba,ZGxԿ xw-E8"X; k$6otׄ0d+yiBAcKsbiV6 ]TO#РL#*++_ǻ,//Qm|_Xǖ-[oߎ1^Ulܸ7AװN@իWD*V ֭i 9ll /H#Hfvp|&/ xD5 0™póGjj*?L<0և Bًr媥KbY]]D<I,//D/Y7|' *uﱌzLުE-YX~;!_OϮDcӴr5Ͻ 3p'[1Çٮ`C,X07\>K@=ß~=ڑ0WY~/Q>ܥMaBDEWVV566|k^Wj7{P*UˏWS[񌩇 } Wqx32jGgٚK>`Bb4bLm^ aT eզ:^{ i+TCat;Ђ)QBU#Zl92CkѴC;k5kbuY OD¾]!aѪ@r<[͡H=E Yr/_ƸBT|P} @];0Ž̒3́.| $ݱc粥|xTǬߥ9-Q0f}MBDjUʒ%[6441u.㍠! i\!Hs]io H{:cC*PG˦+D`6+">X¼N;gӦM ~(++۸qczzziiu+WvB z֭+VXxiHZ-!-^d2L ˖ĴT,]2tNYo7co4wކ@v^FN.}-DZ4oiś +WNQ?hnּii$Y(_F6@ε.mݺקܹӴbvSRR/[QJcU%x"K PSGtA$7jIIqɆtcRS8iiӶdn8%7eOZ~)]X(..FHCLECLSD!j._6Z˖/hK/c IIIӦAIJӦO6cXVyuܥ).n{T|Az{ Wc橧'zd}wp P mR˖~,Rw}FFF/ච;wq$%Ĥĸ8ɣds@<MB4̝;NrxC :I ,ɺe+7kv*7|IMpҢ~|x@!̤_  c}]t:|I0DDY.)*UHM=@SMޘ<Fn)Dӧc x衇u?:ok.*ú[ `lūшNiDiXhK8ZE JqOv1egg(ԿRؿ'%[Prbix$p$!x񲩩[XhwB^϶p -}t E[dB c؅>AaLݻw[aLPԃ<I^cg@Yp{ Ϝ}H c3Jv=ys֮Kӯ@ al _EX ˢصo*NMNbϗql='to:M. sYVduF7 :]U5ZL:;v}MZZ>F:!a)ԮFأxk~x ׏{8Z%r/Gºsot>0Eªu^|X8@gED[=Tvgjs==/r地;)Yٹ&DQ63ḘF*POD6AvEcr.QPc32Cup?`z'G?+RSOnVrrru:ƚ[A1hޱ2!%4r`}ݒ<X]ر<\Ɗ|DX?a c OOLzWԔwKpQ[BW߶~gBۯ>H`-Sg<k>8(یOk3?wBI4!ѽ[Q_BԾz,N3h\Cs.UsG_hʍvՔni m=csݚ7<?jmiVGa},հw~~d`~'Jټ~SAS `(yv*DtD /U5F }B7<\ytW#P%bZr?E1l6<>vدvrPSڸιꀿ;ihYez8WCKHli~3G2PX^{VhFElJkP,w4GYu?DDl1RwSlaMW"Veo-_\9gE26d/(&ƚ E1cp&HvGs9hbdw0&LzwGz cVݗϻ1l̻8f8Djo܋BD&d)8& ϋM/OCh 5o?eMzWoY!V+{ D51 QAˋ9- al_(A96AKuf{Y};B k#n a A'!  kEw|lưD h Be<T8yMto:D}[GSr9*Bx !!]O,06yS7x9Nvx?/@a"Gg&EuEg( %d cH 1B<0fn Hma c.`j>ꆛV"aBB4B0CUȢYlÁ41lH#?Z&*\YUC\zU;$5qƐh~/ ;U1{X$ ې0ѝ蔎_al2g0*Yx8EH6hQ !b!!yūKxMLD!.E/%*ƌ UWs0 ܿ{1DCPG7a wWDP[߬a A%ǖPa V0gc5p[’h cZ`u ؆sn b-! أOnE>nDMBb^Tc0+k9KC1c7v4!҈^-_쏝<菊Χt7UL50򖏝06ܘ` ch^ [!Ae;r3 ]`؍oZwxdQx9;r&,3Ɣ91DAApxO=/0@RpcXARՐEjii1s"*6P?*|a 3 cz_į;ʈjҐ1$ Aa G^"36.=c6EZZ1tOcƌ@!*#;v?>˹ vcU0vV!wYjQa "Q ݑc\fkv&BX` cn,\t͍u:zokW=cVa4[){nݛN6@Nt-3= c!n,\u|c2w|: 3fн锅rm'\0l[ں~K}y݉N}7p=}d֬;SwS6na %]]2?=lk[Y6r?\cH'***R IIIkBnEt]p[p Qn+fLn-8|X y@8p@aQMlڔ1m4}Hrr򺐟>:tEqqfV ^c~ '|Z  cB05YYYo  cB=1555W]!\HzEwØInnMtFHzErRSSKJJt^HzE/ØI~~~zz7~D0&p1Y8OL HzExØIaa!Z @˜+(mO cBXf͖-]f/)--Ŏn Hzŋ`tٸqc^^Ԃ HzA;X۷oOIIq:ػX4AHzN;.a!aLK]ߊs{JVު{oplTsfG(!r06)=?qcHB|ۆn=a06ԙ7mOC`m9 N70&B/06Ա1ro-:Uc-u`5|ԡ V1Kδ[--.~{=Şgm{~/tAh$ ula"SipGH=:Zp 6D}1|Ec>WT]z>p)}_f Ԓit'5޴_8B١=v϶"!1:>!!=>ZFC 0&N[7  ٺ9~D mbG|e0%V#\32˩uϐe$w0`(U0! A5FxC3m~dUWQuƖ6-HDP7 cuȄn Tk9ݛ5~amnY$}C=c`́0Fk?%v%1*n~KSn,M*'s:ƍp1Ɣ!KEP(D5=n]ču,8fu*VYȊ ǟ 0H\>Y.蔛o6Xy{g 4Ƅ'zчm3u_먣ZhRVVyιoZ(df 0HrmܸQg"\銕+WTWG! `E˜:1TUUv1YD D.; WQQ^SS55xA]__ B:4ɺ֭[αSqfPΘiA c<Ac@%_=Z1A&EQQQFFQЀCM,?Dz͛7s<^" c f$*v90YcFZ%s0{:ߦ 0x/j%uA7],l˖-#B!a, E1zM*0H aFYSw.ΚVaaaVVVii)E b$tx1#UUUfA$E9A9[tJE2fI<AcvH9}Xj?Ak0_ٰ_Hp wp˜mM8mӹP~FXtG!ĜH=Q}`,0# \n7aLx)BUT=?D"Pk @RRRQëLxU-a+VAޖCh#u։9~FXt0 |d9̨B$ Q_MEfVa3F7Wi[mAʇPNT-jbHCB>r,ںu+*#*p .ؐ7ESUkRW+͢ X%L cэ EO( P!,effcݾ};t[í081Jdϣ>WVpkT aYTT]VVFEuuNmp1 fYVKZl5kPvUځtX`p:/B a,dL.f^3%6z <q+W?>["uaq21,!ʚMT!qZKuf-:+)-&X3~aW(r i@ASLpn` -Q5܁*,,LKK !Hn|&மs"VxNԫ*ܾJB)h᪥[6ecVWQ1\V@DNࣿau_EfZڪQ>oߚn͛7[~ . ! YUB5*a\PT]"-_U0ڧDngP=&9Ȑ\ B0xk˷zދ>o33vg!:3g>nig?pyZƩcVÜ>O]vQ宸{;~EƌyXYci9:s3Ϻų.zv6ܲ| x}gIL J3g<.8‹.",.| ߅^!} Pv!_SQ1c󹐄.9ywCۢUj 5TsІfV+n .8KKIۂ]@HCv%<|/sOee7(覴w1qԭ-&)dc4Ygv͎:;Nszzeat r6_}yEE˓T=ʱp6goڒQRNSPVݩkǰaða2@&(b!u ހkbZTLuQCn#Fq0`)1=nQ<Ƣoc} 0qǔx%$咩1:{cg?o}pCj8sz<x4՟<\72bd\㓋Դjjjk8~qG!VKP?Ge}x| [pt+00aTprNCԔɱQב/X1:@o^B0fd[[չj==Զ:t!@s#61, Q7b)6/ z'b9"5aÿs`:XGubrwh/Ço8P#vw}K>oj)Qh b'/haGƪ  ף];G˜  cM}SQlDil%VznSvmC\^hj޲NӿW߶bA:ՆVag;?nΟVݥFgoۿЩG)KV+W_p-tY[!nFZaKKˁO=?N{VϓP~М(Okl%V wvoz@?iiݽ3 _5ϵU܅[X kZ}u8-dQiU-5d֎25Ј:`w`6GuAH'ܲ>N<9&_}d-tY[!(;f=s0ijx?XSoٿOVyjDYXXr[U c " ^+c-G&DIJ?Ci9x%?UB>}q8{el :6vpVmY̐Ua=dޜDUt~Ջ-tY[!X7|qkڿ]O{ᘵiH_4\06kzGE ?a,fDABCܘ$N cX? ]ih!tyƬ:l#RSbGvP9!0*,m*݊ y$E7ޣnUNh3Ri "0vy^hQXxABL [L:0z#a ]VVa#a,q6V_4%Tg|B}4?1ԧeuz/=MQh۱k'8np$)o)vZDGl#f{SmΊ%FO=wC]<쳿[O)W8þp 7*ՍGObXE۩?HZ+c#v~_AuNFF5,uKsnE<ƢZ|{\5f8GF@#=4 G<;˓gtm_ZB<|>lK~ux=<n9aĽ'{CO%9i&_z5NSm߾k=z􈑣GEihGĒ4rHCH#Q45BU5r448)tMUoQI#G>qP4z4 PeD>456+ں5_[Wb!Oꖮyrbq" Ƣj_vz<Foc#eݍ$ u&Rȹ3aMFOz|zP_`訄v !U{5KC]hiE=ǃ:v=O'꽴D mՁUƦ;֯__S]vXPXjZD^L̵hJ`ͶmtJN0)_m1㢟Y!# qRDju^=>ixjQHkcu<.wcG" {Q UZu(bQl?ZZw@HZT[PP[$v˂~y(G: ǶMV0z-^k4BUއH0 d` O&z ]zVaL)fd#Ev GP(ڎ*S 8A,YGQJoZ6C ݐĶ cmCC#lSYYyYY L{ ָ%Tn°"aLBD s*gV!ӹv̮vxa>SdMf@ (!D$ CT\ W t°b:-0333WF$ BHۜ@.1F l׮]wE˜ 1!a+zrrrڇ1!D$ U]]]SScF˜ 1!qaxY&55u:/BHD,IҥUUU4ʁ\yA:F˜`߾};f|8lzuԂ#*..A:F˜ZBg >Q8Ƅ ;c W^y >X;LO۠" cB)..?L2wʕ$AHzȲe>5j>NYp&1H coHz-;X>TgT:6&vs8FٵZGZ:ՆT/8ffN):Ӄ0RՆ%W$&RNΚL]!aL Hz-QL?9G;%cLfE/+F&$ƨ(;Q+#жZ[}B^P GT8p`_p*j ;=e6:^:*L#!rKyX?zk#VKk5kv537I3ʂ>nݎOLl9~'oyȢڎV&%Ʋ$c*_{VH1a( aL!;@1/ىsB f@Mäݘư-1 0kC6QY{f\>Gp!-aO)0n(i~#!?n?mׁ {'aL HzH_CLҩPP1{cdF:k$ C cBYbڇA4$ =ROCzX]NG;нA1礥ϘqۭL"z7B UVK/007o~YY j$ Q1A!0& D1A(F˜ HAnoA!5 ڗ}  c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!06+uNA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ P:' Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B D"H$:0&D"QJ˜H$XDZ#Ͼ2d<duUp:*Dll"\C .[![ByV!e<duUp:*Dll"_Ǟ|iqacs~sUՉc1&5'FzkFZO9Q;Ff #N8~' 1^=rܵ3j5h T$蚑Ff4jhiulkFxYO9;zęW8Nr2Up:*Dll"\C .[![ByV!e<duUp:*Dll"\C /[E@c~E߂(d9yտ0cgN:qμ~O9zQg^q˜:J8\DK75ahXrkJGrb'iWF1c~u'jWs nr2Up:*Dll"\C .[![ByV!e<duUp:*Dll"\C /[Eݑl5{'^Zxek!(*kUK1h-ȉ1ʢHEw~u'“.3~qaUs5z0WWx3SN=oo8n#sҙ̫N͈1W闟8]q9[N>Qcq'qZ}hX>n{% ؈Zל4c5\܉tc &ӯίzY>N.'#[ByV!e<duUp:*Dll"\C .[![ByV!e<d_LVʺtbVO4\~ïXW_39:c`6F޴w߻&x~ȱ,|/z,bdWuBGdNtŊ֎Rogג/:>~1q5dv9N9y3 9Ѕ?q_FFN}U2u/?|_~}DxL1k)g&17̫N:μ3=~so8kO>>W?>x∱W8ˉg]ukNwͩc97rl,{bBByV!e<duUp:*Dll"\C .[![ByV!e<duU|/ ]12۪!dfN(.w$ke. E#Ǿ2,=:IDATa+mZMN'`ta7 ?Q&ؗ 5ݑy}2VtOj8ض>e6fV*w X̽3]'6O{_sx1ן|an۷7__g%>E<wf.xጋ&y</w9w\vM?SOdf֑x:λ_{Ÿi'߼fug༿GUyGw$kis=Xl"\C .[![ByV!e<duUp:*Dll"\C .[![B!.V7ꨵvOO0Եn<gއ_1kBzuUboi] f؞vW5uݕi`^XK Ա췓cU&*[f/F5⤱N?Mh呲L8y̕9׾mn'={3>+O=cם0_zq]8/yzW O7wj¹W>z`:{=3g|ziy:RK//μ1W;m<sNU*J?+jCcHel5Y]1o.+ku_&v:yˊir6VUUzGR6 3T%AeF( j|aQΛNUωe׺Y*Ǯ߱FH3ړrC9_믧>|eSŋuMϹq#μvm9G{9:r ]pU7,y+ܫոko<-Ly3.}5ϘvٓN?Gbę7ܫN: r۾}D"H$DC\]l߇ߐu͕}rGzBs`ДؘfUpPD6 D>|üp>]1càruhlhG\hY]V1axȳ9Qg失W2~ c&Ow ;a#Ϲn{OU?>sՈ&fm;cჿ:S~w֯-v5꟏iNċ?z̯Ϻᔛ|hi8;1&<i` 9a~A]xCy1GvFβ[wE"H$DC\.ʀfdu6ud3g]M~xg_F?ixԱ7uʸ^?z'qbiO8gԩȎ<Ϲǝ&;gMy{cI\߿rٗr'r~Gvoߍ<~_'1akO:lI㯸+O8/>?7g'?›Ko8ˎ? ϾӮ;+1c"H$DA1ՕT'N!~ ¡\w4w?Qg_7 '</|oǍ>{Gϑ/9g0juN=n&pU߹9G~׌>ʓ^s9'^yOwco^~ܸ+{3'SιnY׍ȱWs%-M<iܵOu6rhc뿞z֟Ν0c.\$D"H$$ENgElm]qTFyͨ׎>g]s+G~7 Sն^4aX+.fx%$E1]ԕ> BkGv8z\>W{v::tWx'PMޑH$D"H4x$~l$.c`cEOr'}`D\X׌׌ JY5a#¿M1n"TRv_lμjکmTaxM<鬉'u-ވ3qU'Ү5H$D"hHIc&`4I9t\UeFj? $2N^Uc#NF[^ʏY-lưV}NN+GȒ[gYq]" D"H$ *bD鱆bҕZX2ieTSFK2tqվ]mh$dԆj[]SUTD"H$;śA)vl5;m[N'n}H$D"(J$~l|'5u.VmeorGVeH$D"(z$~l|2Mр+Ď٪D"H$DѯXss2>_`[wj)y=\*̸qOVo5^]gNƥL>h]BdQUB|ȗ"H$D"Q?FvwtKMA}Ǵ/RH[BmV*ve|E"H$D"Qc?oϔʽ[I*f*T~vyvEnw{YW{P|;%h70*m GM v*SIm4`Lw.vb^U+-D"H$SOm Y[R}g *4nF)k.3E5q-loU`/ҝYۦPe0z^]ۥVm+=v?2_iH$D"H k׉"y qs k4Q[w=g ʲ#G҂i'&vRNʹJY@vhTo\ٶ(H$D"H$4uqR?<^Ow|8~$ŏD"H$DEWZ$D"H$EďD"H$D"Q+ȏ0?UW$D"H$D}-/c"Q8K#PN+taH$DA=n߻n;n}4]Ռ ut[}Sp((ZxAIU]cZeSAW!a[BG"v D"H$uÏw㖢ԴmN؄B<m6@3κ{[ZC"kvBbK®?pӆuTۮcz! ďďD"H$Z"](3 6nmmyL߆e;Q5;:.cΛĶ!Kv/7> ~ᤤm%Xr˭(autscG l7|{T%c'f /+WgM? E*s܏x>t)Allg]?哓#sBKH$DA1]W7py[oӑӉ%pZ]l=J6`^VWf=tRi{ǬmY] ĬB_<gZSpsynW#(Ѽ'S\̏2Z 2hm͘B^UtIvBc-Dh^KZedYVM7e\tlYm+c"H$:} ތ֢"clB6lSWA-1mj|K7 QڒMKR:t-V%Z󸚥tS|o ۪Pt׆?>Q&Y4T9=^i-\hȮfLaUdXG~ j׌AhY E+&;ڌYB[*=$t]ue)nyJ~̨N5KSAl;IH$DA1w?qkhqֽݑہzpY^PD~nmK}66o膘at:o֎:do뗔Uf:Ť$ȽK{0cEmU'^ 9AՂC{Lg}^?h&l13aBGymn ފ2QQ:D%['!ՏQIY2yi|rV57JH$DAmn^Nĉ㡫]^[%rte5gb1˼KFQ,v+٦i$m3crܷXaF5cd2 ,wG^aeդ!kB`)lUHcݕ-?^D"H4(ճcm2s誗,ȎAm~G==DU>PS #,6[ d>{ezs?9KNB3c?~KH$DA(%P8;FmPĀ.: @XďD"H$?&H0<.[E"H$ďD"H$D"??$   %AAAc   1AAAA    ~LAAa`?&  00AAAď   AAAc   1AAAA    ~LAAa`?&  00AAAď   AAAc   1AAAA    ~LAAa`?&  00AAAď   AA!_SahZ=B   cCc  Y:AABA   D]}%O^0լ~aKܸ(in޳2Qfw=v[Ur%]:s.lޓZVF=j?ws_yc+E!V|0AA!Sf,௬tPM.0E%1ls'ƈAAȢ/mrM'tUz0s?'㞛+k1AAA,zչL.[@/7:vOO0Z?&  E~L4AABA   DdžAA!?6t?&  i{an@   D"vSǑK   D"c  0$?AA!A(~l{u. g]n>,zQhYoLwN۟jď  K?36,{V&Qj^37LX%~LAAP5+ys5n^5In57+V+kcT򄹨Tp1ՌB=Zw`D~lWBAAL{eNz0Ț.˚:"bY .4q[؞Ɓn*G`l̊1AAAt5LdgծC6Lo'e3m1"ec_l٥`~ұKzYoTԀa.ď  [L,Eۉ|ď  g~LSď  @XnAABA   DdžAA!?6t?&  5K7g ~LAA" c)G%~LAAc1AAA@ď  K?aKxfsJ>g %ByKg\I󞔩F+AAaHХ#3 ]:ۼF=Y<yyœԗ.urVHq .Yv{a`m:vQcc@5^զ?A   c&)2]۞0UF Xbfjɬ`x9=luMXZ&iצ?\9*?&  C.Uhd3F&G^|f^թ n*ZשFdTH/k5@   B?fż[BX?&  C1e~P ď  gDŽ>E   ďE z/ݜ1AAA,ď ď  Bd!~l ~LAA" cc=n@   D"vSAA! ?AA!D   cJ<al@zCtsNU:yOTޅ3l쫹y'w6L?&  Cc:#`.q<· \`37:c  0$zu(~Ye7hk6ԨxhQ5u3Jۍ)vw)kǰ-ZnU칹[0mB;L􇁦Gʹ6%!"~LAAc~p1=afcQ1Avd^hOJ"X#1VsE.Q5k-T5>؎3@f>mނO]AA!AH~2TtoJ.{P"=r50xZVwՌ:v?40<S̸|T2njoFY@F{5$AA#c9?3Æ2Q &"ݏ?AADď  @XnAABA   DdžAA!?6t?&  5K7g ~LAA" c^ ~LAAc1AAA@ď   D?w=ҙhnWMtG47Y|17tˋ\ͼKz^n좏?&  C1..EN u.Ԅ2 $-XSff f Ǟx`ʦڭLVPmwh7{bcYǂv7+k_ YWuYgAA!A\f!]1j6Ɖ}m[ئ}2֏mnS6gl~>T!~LAAcM=ca_؋ <;0H;c{W͚? ԹkY ҏۦ̸m^e14y?c   tE~П4Q'^3?&6ZÁnKÀ1rV3~!}R3z?&6@% & c9x7   tT拏3k_67uߞ:AAA:@~$~LAAcCc  Y@l;tsAA!?rc  @ď  @X"~LQYYhqK/guwwnYSse% N~y_ɓ;,W47Y ?,z3יC i|>ItHj6Ў:@VEp!cې/O^ď /}puaZ_x1t& HH~)3n!)wҟMZ_w,6Lٳuɍ\̀edq\&Zo?&~L\6!jWFVO  #18a_w=1eWo+ɡ[L.*U4w5u?~;'  nM )賉PP<N.ښ:.;4! rf<DJ 0PǴ oc9Xu:Tܬfw0yusz[#/~ѲyNal~̸?fMw1A@g~,ƿlk?PoO'Z%v(Eh}_, ,7R~5^ď E~{R +Ə)륾DžrInywC?FL;5<ڱ1VZl=a+hsi?\e@rNpx_[ v*~LA~ ?Vύl(U-]x H&u[[7^ R ?pI;TӆتcSuhGjj[lnud̸:ɿؤ&~LA(c y'et~H"~L0Х{B"Dz NRj }5 ;KA~K>,ˆ:3=~]̛iܸ_՚>.W$~LA("͏ @ a ?B\Hly4MYqm^oXwǨWTrȿUTcM<c B$#~,a7{ ď Bď 1AZx<ȰQ8.3sKYYҧOAcCc0p=KfpĆo:ֲJ}pe۷o߲eKZZի׬YiӦ]OAz1Ax<XuZ;-!Y :M`2334>v؊Bۍ7*WUUYYA:BXbX3?&۷_e˖-al z,Gzz:ڬ czǬU^fdd8N]˃뒒 m6^n[A*"vStGa0K|'|\ه[OhCqq. c&4p;W.((EQEmm-N8N ^̴4x6XMq\0rMa#~,?&]B+==WpbzuME}CjWTTA^ <n`sssaqສ m@ď %%%[l6 n%>8ק~ \ eZ$cIUcé[m F~y_ɓ'u577+~Qfcn&w<׼ҙ[&/F]uO({ 0BknO>n#4+~L۷!tB /٨`ͫ~c&. $55T mpBp* iii(A=+ 'es%]l+(UrYv>,zOFKy7.BTG.vO^v}j+6 Pzuv!~ >FKOO~k/sq+7ߏYy+Op֏Gfdd`TLa K~ i @{W2Yw`}6f ;xG6ȏ{'Tux.ԻtHda>?ŧ~٧͟} ?&a fퟯxu2Gyy.֏ǫ.BF{QQHPͬ):ܱ鬺 7z-I#A1}[J3 6qF +x2[`eU?vL߬T@MjZy#OSc[nwqq+^09|ohJ@ouQdfff¸br8i^p=_O\+Wt==Puی֏yL?zWI~K?{ma0?c&tfP~?1A X,-W"ײ+V*шW%/LϥK.6(,,+"Rp -[,ryJ0].G ӎxR坬hTBXkǨdʛ3%B~,\ ]'_4ܧrLRQQ_JIIxIdS]] 'Ɩ&55N ײz]ăkn9 .T `Ƹiii?618xE-**˜7?w.?̃ezjndA>W-\ %[(76oa[YY5ڛ1Aȏ >O?yPpYիWWpUWG֭c{`WG8 T0l0`)?9=?wqbYj}zw]Kתk}nwtעk*+kjk;w6x몼}Z~k??>䓏_͟QZZ6قiO聋/}aGzꍧ׬Ymҙ`+^)))Vt\Gs/9uޅ潹Dp\׮G;Tw3^}eza"'hk[&Mv{[C/]60?f-X?j>y}Zs\{mՄ.: {>};ߟ/.>}磂ҹ&U>_J>8o{~ |qKla 3^MH~E cfcBYzɱӏϚr}秪 L|. QW 05짟/[Y^S\\Bc5⮑֮Н5g|{|` ".?񿰰NO/--'kQϿc{w8ZԲ*\\ b-éڑ篼^[p]^zJ #147+67DŽ˅g?gsJwqFa&*ҝ>o.᏾y!{&׬:f16?lD(߾[<Js`'}!\TUUoݺ 0eeggu%Ŷm0}-[ Nե{[.H1G1Qxr ;vd#1(9#1!xb[bb$ G ?Cu>Ta.Q}X п@l;>}g~N?&ct? jjjJKKu'w|\.f 6_L7 :c>,V"8#d8Zeqeaj99 B#dwm嫭Êm>YA">?Ͼfŏ =s?fVE~³'j=mJo.uyi[m{o_۾[|r6N}b=aZ>_G^??6oZު<ɚm=> T A?@#V2v=֗cEqqesrr.vqƤJ;hSӪ??2ZeZ2lXX;ce55ʏѓ<X&#U"B?lUvtʟ4_?&.؈,-mo0~򥛛) >i|w?򖯚ۼi_ܬc;ˢe~Cc _"m[,* `Ÿw[:N QvM?rel_K Ul 5\e]ׯ~,bL}qY;+gUi6f' w4K3=UfQ?zm~`]}fuzٞpo=T/oV/A?5ʹ /66at Y,}*~/ˏjӬ~L*iFj c4~ֿW *;; ?@~,&X,؃NgӏU㲫- cSYnSN-|০;x-ώoQ&͟~)YB؋a.vUkrY(y=ZxLϕ-?fz$mYb`x`u؀}2z{*m13Ktr?thm~z)ٷS³c12+\V)^w fUm Y}D1ub&Z|Y'?(,m& ^W~9+ ?f3}9+cQA~~?f?t bi 1͚+?6JbcZ ?Ì sŠZv͘RO&ݢK?ּ肞SfnF.;QZ߸L-47Y|q۟xS!?!mT`vx3 Ī'557ia ?<C119_Xo}K{ͱ)qiiܦb_vlcf% 1ldU~w~csv_1uNobS1w%t}9Q>ز?u@SYla[1Κpڭ~,plF1UISz c\Y|'hW\XT+ǐ3-5mǚZ84<eX,5 ?6q7f<5:q\7BOH¬Q ;aGJ`:A7rS?۰dffSMM O؊̗lj𔣚uC1cBOo>g&X)f1ZcP~^$QǢxCv3Zw|ql =Sqwa1>`èu0F٬' * ˪J+k*ʶfggA ''#n,M? pK9A,.1:f}ccâ.dMLZ;Anm{*5 i[7n{Rx ǘ~,xAw"ijY=US}a⍫L3f}^(>5xcB/A$.,,|c$vYB\ii7xy2t| }zͶ¢kz~~/.՝5qQ?)'HTW<VkCX6]t[1d9bհluh{β1,x9a}Zuy0OC<Ǎƒ•¡)F(VZYYc Xejkȱ)VƊ@p1E |{010Wftljӈ ?FI,.P/pc-`${ }(m1kM?z;vIU/K+6uyEc?&t B# غuqsY[s?/'sʨ{FΜ5&V/  eN<=F8uxYs232|iNqՒ)ǝ> +v\Us[ᦰ>g;l-zQ=ikA?~%D,u-Ͻofe{5t/ONSY'qɟ:/,:)'4}f{{v4ռUO㯐_!=C{-޺\.d;f0fׯ_|yJJ bǶmPF ##Yyj.AD-;?5˸٥2ifa3X`Kge'X2Ԅ_Џ4hgK!UgFl~*Ǽe۽!f'ڏ ґ 6mљ!γ襪 `FFGuQw_RRf͚|j]>u o]ې!<>7YTB nO]_n4Vzk\;vԹ;6l7x})pBJKԮbC ،1YYY6lذu۷N'ZFi%\^!QH~, d= lUS[5`kM4맟Ŀ>5`6ďY?RPP`|wlm  zSSx+]0'>QzkYP.JP]qֺ<XWO C[[Xk04>d1Ϧ4H(V Ӫ:1e˖ eD%sE ֎뛘mҎ8a+t&5[~&*Pfzf>3?6AOfCc5YYYk֬-E*b`'D(ʃF0;Z>x 6\ZǬU oF~JhKZ"%JU oQJc 3v:%%% /QHὠi0-^Ĭ̘upVcVXc͟ K&~lH(5̆1+" xqX\\Lp l`E<p:OO'ԓPtUr2SJ^JH*kKChSez*΢ 5}ZZZ GqF"Qެ3̅XZ(Ag}٧cr, %HD!~̊4}WUUatݺH<uRDZa kHc 3=Gp>e t dQz7 iFXbEjj*N$Nqe_uC}ee|bsnj?;21}A""ր?fEX배"sCpavHpNuAoQ]"t>v#fiUZaXKiK.ۺukyy9V>6{Kդ޵ 70cǢXF!~̊[xaX*McHj 6]ib=@2 mO 1DR77ӍNf͚͛7íVݣp0?6ig+#="zN,RP<,2AWk"$ -Znm7p7lܸ TUU1zp;ՙ>;X]. ܮKYYYٗA_ ϗuu|Xг7H]ó@,L/9%YE_/A3fkh7,/8H#QPPrJ8a8R8Xkmչ4^#P(t foN~X 3]vt.z:C+k&7s,RXXaÆl$pd~#kM mp6Ph-mmu a*j*`wjQQŋ'-[۶f}AnUN݇W :;j!]>@ D榤^|媕[/󎄰WLx*//Ex/GOvXt)L^7`"ڲe ::%]ԔBp%\g m۶Z /yxŔ[]]s53'RmyodF=sV*NpDFyee4H~H^^?_.m QbWE i0``⤁#*@aG oc׺Z7?6t?S@. R{C d1r!fqܛ6mM=?!?ȎuNF- 5BF׳@!44Qջ`tB7a#*qP[fLzEw[+]TФ\ 5S-,D!$Wi)VpoO.˨΁ g8UD 9^;{+՘ +yRRR=t z^YAM k:x}Wxl 5>hѢ%K,[ qQ</&'u1*TTΏ!K41]~6LA60K%Z WVVV Wqq19 644 j\yC $8*1!YDXUCG&@t*VO6T 5]g Cwcх~,!~L74CW`mѭ oG.K332Vez%%%^_0U566"`c'NJ^:ܾ9SG/C-!X- P9]0i{ m^mK=Pز x ;a^KaMky:su!LA8)E..)F9~FaKཀ-]#[ 8 !\TBӁg 9kj}d0 @D`U>"^)-[ M-b@ރ^„CW4?sڿ9p8k^\Sŀxg%F\,_n-??!T꼅{B#:i%<$}skVb4 0u0I5Oy/rǧZV.oY""׏]M ڡ[@h Or(zPazث_>jd2&說*ӱ`BBԫ 8и;p; ȾYf,ྰE?z iTK+{ sN q"Xsz\ ۋqJqUUJ$]5:oÎթӊJKvxU6^└m#/^lP7n܈K^wfGp9H]RG\!R{\;]. @ݞ:TT`2jNW[ K+*Qªr:Tr54j+=M LeznQD ꕖT (Q,afDDB9H?b \NExCACVoK/ؿюU}:`%91Z>SX]]qa061cV]:[EfaJp!ɬVT1")syKSJ9?]%VL^01 Wt޿o?7С|{|"M~{kX|:(B1":ZAh5m7oZۙP}:T+>~{C_aWTC%Fj޽.q5'!0w*4I|WclфIO?=k;w߽BݣEkfbIo=3gђ(3gB6PSB{Il0s֬\ +yWEKNμY @uʀVsU ;>}w}_0?7/M s<^PWޮ;jkoI{tsϾ_i;?]1Hɝ?TK]?=?9c`{~[3Nt'\E!NE07?:g?Hwg&#s<c91n]$OfenxbgqwwWrqee;Z=nxW]e˯yn/9fU81DSd~{~{1Gm??M/c~r69w~w}l/~۞_;뼮:>UB7kA*%:wY ._á7ׯ__#D>*< ZV>PuB.宁7ĊzoF-ϫjO_߳;~ EWHKU?GJ_jI⑌H~y19߿w 3~yL;}CѺJwEc>tU (s68^!z\?VYYw^ّ#-֖hA[[[(?omEi*J*U MKkkK zGVf#6 Kq60bęӳ.v*TleKĤ3%%'%$'%$ģ0!1$&&&%'c5T< %$OOLmh $aK1ZEۉq ]Mf29>$, TPaZ7-Jj JKA&I^>O]HP2Su{=Z]zu'>q0ǤXT(13r8t,Ee3D *e\.|Gۺ Y0V8E9 w}fK$%wQɏqYE齯tp\p$$dBSDS&0rdG MAjm\@̊w8b7|]UWΥa-.oשl6ap:UUUl6ꢢk!`ƊV^xť%Ӟ?[j8@W$Iة1S1nɑ*]d6w8s |SP뫅% 88Z7RŏE8x T֛Gu> Ë9t .:HSE07䀈aB)B$o}PFo1:c( F;:|TB=7Pvؑ3w \1jnb--+}@H$vvtz%O<ddP4}dxرIq:QkpJJIq $re d5R{ӕQ.(!.))aZ2 wozXs&'?5)ajR"M1kD 6DnQY>e-_\<'V;_ .O9*v0](WB:t$!6>m:ר{FenН<o>{f^z9v"_V^^>ށ7^uw~[_qtܤ̕4ԕM\_a3YaP\ .+D0Fן)VWct/^Dp 6`ҸK ,';'---5%u \kZ*+gKqi1u)ç|7fB 9xb8M6<4PcIʦ8^zeOSuM_5ďE8uBYЛG5k'9_}?푯ߑͭG_~CvЁo:@Zh呏t @#呕C &-Pu y-K+}klD7P~ß}`7G>;DLA[}SgQOUo>#e![hT>#s7l'dee' /Ubοn4yrRr2Yq S&N[oMI.iw:%i n6{=0)9뮞LNm7zԄS>yZr\|RBrۦޕtf$N:=iSfLK>#a ࣦ݊OM4 /!qZ|iIw$'NJmjRoIN@mq>eRҭS<:ۦO8-qj3_t9n,)nzҔnN쏉HH4=!I{e p._O]дo**}U. 3. \QM…cdpI)$_sKGlWbDG̤PHďE\ u{ݦu={LJ<nNr59qKX\"n5gUշmoQqPYSNzEW` ÄC_L+sUw5e˖}c%֦۰qÖ̒r(9LCRQ ~Fш8MG è3Gu׬O%${y&8ӹvOЏ &ďExɴS W@)عŕ rտ{%c_9 OGzv/AniZ -+>YZٽa***~衇.V+w JKZkWͻrzg?ˬ'tUi/}Sϼ6fi'{s3cŊu VCѠʱl﮿{0 coۛu%nlHUy~7~n)r؉5% CciQ|&sk?;}/UjUؔXDQ*I;5ZJūr\r#HeecJ,9xٲWP\1fKtL wv97#= :sWFfMP7Wyԩf [nSO55?ۇ5A Džan&\YC|v5r۩m?FiŨ6x c^2m!~lUJJ#p@oͻ$qre6J4-S ۡޥ󼗲[Iv"զ.+\NۨYXKYo le3^¤}T;ßս:{>7Mضa[ _}YT{9ߌ60iq'{ ֿ_rr ~lK~M=Q͢f}cf5g?vY;oW6f=_|^,Żէ[צ=3w`c0cP1$>1d}_?&Os [_JޡzCU ~,`VUomcmܽo9=z)Jle?36ɸ`H1Q8l5'_w#j-{0$lǏ/ݎFs<3۪Uu<ά 2ToJc;zkӦy& uHjU9O*Bj.oq9)qg K6u8yㅪ2|GvgcJo)]:DT 3d3{ƍ>h[A>iӷAwִRI=~׾rJNl]~cʽ߿C~O?j#-Ok׏YjXwhq=vg3>6gҼ4kK{~ջ{v2t$Pwɞ}\Н>zcov`#H`àp]i/ YlYmϴj u>˴a䲼mcJ V\wvk3l=k6?.ɃMSȭcNkةڏ=1XeMe-݄bN6>H [չ6nXȏNLɼ5 Cc,bG%_ Ҵ}3;SϽRuM_'#3?N~LQň:DKM]dZe钾 `"~c}i"[_p5ٮ͏E"ďƌA܏)E#]`zZ6mKf_B2o2vb&8&:s0N }q敮юu[L2惈|ٲ5:U7؏׼ꪗ/)1:JO_?cC ӁOuLE?xٜ6a@3E~1НRRgn\RZZY]wu>VNZhUpCR#~l~,==p jQW(4?8{+J {**"ߏ=C>{f^~%v"_cϼ 3C'\cz啕6nCQ1PDUNJpz>5AGƌ Q ϾbUu]StN] SOXZBԣ^fܵngYJH?SiP)Kd:+!a's;f؏F.hB^ca }鮡_Cj+*p1~}ذ!=77nvm566Х1(tN ~l~o%TRO!T?(!OJ/|=4-exK DkkKkC~akl*IJ-8]ڝIe\Zܢ*[Q-}]yW\\V_ E7g cϙ>mڴĄxуy U^COWOa,ȒU$oL$K>-aFRz$=HNC(4Ӱ={JNH^'&HLNާ_F qjvt(9@MQE*KHj>jMm-A{=>o}}KS:<<ԞrZ@j4%v.6[<? E?n{f?Խ6ႇkY~'Nr?osۯE4d F_uUZrwFG>!AS0Vfn9b}0= 12.V87;boB oϯzKT~1~4%JbY+:%D5+w~]Ɲߣg$5eÆoÉi@Ꮙ]5Pgcwc ssBeT~wں.g "OOu[>8 n,'''==}ʕk֬Aْ*Xl`:4@F2lސď "׏QT\\ZV" M PY [*h9ZC/xbWmDqj>Xxw֍S /nt}%nkJJ22lnڱs]55NL4jnÁݱcً/3g3g- ӎai\~VI3ƿ&UzNI3Ocst;1S5WzRT%QFM@Ug{_3g ׭_tt} ކzO}.`>8s&͙j)Ι|SL|kqW>qX[1i򫓧Ι2Em{s:ҹ27D6^r#|{ݙ[8' Lqr]|K`u]ߘ9#H;|TVV-XOu[m%i+dtpaK5,M}|}ڿINVDO2HsCM S^25OBL2< Ug汫ng{zs[swhlUWVmڲnݺ|$u!L 31!やTkhB6=uŅ|N럹o@:U Ec44eN\IX{+\ ^haG q :y>q͌|^ZIU;UU*..˜ܺ5t]4$a5 #A}z>kHcí/_|Æ [nݾ};g,A  .=\&i_.f5kj\մ4Ɏ~Wm>>`}Js5܈~t" =| 0٥$`sS퀦jtd\nt,놬ZVt*lS]VԺ=8 zhfZtG BpPـ uiXTUWWT9k0Yz_BSVVx`gӦM8]:#𕯇 BnzpA}SmC& ,tr䂜NL#C*}} ו QME ZgYxSlNvKr O[SZVZUUi36% P0rNBQKQDTW_8=7nWWfNFgFۃUU28aLtQD^Cx=A}S)((.)),q (tbX˜?-W+gd{kW6oe @1E.`Y1 SЖ/((zv6ZdH]tJl>j(TaOEF!N)tWV3cp@mU`1 QR3QC'?EBB;ק1zk. 6ioʪk ȨN!T|OR~ Gf"Xjvz25YBrd1`B1|/'\#_!5ݣ.t:O==ռWKuЦnXmOk(br۶mŝ4$X]be̽ 8.7B@Wx(`41rTchDTCǍÃixM7AC.;Lإv׈F+i@ tÆ k֬ǀ4"aubu MVTTe 4NMMŻ Qr[A 0bFŵLmVfoU0YBsPe<*FO1v fG}Ӡ2PoCq mR@Iگ"9n444lݺp:@"\qfdd_^p0[dvxR"?A4@|/SuesR__%6\'j˜5xS@ K${s~R'5_aII?k0zqab g;vE3^=۠ tpG?J=ԐF<1H8.8%c fu4 ƴ[GKOۍh4Y Rnna;wzo mBD!艮$=ev OkC糽v g q]( É)"USW?7mJj{Z_B[1 ?^[d@ *ғ'Wq}I4 X )xkjG TTkV\⢶V Tpii).7oތW|L]vʨm! @P9=x+ِ!Cӹ~L#(lW=IcTDsNII $)++j< MP;۸qcJJNg% J؏ a{ХB. Bzە~2T|d@SXXzj\P|0[d!I#لeu ݣsk3t.t8|R`n \v܉,>,Y%(;؊f`=n"_0K2fLdiDzNg 9Xzm;aK.ci(ڲeŋD lᐥ- 7QO[KOOs ٟ"c 5_itwA$ }U@"UVT Lyfa avvvjjjyy.c[d!cL:11%x6c c4}5,zqɋ.d}mݺu͚56lpIIy VH2ՠsnW62MX$+^< I"3mTCax08R $Q~~>͛sssj`AO fAfddxDN?F`C޽ Nvq<@d@*((΢pl эBrZZƍOCЏE}#%o#ko=HЍZW`fcpz۶m=~HS}nѫHc:;xHKB{Ӧt^&0eܼAhVcv,A9&0&a~081~Y1=t"az!bFcVIq׮]|͑]TTiT@$PL?JJJRRRrrr0M?fEW<$"pΝ 6== .myb5,SS?컐4QQPP܈'7͑`x[.rNp050_ N/W~xű ڢB HE(1u E~((ā o+oB?&Ⴇ}/իW\r˖-[jUn.=3B:TUU"///Aaa K.]x˗,Y^7پ}&Ś5k0qz B]:F,T^\~m+؆ W)HbccTO&=A\*JKK11j 8F!AtƵ~?_kK_]D:OoӦx`û/V5w뼵 Z@mۆظq#^ц﫯\o.&dĬ6 9G󚾐z윥K.YdѢYYƟ+z Bqa2IOOץCӹb }áqf*({$\ c|vkk6oXM-8yy[U5wBI;Sr%i= ,FpܹV1UWWÃUlXf-Y8;vNE t'\Bg>LJvઝ-g[+RMS CZff&E-[:[6} B9abiy`A,(( j?&D%*T嘈)7!ruNG 'hGWjꚥKeg \qӥf26zܗ_xʕ+"< :?@DZ/]Tz72.q5Shf0ŭ%cu\MoiZZ%K7m\SlG hH38 fҏZVP:%e[p))o1D]3*gT=3O,Km!SS9%b+|:/A bgz-MQnMO5Dq,k׮[@]japT7H_?4}W'%&TMt䤤Clܸ1\G8\jC 8B5DlS'&}&VN׀Xuǎ]\dTrw[|[ ^:==IkD 7ocǙ6oF=@dWN#}"++t:3JlS<X\aH766 NS\-XYN Whtnڹ{ݕ9ٹ+V_dҥ^ܚtaPg]cwא1!NnMT1'sGӎF>—>C^/@x𢘃A$J<H\ʳsk|׳dF,ǎGlv|vNAA+ϕ R5k`WݨrJLPc AY07m۶-\GMLL#ªx`QaB<%'"BK#$tk䄋ッ?8BV+KSVLx%|16u؈FۊԵ=Œ3X$%%͚5{eammۊo{tzݻ7???++ _ ͟=~nj*ةJH Ĕ)qS iV3mVZWB}|7nܤ>{ٓVy2x[R j>gWq|Z08cJrr67w3裏d唔3x U6f.Zry˰_yuP ~Ln8ϟ0@RRr*Q'%'+%M X;0g,Z_|fs>,,S'&wl*~k 5^x|pϞFkMZ--\ o߾K ә%KIJL4JD̙Iw\H(ߝlνFF\:^qΚ9+5uMyyyBY 4* FwLr<x_WdcxYN8"uPtHƑVUU)x;i[a8rV\5~|^G}g!.VgSď ^<<]}"`OR HTtXͮ~`U ^϶{;px9Ѩ{Fen87.#cCgfø{OFfuCݻwgggiիW'Ӎ#L_xFE23(&p*=!&Q!L9e(SRRps9$a1dB^ґeўeG X>!=csƖpC}~KX.;#0cBb",9tcc#&?PSq/Վ68]/?{;ďE;z ]  \4 O|9+Xӣ1yͮ\ cEi{ҪV?f%Z`[999]^ 2xُ$a4 ‚1aRTTk/>=Yp2B>"Nڷ౅X?5EW5HH~f:w,ߗ΄+Vk:cG7_h ]?\߻o+ďY܏󩮯g^ڿ5w6ϢMT1".^-fl ܢC~Õt%Zeo|fלΧ氪i坴nZobn}Vom+WN/UVx{xT}H@l'q쵝n46n}M>>my6q}_c 㤵_i':N67#W$>3IȀ`L93 0+_F |>9hV?{HVJwweeJUzNJ'fQqI f?7S'ev̱ο+yZ]t j* l='jܿf$,})644N&'7|Z9nz,#64w_>?y敵,ím,ylOcoLؕYc+&J?.c'\i/;[OcGaha1,417\c^%KW _n'f[Ap *ҫ&oێ=n4M+7$D19bkȲdfQ[6䓁3NDUxvjQNFLm' Guϴ<fݻ& _H|%U!0yěGƖjautN >c;CջL<ƒ8}TĪ_鴥b4yKo q b1Uënj<:OS$a66hhS" IŐ^֤Oos<fb6N?:Tyˇ?]*~2+527e!-TW:CfXY;~c$VPiK.ipޢĦcF}5jP%8׹yN=nr4HĪ鴥b4yKo q b1Uënj<:OS$a66hhS ):\8sPOǡt:OS>w<c͕}N,t$o}7ުVnVQ3 򺯸FcZ;wS3aLOjw-c+gy ~\ҖĪ_c4yKo iq b1g>^5LRu7<gp w]OG"5K^9`VKۑcst\'Ti&7 ܠVGϔRy}"g7[_xwqwc&M<d'lRz\%<K+7L |L.;˔<6k45VֶRKZ~޹\Swn0]|LFdc:[cN2KSTFӋfX4DG=L1^Z dP7p%D-oNTyu7cL2_>mse1DcfSRqvz^YzL8/ܨcO K*yÒ+3<1'kTdV5ljGuffg&Sd,c:[cN2KSTFӋ<f~\Mmtgn&SN/7y2N?_VKĭ6%ɛ1Ik&hgc<f1߯KksOTKS|̍:6J$eI1|̮|̓ǜeKP>NewX4vLՎ\HL"a=] npy o3b*T;[߱O^XV,]Np/7ylaYtM[Uy Mww~C`ۼ%kylڦssg\rSOg+E"+cfkj9ujρ-FDzu\V^y}"SR<hС7(}=;&)5Km|~/2s #a*.)_OO~o;E=3x.ۿw[yM!#,]ʿ;MG"vV[[X4Fhs|rͫs"&t{M}8媮]g?{z9Yt5:6n?Cӧzf+ tX0o(<ēs|H488XQYysɦ͋ l).Ӏ ֮kz-[֒2z֕d$ٲgiVY_q=#ERٖҌ/YJ*z{gOwwO}C6-ojhlU,.)+,*<.s3mi7y_ںFe|^]/Ş݋N-۞=kg׮]%/[J6<gUUUv)vU]]]YY!)se>A 2l߾BY4!YȈijZgܑ̗<AYooo]]]YYY[[[~`v1>T}}} Z[[l+@Vc˛eٶy .<appP3 i3pc|K臇[ZZ./ y ?6[0IFY[[ij^: fΝ6ma[H$^YYY[[w^UXc(aL^B'+J0ATTUUXc ee\sg{ G"V}CCaQQFޝsa 0(EM'xs{yX,f/A6˖8Ʊ[y @|SaUW"z1eHf¼u/go[mzs-͋Um퟼pf{y eyE y lylSgd!bp|һiZ69vha (9|^PcM7YS教c]vd^5/?)W8n/dO!8QW_}( y ,4lrdWB]'R+:erx)O8ylrE)od̓sr^2`fs&;poMfg:̐^r&L*JIX:[ӓ5EO JV=>lFnf<M:) .G?=yR69H(}RɮML=RLR^y !S>J-i<fܼ{򘮳1:Tu$ج<lcO՜HcLdG|-BvlGfrǞհ̡H*J1SһUgCpX*Mɇs\=;r9+lV8 M/kF3ƧuumyB]΋񟺻{zUX,~C|?()O?808h pI*+-P<Z5u[vo<"Hն Z3x֒7fϧXIffm,dl:[u< ;[^^i1X,UUUU[[{!JJJR544gmxxضsD0/CCCv3MpX<`N$?Hd2) vԴs'9{ =IEJ@ww$՚IbH$eI$gyeigsssOOYvXc"  ý3ve]uAnii$/7gbbe[m(g=qi*dA`0888::*;Jw G253 3\9ؘz%ʗMQQʲLlbbB.Xv{,7W[UfF *}U$IlxxJ6Z}7ijeF s6\aͲeY޽n۶m4$ʵa.fL`3±r̰rF!dr5 $W|-u/nE<mTIsJ– cBY▼ʪ:n[JH3}f6;zkV ɟeN<!DupsiOOgAɂ_c[邑CL$9;6yȔ F ry``\*?{Xlckk*ؒFYʓd0Y*wƒ:${DigfW>Y*̹{Kg6ʬ ,54LWw0>3Tr,ܞp9'5e̳XVͲxbrDݰ۴UxXTcb1&;jUrO=*&IniLiP)nRFvҢPݹsg}}8p@";xu?PsHhI?HԢڢ;)\zƶdF"tQF}pFZ.*s4}Z[[Qڄcnq[\1gP sHg9ICCC^p M_cvb y Ylļ !rQ*'KXa1˫,tKH]vͮߕޔ,;m$SM-Mt;-uM/%'iݬLL^r(Jjfs@#ǐe-rޟ3tPl̲jC{YOc"Uy5oذaݺuɜ9!@<,01g*/V fNhl,≑[?*}2{ɂP!Fr1cǶmUre˖[Jܵ˂7& =#j~f5駷32ۑҍNݒ4eWԣF %MJP1$wIr#~~ *en1 S3]qVEF{Y+s.<n#={JKK7n޼}.s`f>;un>m7g&ǀ\ZcϒH276&͒:~H$U U#2[ᨳza]5qo(2;Ըy-ŕk[f͚&I&rKofFrnT2Uf9EEtUʨH$S?%dP}PۻY}䪨$l3@^*,̼?:=Gڊ "&*2:<t42[IbT\GGGaQ|rMP[;Ȃ08e9.Au/Id֮p1!>KFG}P$wO_WGwGsw[ݮm ]mm m;ڛv7WYnloƆֆ憶FݭqG,4JշJiټaƊ[6E41_RdSOē Uevyli'# 㣒Hrbb|xdu{WuEC}up:T5e*g&Vj)}wIuu5h9kp`h|l_2ݽdg6H6{1d1n\ooowwwMMMyyEʊʭBWTy.KS=Y)+/.UqұLvUTa#zm*J 6%ܪf_=RMDJi(DuuTȦ5TssK__ʍgś*Iv?޾N~{H<cckC~ pg pW^T,rp*YW*ɭU% LYki`U򗬼{ oJ?GI3 b 5OFQ.9"alt_R%nO<˾]/X3%eιM|UiyEo[~;:jJʊ7mX_^[⒒=i_c~z$=ǯ⊀ )/ٍTiWtɺU͆:\8 9m1";Zl'Z6a 5,OPRQJw'4W]uO?s?0688yf\%o]կF-t V𝁐`kyf@p-Yv0Bw_ ^ҊH<WOI$;[715^Wew sѩ,kRӓw2MvgJBK̗T%PPe8l867Y[K{:zyZ̷I0z% S$C=rZFޱ+5Ť2:Z68C8cϳsr=sw.Ɇ 6o+\꺌l<.1>̺Cw=*WC+B*{|-;yLrGH_K6 ޓw #K$\kJ:{K((+GcilLQ?#K]'Gb>jd9p@"Ӗʹ UMet6e&/H:8|K,P(Q\D2P*$1%Xl|||ƍ_B'K*ErP0\ tȇt\@^~@dP@ͰF($?^&{Tg7,Rj|PNRJԫCpn_9XXM;$3LuқsPLv`0Ofe6 p^85[i / /P8,ȓ m޶l)HJ9"; cF\$A4$wɫy tkCYnp+KsSk7gɆM 4o%_EQAkEx%%=]9yp~X~շŪ>X,~՚ϭ R2=yX#~У+B?[.g|d{"/ƾ*y5gQ:hW.>Y|>6<}<ľIS̕fE7}o╡/[#eG(=);pjZr?>f)uoxf+y,HOZAӟ/K*e=y+j `< f&cﻯU|FISQ=|U0Ѵ( hN5''9j<W)ofNߨtÝ:uZ3~tP?9}j/T=tjujsCR*cre/VP'ފ#X;ؙYk.Ex%ş/|^:7|r*{g3Ihnlr/~_^'L3CM"-}#pLʏcN(rH*2<fd\8E fn.NtE_1eFpZj$2 Q*\ y<K}("c_4X1y x|5wm U]yUiS{q,SE]8sh<k(] R.fMJqQ=8~rZs,<l ڻa?0f_1\^w)\Ἧ,yMr(#lkH?x7B+/ K5;=p=)ߺ52'}fg63鑌F##cبoɻCRe09)3=~~pO^w}^&r=LT{T |-bҕ)M#X4GbIaNV_F֮]{׆60N( ~A]P3}p~^=E0/ f|dn ~CI5ʚ #yy]ˡ^Wqj%"2T>j:yE! ]C^!u~GйXsa}ւwqqɕ~$#). Y; @|6t8[ }-``m%÷Ic xzzYPnn o 6%Vmy[7n oܱ4|{xm% 6ǞDX<%wwWqF'ɱK_xxC^%w.Z~yr\ԩu ʉHo /yiޭCyrBaNSޙ@_=;wGbDlDzgL$s{zzJT KvW̼㼔,H Kkl_"]۽6U ' $ՅJ,&/ɗ*1IHPRٔӲ $_,]Y4?򥁥A~8_jjG&ӑ,V^$/5KJ{HVwE W, ,.CK+< X* lաɫk/% <搯:f:Ղflٲ󙚿H$~ˆ|=C+?ls[ y Yr$>7_bپ:Z뚚kjZZ[ۤNVdAZvW#=KmSKMSv]P"%:Zw3$abed{l$UGL21Lcc}Muumu- jkMԪFUMu͵RҭAtyRWCIM3Hݶ]uc}0i~c~:.n*blhhؾ}۶V-u9)Mmj[U%SmQSuTVTTlwӣT#!͂JW63oQn۶JFeKjOM1Y689.Zv5<1O{ϩ*+VTTf4{ј=03 hl(Ehb"OFbG"%.r`褖e4ϷԲ4d2:*5*K_jS<&;9D6H8'ۤWt$E<d\桾w񘌚2GJLUv%c#17g-#8#ѸDp,վ#J&q')5܋ }\Y h}K>nJ:~K؞{zaޮ.m; nYm體6ZQA<%3vpKҥ<My(H␈B\rN䝘eZe#InC+'bⒶd<nT7UE&&LtTL1՝ G>[Q̝nfqHtUVoiN1h(r[zaZjgJ`Ӕ3M3ԜK.| 2,?Ǫ'TO,툆^-kʴ/E 6AMMuI#<ޛ\[Vzbnݞқ<*QVD <S9{fZTMft L쾗 g}O_ؘ_,IdՅFdy ;iRԊm75eV*K''ʍRs8եO2- ]H$رaϞ=c:y>|9 c@N%̚!62%J0)8u#YڼX~V,Vċ/811Q[[k.Մ19Fdy ȉ t O=L 3y̴G_XwwwMMMkklZ}  [email protected]$1Y%ݫB  c@.$a$IFv񁁁uɫ,9{3"9_ 'Onv_򋋋+**zzz|wy\w*cGss"$eEѡ!IbF+((v`4440V]]m[/HH}aE1dJv!Č-%7d\%Vʧ~<UZZ&јSop#ܦo,tu `Ak$e1uu|gV-zO>{Q2Tm=;O}5k'~~$nd[~ y 6oO^ooر'z۶ď6,zk׮#@+_;aaz{q:W˿d(;/o?z1xc{ޙ(g|yx_~6f<3ra<σvP-Gy7}+dohZZ_8z;Vy[qª<p){} Kt9Ӂ՚cgE<GQ>^+cc/JL+jLLW˿eZd *U~oѐJ۩w'^x ;R!ʉW&^8:u[1vMOĥƹсC}%ϼdFuN::d>'чNYf{;}-ԝ up苧Nx3IRWe>d<fQC!Js;+<mPtyssZcCCOܻj}vO `+<ěw_EщH{T=a’Ĥ㿒ɟ␓ X:y'MOIPr엲t^jz:L>oV|Л'N79T6ܺCO KSN 2y GSroVu2Q]RI_}OF I5H^8Xy 9 W .=<.Đ!-i'Z }[y]2jXA+m(QRݼ֧_O5tV咭%J9z>f.ILRM1=%YI뀥IzD3̰Al5%s0QMx&󘙒;H7ԙ< y f~E?Ǎ Bz32StA>qV;g\_)˓܇BG1C}NM}& {eL hb]_jV~G=qjQm<nw?g|; oNSywyA{R=UU' ~Ly'1ϻ;\v3wƹcӳ]rXO(y 6\C,ߞ7_02]np , 1>hjl?_ g?GMM?o[68mTx~6 cQVV/dٱ@}K7'~ʳaxxp<`Cɢo~`coo(Ky bX__޽+^Ч72Hjpp^@1y A$Ktsy ;s)< ?c< ?c< ?cTWR1 < ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?Ry| @n1y A1y A1y A1Gf(((r\1(((<FQEQEQG-ve/m[IENDB`
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Test/Debugging/VisualBasicBreakpointResolutionServiceTests.vb
' 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. Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Debugging Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.UnitTests.Debugging <[UseExportProvider]> Public Class VisualBasicBreakpointResolutionServiceTests Public Async Function TestSpanWithLengthAsync(markup As XElement, length As Integer) As Task Dim position As Integer? = Nothing Dim expectedSpan As TextSpan? = Nothing Dim source As String = Nothing MarkupTestFile.GetPositionAndSpan(markup.NormalizedValue, source, position, expectedSpan) Using workspace = TestWorkspace.CreateVisualBasic(source) Dim document = workspace.CurrentSolution.Projects.First.Documents.First Dim result As BreakpointResolutionResult = Await VisualBasicBreakpointResolutionService.GetBreakpointAsync(document, position.Value, length, CancellationToken.None) Assert.True(expectedSpan.Value = result.TextSpan, String.Format(vbCrLf & "Expected: {0} ""{1}""" & vbCrLf & "Actual: {2} ""{3}""", expectedSpan.Value, source.Substring(expectedSpan.Value.Start, expectedSpan.Value.Length), result.TextSpan, source.Substring(result.TextSpan.Start, result.TextSpan.Length))) End Using End Function <WorkItem(876520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876520")> <Fact> Public Async Function TestBreakpointSpansMultipleMethods() As Task ' Normal case: debugger passing BP spans "sub Goo() end sub" Await TestSpanWithLengthAsync(<text> class C [|$$sub Goo()|] end sub sub Bar() end sub end class</text>, 20) ' Rare case: debugger passing BP spans "sub Goo() end sub sub Bar() end sub" Await TestSpanWithLengthAsync(<text> class C $$sub Goo() end sub [|sub Bar()|] end sub end class</text>, 35) End Function End Class End Namespace
' 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. Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Debugging Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.UnitTests.Debugging <[UseExportProvider]> Public Class VisualBasicBreakpointResolutionServiceTests Public Async Function TestSpanWithLengthAsync(markup As XElement, length As Integer) As Task Dim position As Integer? = Nothing Dim expectedSpan As TextSpan? = Nothing Dim source As String = Nothing MarkupTestFile.GetPositionAndSpan(markup.NormalizedValue, source, position, expectedSpan) Using workspace = TestWorkspace.CreateVisualBasic(source) Dim document = workspace.CurrentSolution.Projects.First.Documents.First Dim result As BreakpointResolutionResult = Await VisualBasicBreakpointResolutionService.GetBreakpointAsync(document, position.Value, length, CancellationToken.None) Assert.True(expectedSpan.Value = result.TextSpan, String.Format(vbCrLf & "Expected: {0} ""{1}""" & vbCrLf & "Actual: {2} ""{3}""", expectedSpan.Value, source.Substring(expectedSpan.Value.Start, expectedSpan.Value.Length), result.TextSpan, source.Substring(result.TextSpan.Start, result.TextSpan.Length))) End Using End Function <WorkItem(876520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876520")> <Fact> Public Async Function TestBreakpointSpansMultipleMethods() As Task ' Normal case: debugger passing BP spans "sub Goo() end sub" Await TestSpanWithLengthAsync(<text> class C [|$$sub Goo()|] end sub sub Bar() end sub end class</text>, 20) ' Rare case: debugger passing BP spans "sub Goo() end sub sub Bar() end sub" Await TestSpanWithLengthAsync(<text> class C $$sub Goo() end sub [|sub Bar()|] end sub end class</text>, 35) End Function End Class End Namespace
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/VisualBasic/Impl/Options/Formatting/CodeStylePage.vb
' 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. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options.Formatting <Guid(Guids.VisualBasicOptionPageCodeStyleIdString)> Friend Class CodeStylePage Inherits AbstractOptionPage Protected Overrides Function CreateOptionPage(serviceProvider As IServiceProvider, optionStore As OptionStore) As AbstractOptionPageControl Return New GridOptionPreviewControl(serviceProvider, optionStore, Function(o, s) New StyleViewModel(o, s), GetEditorConfigOptions(), LanguageNames.VisualBasic) End Function Private Shared Function GetEditorConfigOptions() As ImmutableArray(Of (String, ImmutableArray(Of IOption))) Dim builder = ArrayBuilder(Of (String, ImmutableArray(Of IOption))).GetInstance() builder.AddRange(GridOptionPreviewControl.GetLanguageAgnosticEditorConfigOptions()) builder.Add((BasicVSResources.VB_Coding_Conventions, VisualBasicCodeStyleOptions.AllOptions.As(Of IOption))) Return builder.ToImmutableAndFree() End Function Friend Structure TestAccessor Friend Shared Function GetEditorConfigOptions() As ImmutableArray(Of (String, ImmutableArray(Of IOption))) Return CodeStylePage.GetEditorConfigOptions() End Function End Structure End Class End Namespace
' 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. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options.Formatting <Guid(Guids.VisualBasicOptionPageCodeStyleIdString)> Friend Class CodeStylePage Inherits AbstractOptionPage Protected Overrides Function CreateOptionPage(serviceProvider As IServiceProvider, optionStore As OptionStore) As AbstractOptionPageControl Return New GridOptionPreviewControl(serviceProvider, optionStore, Function(o, s) New StyleViewModel(o, s), GetEditorConfigOptions(), LanguageNames.VisualBasic) End Function Private Shared Function GetEditorConfigOptions() As ImmutableArray(Of (String, ImmutableArray(Of IOption))) Dim builder = ArrayBuilder(Of (String, ImmutableArray(Of IOption))).GetInstance() builder.AddRange(GridOptionPreviewControl.GetLanguageAgnosticEditorConfigOptions()) builder.Add((BasicVSResources.VB_Coding_Conventions, VisualBasicCodeStyleOptions.AllOptions.As(Of IOption))) Return builder.ToImmutableAndFree() End Function Friend Structure TestAccessor Friend Shared Function GetEditorConfigOptions() As ImmutableArray(Of (String, ImmutableArray(Of IOption))) Return CodeStylePage.GetEditorConfigOptions() End Function End Structure End Class End Namespace
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.cs
// 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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractSymbolCompletionProvider<TSyntaxContext> : LSPCompletionProvider where TSyntaxContext : SyntaxContext { // PERF: Many CompletionProviders derive AbstractSymbolCompletionProvider and therefore // compute identical contexts. This actually shows up on the 2-core typing test. // Cache the most recent document/position/computed SyntaxContext to reduce repeat computation. private static readonly ConditionalWeakTable<Document, Tuple<int, AsyncLazy<TSyntaxContext>>> s_cachedDocuments = new(); private bool? _isTargetTypeCompletionFilterExperimentEnabled = null; protected AbstractSymbolCompletionProvider() { } protected abstract Task<ImmutableArray<(ISymbol symbol, bool preselect)>> GetSymbolsAsync(CompletionContext? completionContext, TSyntaxContext syntaxContext, int position, OptionSet options, CancellationToken cancellationToken); protected abstract (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(ISymbol symbol, TSyntaxContext context); protected virtual CompletionItemRules GetCompletionItemRules(ImmutableArray<(ISymbol symbol, bool preselect)> symbols) => CompletionItemRules.Default; protected bool IsTargetTypeCompletionFilterExperimentEnabled(Workspace workspace) { if (!_isTargetTypeCompletionFilterExperimentEnabled.HasValue) { var experimentationService = workspace.Services.GetRequiredService<IExperimentationService>(); _isTargetTypeCompletionFilterExperimentEnabled = experimentationService.IsExperimentEnabled(WellKnownExperimentNames.TargetTypedCompletionFilter); } return _isTargetTypeCompletionFilterExperimentEnabled == true; } /// <param name="typeConvertibilityCache">A cache to use for repeated lookups. This should be created with <see cref="SymbolEqualityComparer.Default"/> /// because we ignore nullability.</param> private static bool ShouldIncludeInTargetTypedCompletionList( ISymbol symbol, ImmutableArray<ITypeSymbol> inferredTypes, SemanticModel semanticModel, int position, Dictionary<ITypeSymbol, bool> typeConvertibilityCache) { // When searching for identifiers of type C, exclude the symbol for the `C` type itself. if (symbol.Kind == SymbolKind.NamedType) { return false; } // Avoid offering members of object since they too commonly show up and are infrequently desired. if (symbol.ContainingType?.SpecialType == SpecialType.System_Object) { return false; } // Don't offer locals on the right-hand-side of their declaration: `int x = x` if (symbol.Kind == SymbolKind.Local) { var local = (ILocalSymbol)symbol; var declarationSyntax = symbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).SingleOrDefault(); if (declarationSyntax != null && position < declarationSyntax.FullSpan.End) { return false; } } var type = symbol.GetMemberType() ?? symbol.GetSymbolType(); if (type == null) { return false; } if (typeConvertibilityCache.TryGetValue(type, out var isConvertible)) { return isConvertible; } typeConvertibilityCache[type] = CompletionUtilities.IsTypeImplicitlyConvertible(semanticModel.Compilation, type, inferredTypes); return typeConvertibilityCache[type]; } /// <summary> /// Given a list of symbols, and a mapping from each symbol to its original SemanticModel, /// creates the list of completion items for them. /// </summary> private ImmutableArray<CompletionItem> CreateItems( CompletionContext completionContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, Func<(ISymbol symbol, bool preselect), TSyntaxContext> contextLookup, Dictionary<ISymbol, List<ProjectId>>? invalidProjectMap, List<ProjectId>? totalProjects, TelemetryCounter telemetryCounter) { // We might get symbol w/o name but CanBeReferencedByName is still set to true, // need to filter them out. // https://github.com/dotnet/roslyn/issues/47690 var symbolGroups = from symbol in symbols let texts = GetDisplayAndSuffixAndInsertionText(symbol.symbol, contextLookup(symbol)) where !string.IsNullOrWhiteSpace(texts.displayText) group symbol by texts into g select g; var itemListBuilder = ImmutableArray.CreateBuilder<CompletionItem>(); var typeConvertibilityCache = new Dictionary<ITypeSymbol, bool>(SymbolEqualityComparer.Default); foreach (var symbolGroup in symbolGroups) { var includeItemInTargetTypedCompletion = false; var arbitraryFirstContext = contextLookup(symbolGroup.First()); var symbolList = symbolGroup.ToImmutableArray(); if (IsTargetTypeCompletionFilterExperimentEnabled(arbitraryFirstContext.Workspace)) { var tick = Environment.TickCount; includeItemInTargetTypedCompletion = TryFindFirstSymbolMatchesTargetTypes(contextLookup, symbolList, typeConvertibilityCache, out var index); if (includeItemInTargetTypedCompletion && index > 0) { // This would ensure a symbol matches target types to be used for description if there's any, // assuming the default implementation of GetDescriptionWorkerAsync is used. var firstMatch = symbolList[index]; symbolList = symbolList.RemoveAt(index); symbolList = symbolList.Insert(0, firstMatch); } telemetryCounter.AddTick(Environment.TickCount - tick); } var item = CreateItem( completionContext, symbolGroup.Key.displayText, symbolGroup.Key.suffix, symbolGroup.Key.insertionText, symbolList, arbitraryFirstContext, invalidProjectMap, totalProjects); if (includeItemInTargetTypedCompletion) { item = item.AddTag(WellKnownTags.TargetTypeMatch); } itemListBuilder.Add(item); } return itemListBuilder.ToImmutable(); } protected static bool TryFindFirstSymbolMatchesTargetTypes( Func<(ISymbol symbol, bool preselect), TSyntaxContext> contextLookup, ImmutableArray<(ISymbol symbol, bool preselect)> symbolList, Dictionary<ITypeSymbol, bool> typeConvertibilityCache, out int index) { for (index = 0; index < symbolList.Length; ++index) { var symbol = symbolList[index]; var syntaxContext = contextLookup(symbol); if (ShouldIncludeInTargetTypedCompletionList(symbol.symbol, syntaxContext.InferredTypes, syntaxContext.SemanticModel, syntaxContext.Position, typeConvertibilityCache)) break; } return index < symbolList.Length; } /// <summary> /// Given a Symbol, creates the completion item for it. /// </summary> private CompletionItem CreateItem( CompletionContext completionContext, string displayText, string displayTextSuffix, string insertionText, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, TSyntaxContext context, Dictionary<ISymbol, List<ProjectId>>? invalidProjectMap, List<ProjectId>? totalProjects) { Contract.ThrowIfNull(symbols); SupportedPlatformData? supportedPlatformData = null; if (invalidProjectMap != null) { List<ProjectId>? invalidProjects = null; foreach (var symbol in symbols) { if (invalidProjectMap.TryGetValue(symbol.symbol, out invalidProjects)) break; } if (invalidProjects != null) supportedPlatformData = new SupportedPlatformData(invalidProjects, totalProjects, context.Workspace); } return CreateItem( completionContext, displayText, displayTextSuffix, insertionText, symbols, context, supportedPlatformData); } protected virtual CompletionItem CreateItem( CompletionContext completionContext, string displayText, string displayTextSuffix, string insertionText, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, TSyntaxContext context, SupportedPlatformData? supportedPlatformData) { var preselect = symbols.Any(t => t.preselect); return SymbolCompletionItem.CreateWithSymbolId( displayText: displayText, displayTextSuffix: displayTextSuffix, insertionText: insertionText, filterText: GetFilterText(symbols[0].symbol, displayText, context), contextPosition: context.Position, symbols: symbols.SelectAsArray(t => t.symbol), supportedPlatforms: supportedPlatformData, rules: GetCompletionItemRules(symbols) .WithMatchPriority(preselect ? MatchPriority.Preselect : MatchPriority.Default) .WithSelectionBehavior(context.IsRightSideOfNumericType ? CompletionItemSelectionBehavior.SoftSelection : CompletionItemSelectionBehavior.Default)); } protected virtual string GetFilterText(ISymbol symbol, string displayText, TSyntaxContext context) { return (displayText == symbol.Name) || (displayText.Length > 0 && displayText[0] == '@') || (context.IsAttributeNameContext && symbol.IsAttribute()) ? displayText : symbol.Name; } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); public override async Task ProvideCompletionsAsync(CompletionContext completionContext) { try { var document = completionContext.Document; var position = completionContext.Position; var options = completionContext.Options; var cancellationToken = completionContext.CancellationToken; // If we were triggered by typing a character, then do a semantic check to make sure // we're still applicable. If not, then return immediately. if (completionContext.Trigger.Kind == CompletionTriggerKind.Insertion) { var isSemanticTriggerCharacter = await IsSemanticTriggerCharacterAsync(document, position - 1, cancellationToken).ConfigureAwait(false); if (!isSemanticTriggerCharacter) { return; } } completionContext.IsExclusive = IsExclusive(); using (Logger.LogBlock(FunctionId.Completion_SymbolCompletionProvider_GetItemsWorker, cancellationToken)) using (var telemetryCounter = new TelemetryCounter(ShouldCollectTelemetryForTargetTypeCompletion && IsTargetTypeCompletionFilterExperimentEnabled(document.Project.Solution.Workspace))) { var syntaxContext = await GetOrCreateContextAsync(document, position, cancellationToken).ConfigureAwait(false); var regularItems = await GetItemsAsync(completionContext, syntaxContext, document, position, options, telemetryCounter, cancellationToken).ConfigureAwait(false); completionContext.AddItems(regularItems); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private async Task<ImmutableArray<CompletionItem>> GetItemsAsync( CompletionContext completionContext, TSyntaxContext syntaxContext, Document document, int position, OptionSet options, TelemetryCounter telemetryCounter, CancellationToken cancellationToken) { var relatedDocumentIds = document.GetLinkedDocumentIds(); options = CompletionUtilities.GetUpdatedRecommendationOptions(options, document.Project.Language); if (relatedDocumentIds.IsEmpty) { var itemsForCurrentDocument = await GetSymbolsAsync(completionContext, syntaxContext, position, options, cancellationToken).ConfigureAwait(false); return CreateItems(completionContext, itemsForCurrentDocument, _ => syntaxContext, invalidProjectMap: null, totalProjects: null, telemetryCounter); } var contextAndSymbolLists = await GetPerContextSymbolsAsync(completionContext, document, position, options, new[] { document.Id }.Concat(relatedDocumentIds), cancellationToken).ConfigureAwait(false); var symbolToContextMap = UnionSymbols(contextAndSymbolLists); var missingSymbolsMap = FindSymbolsMissingInLinkedContexts(symbolToContextMap, contextAndSymbolLists); var totalProjects = contextAndSymbolLists.Select(t => t.documentId.ProjectId).ToList(); return CreateItems( completionContext, symbolToContextMap.Keys.ToImmutableArray(), symbol => symbolToContextMap[symbol], missingSymbolsMap, totalProjects, telemetryCounter); } protected virtual bool IsExclusive() => false; protected virtual Task<bool> IsSemanticTriggerCharacterAsync(Document document, int characterPosition, CancellationToken cancellationToken) => SpecializedTasks.True; private static Dictionary<(ISymbol symbol, bool preselect), TSyntaxContext> UnionSymbols( ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)> linkedContextSymbolLists) { // To correctly map symbols back to their SyntaxContext, we do care about assembly identity. var result = new Dictionary<(ISymbol symbol, bool preselect), TSyntaxContext>(CompletionLinkedFilesSymbolEquivalenceComparer.Instance); // We don't care about assembly identity when creating the union. foreach (var (documentId, syntaxContext, symbols) in linkedContextSymbolLists) { // We need to use the SemanticModel any particular symbol came from in order to generate its description correctly. // Therefore, when we add a symbol to set of union symbols, add a mapping from it to its SyntaxContext. foreach (var symbol in symbols.GroupBy(s => new { s.symbol.Name, s.symbol.Kind }).Select(g => g.First())) { if (!result.ContainsKey(symbol)) result.Add(symbol, syntaxContext); } } return result; } private async Task<ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)>> GetPerContextSymbolsAsync( CompletionContext completionContext, Document document, int position, OptionSet options, IEnumerable<DocumentId> relatedDocuments, CancellationToken cancellationToken) { var solution = document.Project.Solution; using var _1 = ArrayBuilder<Task<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)>>.GetInstance(out var tasks); using var _2 = ArrayBuilder<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)>.GetInstance(out var perContextSymbols); foreach (var relatedDocumentId in relatedDocuments) { tasks.Add(Task.Run(async () => { var relatedDocument = solution.GetRequiredDocument(relatedDocumentId); var syntaxContext = await GetOrCreateContextAsync(relatedDocument, position, cancellationToken).ConfigureAwait(false); var symbols = await TryGetSymbolsForContextAsync(completionContext, syntaxContext, options, cancellationToken).ConfigureAwait(false); return (relatedDocument.Id, syntaxContext, symbols); }, cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); foreach (var task in tasks) { var (relatedDocumentId, syntaxContext, symbols) = await task.ConfigureAwait(false); if (!symbols.IsDefault) perContextSymbols.Add((relatedDocumentId, syntaxContext, symbols)); } return perContextSymbols.ToImmutable(); } /// <summary> /// If current context is in active region, returns available symbols. Otherwise, returns null. /// </summary> protected async Task<ImmutableArray<(ISymbol symbol, bool preselect)>> TryGetSymbolsForContextAsync( CompletionContext? completionContext, TSyntaxContext syntaxContext, OptionSet options, CancellationToken cancellationToken) { var syntaxFacts = syntaxContext.GetLanguageService<ISyntaxFactsService>(); return syntaxFacts.IsInInactiveRegion(syntaxContext.SyntaxTree, syntaxContext.Position, cancellationToken) ? default : await GetSymbolsAsync(completionContext, syntaxContext, syntaxContext.Position, options, cancellationToken).ConfigureAwait(false); } protected static async Task<TSyntaxContext> CreateContextAsync(Document document, int position, CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); var service = document.GetRequiredLanguageService<ISyntaxContextService>(); return (TSyntaxContext)service.CreateContext(workspace, semanticModel, position, cancellationToken); } private static Task<TSyntaxContext> GetOrCreateContextAsync(Document document, int position, CancellationToken cancellationToken) { lock (s_cachedDocuments) { var (cachedPosition, cachedLazyContext) = s_cachedDocuments.GetValue( document, d => Tuple.Create(position, new AsyncLazy<TSyntaxContext>(ct => CreateContextAsync(d, position, ct), cacheResult: true))); if (cachedPosition == position) { return cachedLazyContext.GetValueAsync(cancellationToken); } var lazyContext = new AsyncLazy<TSyntaxContext>(ct => CreateContextAsync(document, position, ct), cacheResult: true); s_cachedDocuments.Remove(document); s_cachedDocuments.Add(document, Tuple.Create(position, lazyContext)); return lazyContext.GetValueAsync(cancellationToken); } } /// <summary> /// Given a list of symbols, determine which are not recommended at the same position in linked documents. /// </summary> /// <param name="symbolToContext">The symbols recommended in the active context.</param> /// <param name="linkedContextSymbolLists">The symbols recommended in linked documents</param> /// <returns>The list of projects each recommended symbol did NOT appear in.</returns> private static Dictionary<ISymbol, List<ProjectId>> FindSymbolsMissingInLinkedContexts( Dictionary<(ISymbol symbol, bool preselect), TSyntaxContext> symbolToContext, ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)> linkedContextSymbolLists) { var missingSymbols = new Dictionary<ISymbol, List<ProjectId>>(LinkedFilesSymbolEquivalenceComparer.Instance); foreach (var (documentId, syntaxContext, symbols) in linkedContextSymbolLists) { var symbolsMissingInLinkedContext = symbolToContext.Keys.Except(symbols, CompletionLinkedFilesSymbolEquivalenceComparer.Instance); foreach (var (symbol, _) in symbolsMissingInLinkedContext) missingSymbols.GetOrAdd(symbol, m => new List<ProjectId>()).Add(documentId.ProjectId); } return missingSymbols; } public sealed override Task<TextChange?> GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) => Task.FromResult<TextChange?>(new TextChange(selectedItem.Span, GetInsertionText(selectedItem, ch))); private string GetInsertionText(CompletionItem item, char? ch) { return ch == null ? SymbolCompletionItem.GetInsertionText(item) : GetInsertionText(item, ch.Value); } /// <summary> /// Override this if you want to provide customized insertion based on the character typed. /// </summary> protected virtual string GetInsertionText(CompletionItem item, char ch) => SymbolCompletionItem.GetInsertionText(item); // This is used to decide which provider we'd collect target type completion telemetry from. protected virtual bool ShouldCollectTelemetryForTargetTypeCompletion => false; private class TelemetryCounter : IDisposable { private readonly bool _shouldReport; private int _tick; public TelemetryCounter(bool shouldReport) => _shouldReport = shouldReport; public void AddTick(int tick) => _tick += tick; public void Dispose() { if (_shouldReport) { CompletionProvidersLogger.LogTargetTypeCompletionTicksDataPoint(_tick); } } } } }
// 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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractSymbolCompletionProvider<TSyntaxContext> : LSPCompletionProvider where TSyntaxContext : SyntaxContext { // PERF: Many CompletionProviders derive AbstractSymbolCompletionProvider and therefore // compute identical contexts. This actually shows up on the 2-core typing test. // Cache the most recent document/position/computed SyntaxContext to reduce repeat computation. private static readonly ConditionalWeakTable<Document, Tuple<int, AsyncLazy<TSyntaxContext>>> s_cachedDocuments = new(); private bool? _isTargetTypeCompletionFilterExperimentEnabled = null; protected AbstractSymbolCompletionProvider() { } protected abstract Task<ImmutableArray<(ISymbol symbol, bool preselect)>> GetSymbolsAsync(CompletionContext? completionContext, TSyntaxContext syntaxContext, int position, OptionSet options, CancellationToken cancellationToken); protected abstract (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(ISymbol symbol, TSyntaxContext context); protected virtual CompletionItemRules GetCompletionItemRules(ImmutableArray<(ISymbol symbol, bool preselect)> symbols) => CompletionItemRules.Default; protected bool IsTargetTypeCompletionFilterExperimentEnabled(Workspace workspace) { if (!_isTargetTypeCompletionFilterExperimentEnabled.HasValue) { var experimentationService = workspace.Services.GetRequiredService<IExperimentationService>(); _isTargetTypeCompletionFilterExperimentEnabled = experimentationService.IsExperimentEnabled(WellKnownExperimentNames.TargetTypedCompletionFilter); } return _isTargetTypeCompletionFilterExperimentEnabled == true; } /// <param name="typeConvertibilityCache">A cache to use for repeated lookups. This should be created with <see cref="SymbolEqualityComparer.Default"/> /// because we ignore nullability.</param> private static bool ShouldIncludeInTargetTypedCompletionList( ISymbol symbol, ImmutableArray<ITypeSymbol> inferredTypes, SemanticModel semanticModel, int position, Dictionary<ITypeSymbol, bool> typeConvertibilityCache) { // When searching for identifiers of type C, exclude the symbol for the `C` type itself. if (symbol.Kind == SymbolKind.NamedType) { return false; } // Avoid offering members of object since they too commonly show up and are infrequently desired. if (symbol.ContainingType?.SpecialType == SpecialType.System_Object) { return false; } // Don't offer locals on the right-hand-side of their declaration: `int x = x` if (symbol.Kind == SymbolKind.Local) { var local = (ILocalSymbol)symbol; var declarationSyntax = symbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).SingleOrDefault(); if (declarationSyntax != null && position < declarationSyntax.FullSpan.End) { return false; } } var type = symbol.GetMemberType() ?? symbol.GetSymbolType(); if (type == null) { return false; } if (typeConvertibilityCache.TryGetValue(type, out var isConvertible)) { return isConvertible; } typeConvertibilityCache[type] = CompletionUtilities.IsTypeImplicitlyConvertible(semanticModel.Compilation, type, inferredTypes); return typeConvertibilityCache[type]; } /// <summary> /// Given a list of symbols, and a mapping from each symbol to its original SemanticModel, /// creates the list of completion items for them. /// </summary> private ImmutableArray<CompletionItem> CreateItems( CompletionContext completionContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, Func<(ISymbol symbol, bool preselect), TSyntaxContext> contextLookup, Dictionary<ISymbol, List<ProjectId>>? invalidProjectMap, List<ProjectId>? totalProjects, TelemetryCounter telemetryCounter) { // We might get symbol w/o name but CanBeReferencedByName is still set to true, // need to filter them out. // https://github.com/dotnet/roslyn/issues/47690 var symbolGroups = from symbol in symbols let texts = GetDisplayAndSuffixAndInsertionText(symbol.symbol, contextLookup(symbol)) where !string.IsNullOrWhiteSpace(texts.displayText) group symbol by texts into g select g; var itemListBuilder = ImmutableArray.CreateBuilder<CompletionItem>(); var typeConvertibilityCache = new Dictionary<ITypeSymbol, bool>(SymbolEqualityComparer.Default); foreach (var symbolGroup in symbolGroups) { var includeItemInTargetTypedCompletion = false; var arbitraryFirstContext = contextLookup(symbolGroup.First()); var symbolList = symbolGroup.ToImmutableArray(); if (IsTargetTypeCompletionFilterExperimentEnabled(arbitraryFirstContext.Workspace)) { var tick = Environment.TickCount; includeItemInTargetTypedCompletion = TryFindFirstSymbolMatchesTargetTypes(contextLookup, symbolList, typeConvertibilityCache, out var index); if (includeItemInTargetTypedCompletion && index > 0) { // This would ensure a symbol matches target types to be used for description if there's any, // assuming the default implementation of GetDescriptionWorkerAsync is used. var firstMatch = symbolList[index]; symbolList = symbolList.RemoveAt(index); symbolList = symbolList.Insert(0, firstMatch); } telemetryCounter.AddTick(Environment.TickCount - tick); } var item = CreateItem( completionContext, symbolGroup.Key.displayText, symbolGroup.Key.suffix, symbolGroup.Key.insertionText, symbolList, arbitraryFirstContext, invalidProjectMap, totalProjects); if (includeItemInTargetTypedCompletion) { item = item.AddTag(WellKnownTags.TargetTypeMatch); } itemListBuilder.Add(item); } return itemListBuilder.ToImmutable(); } protected static bool TryFindFirstSymbolMatchesTargetTypes( Func<(ISymbol symbol, bool preselect), TSyntaxContext> contextLookup, ImmutableArray<(ISymbol symbol, bool preselect)> symbolList, Dictionary<ITypeSymbol, bool> typeConvertibilityCache, out int index) { for (index = 0; index < symbolList.Length; ++index) { var symbol = symbolList[index]; var syntaxContext = contextLookup(symbol); if (ShouldIncludeInTargetTypedCompletionList(symbol.symbol, syntaxContext.InferredTypes, syntaxContext.SemanticModel, syntaxContext.Position, typeConvertibilityCache)) break; } return index < symbolList.Length; } /// <summary> /// Given a Symbol, creates the completion item for it. /// </summary> private CompletionItem CreateItem( CompletionContext completionContext, string displayText, string displayTextSuffix, string insertionText, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, TSyntaxContext context, Dictionary<ISymbol, List<ProjectId>>? invalidProjectMap, List<ProjectId>? totalProjects) { Contract.ThrowIfNull(symbols); SupportedPlatformData? supportedPlatformData = null; if (invalidProjectMap != null) { List<ProjectId>? invalidProjects = null; foreach (var symbol in symbols) { if (invalidProjectMap.TryGetValue(symbol.symbol, out invalidProjects)) break; } if (invalidProjects != null) supportedPlatformData = new SupportedPlatformData(invalidProjects, totalProjects, context.Workspace); } return CreateItem( completionContext, displayText, displayTextSuffix, insertionText, symbols, context, supportedPlatformData); } protected virtual CompletionItem CreateItem( CompletionContext completionContext, string displayText, string displayTextSuffix, string insertionText, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, TSyntaxContext context, SupportedPlatformData? supportedPlatformData) { var preselect = symbols.Any(t => t.preselect); return SymbolCompletionItem.CreateWithSymbolId( displayText: displayText, displayTextSuffix: displayTextSuffix, insertionText: insertionText, filterText: GetFilterText(symbols[0].symbol, displayText, context), contextPosition: context.Position, symbols: symbols.SelectAsArray(t => t.symbol), supportedPlatforms: supportedPlatformData, rules: GetCompletionItemRules(symbols) .WithMatchPriority(preselect ? MatchPriority.Preselect : MatchPriority.Default) .WithSelectionBehavior(context.IsRightSideOfNumericType ? CompletionItemSelectionBehavior.SoftSelection : CompletionItemSelectionBehavior.Default)); } protected virtual string GetFilterText(ISymbol symbol, string displayText, TSyntaxContext context) { return (displayText == symbol.Name) || (displayText.Length > 0 && displayText[0] == '@') || (context.IsAttributeNameContext && symbol.IsAttribute()) ? displayText : symbol.Name; } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); public override async Task ProvideCompletionsAsync(CompletionContext completionContext) { try { var document = completionContext.Document; var position = completionContext.Position; var options = completionContext.Options; var cancellationToken = completionContext.CancellationToken; // If we were triggered by typing a character, then do a semantic check to make sure // we're still applicable. If not, then return immediately. if (completionContext.Trigger.Kind == CompletionTriggerKind.Insertion) { var isSemanticTriggerCharacter = await IsSemanticTriggerCharacterAsync(document, position - 1, cancellationToken).ConfigureAwait(false); if (!isSemanticTriggerCharacter) { return; } } completionContext.IsExclusive = IsExclusive(); using (Logger.LogBlock(FunctionId.Completion_SymbolCompletionProvider_GetItemsWorker, cancellationToken)) using (var telemetryCounter = new TelemetryCounter(ShouldCollectTelemetryForTargetTypeCompletion && IsTargetTypeCompletionFilterExperimentEnabled(document.Project.Solution.Workspace))) { var syntaxContext = await GetOrCreateContextAsync(document, position, cancellationToken).ConfigureAwait(false); var regularItems = await GetItemsAsync(completionContext, syntaxContext, document, position, options, telemetryCounter, cancellationToken).ConfigureAwait(false); completionContext.AddItems(regularItems); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private async Task<ImmutableArray<CompletionItem>> GetItemsAsync( CompletionContext completionContext, TSyntaxContext syntaxContext, Document document, int position, OptionSet options, TelemetryCounter telemetryCounter, CancellationToken cancellationToken) { var relatedDocumentIds = document.GetLinkedDocumentIds(); options = CompletionUtilities.GetUpdatedRecommendationOptions(options, document.Project.Language); if (relatedDocumentIds.IsEmpty) { var itemsForCurrentDocument = await GetSymbolsAsync(completionContext, syntaxContext, position, options, cancellationToken).ConfigureAwait(false); return CreateItems(completionContext, itemsForCurrentDocument, _ => syntaxContext, invalidProjectMap: null, totalProjects: null, telemetryCounter); } var contextAndSymbolLists = await GetPerContextSymbolsAsync(completionContext, document, position, options, new[] { document.Id }.Concat(relatedDocumentIds), cancellationToken).ConfigureAwait(false); var symbolToContextMap = UnionSymbols(contextAndSymbolLists); var missingSymbolsMap = FindSymbolsMissingInLinkedContexts(symbolToContextMap, contextAndSymbolLists); var totalProjects = contextAndSymbolLists.Select(t => t.documentId.ProjectId).ToList(); return CreateItems( completionContext, symbolToContextMap.Keys.ToImmutableArray(), symbol => symbolToContextMap[symbol], missingSymbolsMap, totalProjects, telemetryCounter); } protected virtual bool IsExclusive() => false; protected virtual Task<bool> IsSemanticTriggerCharacterAsync(Document document, int characterPosition, CancellationToken cancellationToken) => SpecializedTasks.True; private static Dictionary<(ISymbol symbol, bool preselect), TSyntaxContext> UnionSymbols( ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)> linkedContextSymbolLists) { // To correctly map symbols back to their SyntaxContext, we do care about assembly identity. var result = new Dictionary<(ISymbol symbol, bool preselect), TSyntaxContext>(CompletionLinkedFilesSymbolEquivalenceComparer.Instance); // We don't care about assembly identity when creating the union. foreach (var (documentId, syntaxContext, symbols) in linkedContextSymbolLists) { // We need to use the SemanticModel any particular symbol came from in order to generate its description correctly. // Therefore, when we add a symbol to set of union symbols, add a mapping from it to its SyntaxContext. foreach (var symbol in symbols.GroupBy(s => new { s.symbol.Name, s.symbol.Kind }).Select(g => g.First())) { if (!result.ContainsKey(symbol)) result.Add(symbol, syntaxContext); } } return result; } private async Task<ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)>> GetPerContextSymbolsAsync( CompletionContext completionContext, Document document, int position, OptionSet options, IEnumerable<DocumentId> relatedDocuments, CancellationToken cancellationToken) { var solution = document.Project.Solution; using var _1 = ArrayBuilder<Task<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)>>.GetInstance(out var tasks); using var _2 = ArrayBuilder<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)>.GetInstance(out var perContextSymbols); foreach (var relatedDocumentId in relatedDocuments) { tasks.Add(Task.Run(async () => { var relatedDocument = solution.GetRequiredDocument(relatedDocumentId); var syntaxContext = await GetOrCreateContextAsync(relatedDocument, position, cancellationToken).ConfigureAwait(false); var symbols = await TryGetSymbolsForContextAsync(completionContext, syntaxContext, options, cancellationToken).ConfigureAwait(false); return (relatedDocument.Id, syntaxContext, symbols); }, cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); foreach (var task in tasks) { var (relatedDocumentId, syntaxContext, symbols) = await task.ConfigureAwait(false); if (!symbols.IsDefault) perContextSymbols.Add((relatedDocumentId, syntaxContext, symbols)); } return perContextSymbols.ToImmutable(); } /// <summary> /// If current context is in active region, returns available symbols. Otherwise, returns null. /// </summary> protected async Task<ImmutableArray<(ISymbol symbol, bool preselect)>> TryGetSymbolsForContextAsync( CompletionContext? completionContext, TSyntaxContext syntaxContext, OptionSet options, CancellationToken cancellationToken) { var syntaxFacts = syntaxContext.GetLanguageService<ISyntaxFactsService>(); return syntaxFacts.IsInInactiveRegion(syntaxContext.SyntaxTree, syntaxContext.Position, cancellationToken) ? default : await GetSymbolsAsync(completionContext, syntaxContext, syntaxContext.Position, options, cancellationToken).ConfigureAwait(false); } protected static async Task<TSyntaxContext> CreateContextAsync(Document document, int position, CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); var service = document.GetRequiredLanguageService<ISyntaxContextService>(); return (TSyntaxContext)service.CreateContext(workspace, semanticModel, position, cancellationToken); } private static Task<TSyntaxContext> GetOrCreateContextAsync(Document document, int position, CancellationToken cancellationToken) { lock (s_cachedDocuments) { var (cachedPosition, cachedLazyContext) = s_cachedDocuments.GetValue( document, d => Tuple.Create(position, new AsyncLazy<TSyntaxContext>(ct => CreateContextAsync(d, position, ct), cacheResult: true))); if (cachedPosition == position) { return cachedLazyContext.GetValueAsync(cancellationToken); } var lazyContext = new AsyncLazy<TSyntaxContext>(ct => CreateContextAsync(document, position, ct), cacheResult: true); s_cachedDocuments.Remove(document); s_cachedDocuments.Add(document, Tuple.Create(position, lazyContext)); return lazyContext.GetValueAsync(cancellationToken); } } /// <summary> /// Given a list of symbols, determine which are not recommended at the same position in linked documents. /// </summary> /// <param name="symbolToContext">The symbols recommended in the active context.</param> /// <param name="linkedContextSymbolLists">The symbols recommended in linked documents</param> /// <returns>The list of projects each recommended symbol did NOT appear in.</returns> private static Dictionary<ISymbol, List<ProjectId>> FindSymbolsMissingInLinkedContexts( Dictionary<(ISymbol symbol, bool preselect), TSyntaxContext> symbolToContext, ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)> linkedContextSymbolLists) { var missingSymbols = new Dictionary<ISymbol, List<ProjectId>>(LinkedFilesSymbolEquivalenceComparer.Instance); foreach (var (documentId, syntaxContext, symbols) in linkedContextSymbolLists) { var symbolsMissingInLinkedContext = symbolToContext.Keys.Except(symbols, CompletionLinkedFilesSymbolEquivalenceComparer.Instance); foreach (var (symbol, _) in symbolsMissingInLinkedContext) missingSymbols.GetOrAdd(symbol, m => new List<ProjectId>()).Add(documentId.ProjectId); } return missingSymbols; } public sealed override Task<TextChange?> GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) => Task.FromResult<TextChange?>(new TextChange(selectedItem.Span, GetInsertionText(selectedItem, ch))); private string GetInsertionText(CompletionItem item, char? ch) { return ch == null ? SymbolCompletionItem.GetInsertionText(item) : GetInsertionText(item, ch.Value); } /// <summary> /// Override this if you want to provide customized insertion based on the character typed. /// </summary> protected virtual string GetInsertionText(CompletionItem item, char ch) => SymbolCompletionItem.GetInsertionText(item); // This is used to decide which provider we'd collect target type completion telemetry from. protected virtual bool ShouldCollectTelemetryForTargetTypeCompletion => false; private class TelemetryCounter : IDisposable { private readonly bool _shouldReport; private int _tick; public TelemetryCounter(bool shouldReport) => _shouldReport = shouldReport; public void AddTick(int tick) => _tick += tick; public void Dispose() { if (_shouldReport) { CompletionProvidersLogger.LogTargetTypeCompletionTicksDataPoint(_tick); } } } } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamespaceSymbol.vb
' 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. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.ImmutableArrayExtensions Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class SourceNamespaceSymbol Inherits PEOrSourceOrMergedNamespaceSymbol Private ReadOnly _declaration As MergedNamespaceDeclaration Private ReadOnly _containingNamespace As SourceNamespaceSymbol Private ReadOnly _containingModule As SourceModuleSymbol Private _nameToMembersMap As Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol)) Private _nameToTypeMembersMap As Dictionary(Of String, ImmutableArray(Of NamedTypeSymbol)) Private _lazyEmbeddedKind As Integer = EmbeddedSymbolKind.Unset ' lazily evaluated state of the symbol (StateFlags) Private _lazyState As Integer <Flags> Private Enum StateFlags As Integer HasMultipleSpellings = &H1 ' ReadOnly: Set if there are multiple declarations with different spellings (casing) AllMembersIsSorted = &H2 ' Set if "m_lazyAllMembers" is sorted. DeclarationValidated = &H4 ' Set by ValidateDeclaration. End Enum ' This caches results of GetModuleMembers() Private _lazyModuleMembers As ImmutableArray(Of NamedTypeSymbol) ' This caches results of GetMembers() Private _lazyAllMembers As ImmutableArray(Of Symbol) Private _lazyLexicalSortKey As LexicalSortKey = LexicalSortKey.NotInitialized Friend Sub New(decl As MergedNamespaceDeclaration, containingNamespace As SourceNamespaceSymbol, containingModule As SourceModuleSymbol) _declaration = decl _containingNamespace = containingNamespace _containingModule = containingModule If (containingNamespace IsNot Nothing AndAlso containingNamespace.HasMultipleSpellings) OrElse decl.HasMultipleSpellings Then _lazyState = StateFlags.HasMultipleSpellings End If End Sub ''' <summary> ''' Register COR types declared in this namespace, if any, in the COR types cache. ''' </summary> Private Sub RegisterDeclaredCorTypes() Dim containingAssembly As AssemblySymbol = Me.ContainingAssembly If (containingAssembly.KeepLookingForDeclaredSpecialTypes) Then ' Register newly declared COR types For Each array In _nameToMembersMap.Values For Each member In array Dim type = TryCast(member, NamedTypeSymbol) If type IsNot Nothing AndAlso type.SpecialType <> SpecialType.None Then containingAssembly.RegisterDeclaredSpecialType(type) If Not containingAssembly.KeepLookingForDeclaredSpecialTypes Then Return End If End If Next Next End If End Sub Public Overrides ReadOnly Property Name As String Get Return _declaration.Name End Get End Property Friend Overrides ReadOnly Property EmbeddedSymbolKind As EmbeddedSymbolKind Get If _lazyEmbeddedKind = EmbeddedSymbolKind.Unset Then Dim value As Integer = EmbeddedSymbolKind.None For Each location In _declaration.NameLocations Debug.Assert(location IsNot Nothing) If location.Kind = LocationKind.None Then Dim embeddedLocation = TryCast(location, EmbeddedTreeLocation) If embeddedLocation IsNot Nothing Then value = value Or embeddedLocation.EmbeddedKind End If End If Next Interlocked.CompareExchange(_lazyEmbeddedKind, value, EmbeddedSymbolKind.Unset) End If Return CType(_lazyEmbeddedKind, EmbeddedSymbolKind) End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return If(_containingNamespace, DirectCast(_containingModule, Symbol)) End Get End Property Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol Get Return _containingModule.ContainingAssembly End Get End Property Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return Me._containingModule End Get End Property Friend Overrides ReadOnly Property Extent As NamespaceExtent Get Return New NamespaceExtent(_containingModule) End Get End Property Private ReadOnly Property NameToMembersMap As Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol)) Get Return GetNameToMembersMap() End Get End Property Private Function GetNameToMembersMap() As Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol)) If _nameToMembersMap Is Nothing Then Dim map = MakeNameToMembersMap() If Interlocked.CompareExchange(_nameToMembersMap, map, Nothing) Is Nothing Then RegisterDeclaredCorTypes() End If End If Return _nameToMembersMap End Function Private Function MakeNameToMembersMap() As Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol)) ' NOTE: Even though the resulting map stores ImmutableArray(Of NamespaceOrTypeSymbol) as ' NOTE: values if the name is mapped into an array of named types, which is frequently ' NOTE: the case, we actually create an array of NamedTypeSymbol[] and wrap it in ' NOTE: ImmutableArray(Of NamespaceOrTypeSymbol) ' NOTE: ' NOTE: This way we can save time and memory in GetNameToTypeMembersMap() -- when we see that ' NOTE: a name maps into values collection containing types only instead of allocating another ' NOTE: array of NamedTypeSymbol[] we downcast the array to ImmutableArray(Of NamedTypeSymbol) Dim builder As New NameToSymbolMapBuilder(_declaration.Children.Length) For Each declaration In _declaration.Children builder.Add(BuildSymbol(declaration)) Next ' TODO(cyrusn): The C# and VB impls differ here. C# reports errors here and VB does not. ' Is that what we want? Return builder.CreateMap() End Function Private Structure NameToSymbolMapBuilder Private ReadOnly _dictionary As Dictionary(Of String, Object) Public Sub New(capacity As Integer) _dictionary = New Dictionary(Of String, Object)(capacity, IdentifierComparison.Comparer) End Sub Public Sub Add(symbol As NamespaceOrTypeSymbol) Dim name As String = symbol.Name Dim item As Object = Nothing If Me._dictionary.TryGetValue(name, item) Then Dim builder = TryCast(item, ArrayBuilder(Of NamespaceOrTypeSymbol)) If builder Is Nothing Then builder = ArrayBuilder(Of NamespaceOrTypeSymbol).GetInstance() builder.Add(DirectCast(item, NamespaceOrTypeSymbol)) Me._dictionary(name) = builder End If builder.Add(symbol) Else Me._dictionary(name) = symbol End If End Sub Public Function CreateMap() As Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol)) Dim result As New Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol))(Me._dictionary.Count, IdentifierComparison.Comparer) For Each kvp In Me._dictionary Dim value As Object = kvp.Value Dim members As ImmutableArray(Of NamespaceOrTypeSymbol) Dim builder = TryCast(value, ArrayBuilder(Of NamespaceOrTypeSymbol)) If builder IsNot Nothing Then Debug.Assert(builder.Count > 1) Dim hasNamespaces As Boolean = False For i = 0 To builder.Count - 1 If builder(i).Kind = SymbolKind.Namespace Then hasNamespaces = True Exit For End If Next If hasNamespaces Then members = builder.ToImmutable() Else members = StaticCast(Of NamespaceOrTypeSymbol).From(builder.ToDowncastedImmutable(Of NamedTypeSymbol)()) End If builder.Free() Else Dim symbol = DirectCast(value, NamespaceOrTypeSymbol) If symbol.Kind = SymbolKind.Namespace Then members = ImmutableArray.Create(Of NamespaceOrTypeSymbol)(symbol) Else members = StaticCast(Of NamespaceOrTypeSymbol).From(ImmutableArray.Create(Of NamedTypeSymbol)(DirectCast(symbol, NamedTypeSymbol))) End If End If result.Add(kvp.Key, members) Next Return result End Function End Structure Private Function BuildSymbol(decl As MergedNamespaceOrTypeDeclaration) As NamespaceOrTypeSymbol Dim namespaceDecl = TryCast(decl, MergedNamespaceDeclaration) If namespaceDecl IsNot Nothing Then Return New SourceNamespaceSymbol(namespaceDecl, Me, _containingModule) Else Dim typeDecl = DirectCast(decl, MergedTypeDeclaration) #If DEBUG Then ' Ensure that the type declaration is either from user code or embedded ' code, but not merged across embedded code/user code boundary. Dim embedded = EmbeddedSymbolKind.Unset For Each ref In typeDecl.SyntaxReferences Dim refKind = ref.SyntaxTree.GetEmbeddedKind() If embedded <> EmbeddedSymbolKind.Unset Then Debug.Assert(embedded = refKind) Else embedded = refKind End If Next Debug.Assert(embedded <> EmbeddedSymbolKind.Unset) #End If Return SourceNamedTypeSymbol.Create(typeDecl, Me, _containingModule) End If End Function Private Function GetNameToTypeMembersMap() As Dictionary(Of String, ImmutableArray(Of NamedTypeSymbol)) If _nameToTypeMembersMap Is Nothing Then ' NOTE: This method depends on MakeNameToMembersMap() on creating a proper ' NOTE: type of the array, see comments in MakeNameToMembersMap() for details Dim dictionary As New Dictionary(Of String, ImmutableArray(Of NamedTypeSymbol))(CaseInsensitiveComparison.Comparer) Dim map As Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol)) = Me.GetNameToMembersMap() For Each kvp In map Dim members As ImmutableArray(Of NamespaceOrTypeSymbol) = kvp.Value Dim hasType As Boolean = False Dim hasNamespace As Boolean = False For Each symbol In members If symbol.Kind = SymbolKind.NamedType Then hasType = True If hasNamespace Then Exit For End If Else Debug.Assert(symbol.Kind = SymbolKind.Namespace) hasNamespace = True If hasType Then Exit For End If End If Next If hasType Then If hasNamespace Then dictionary.Add(kvp.Key, members.OfType(Of NamedTypeSymbol).AsImmutable()) Else dictionary.Add(kvp.Key, members.As(Of NamedTypeSymbol)) End If End If Next Interlocked.CompareExchange(_nameToTypeMembersMap, dictionary, Nothing) End If Return _nameToTypeMembersMap End Function Public Overloads Overrides Function GetMembers() As ImmutableArray(Of Symbol) If (_lazyState And StateFlags.AllMembersIsSorted) <> 0 Then Return _lazyAllMembers Else Dim allMembers = Me.GetMembersUnordered() If allMembers.Length >= 2 Then allMembers = allMembers.Sort(LexicalOrderSymbolComparer.Instance) ImmutableInterlocked.InterlockedExchange(_lazyAllMembers, allMembers) End If ThreadSafeFlagOperations.Set(_lazyState, StateFlags.AllMembersIsSorted) Return allMembers End If End Function Friend Overloads Overrides Function GetMembersUnordered() As ImmutableArray(Of Symbol) If _lazyAllMembers.IsDefault Then Dim members = StaticCast(Of Symbol).From(Me.GetNameToMembersMap().Flatten()) ImmutableInterlocked.InterlockedCompareExchange(_lazyAllMembers, members, Nothing) End If Return _lazyAllMembers.ConditionallyDeOrder() End Function Public Overloads Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) Dim members As ImmutableArray(Of NamespaceOrTypeSymbol) = Nothing If Me.GetNameToMembersMap().TryGetValue(name, members) Then Return ImmutableArray(Of Symbol).CastUp(members) Else Return ImmutableArray(Of Symbol).Empty End If End Function Friend Overrides Function GetTypeMembersUnordered() As ImmutableArray(Of NamedTypeSymbol) Return Me.GetNameToTypeMembersMap().Flatten() End Function Public Overloads Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol) Return Me.GetNameToTypeMembersMap().Flatten(LexicalOrderSymbolComparer.Instance) End Function Public Overloads Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) Dim members As ImmutableArray(Of NamedTypeSymbol) = Nothing If Me.GetNameToTypeMembersMap().TryGetValue(name, members) Then Return members Else Return ImmutableArray(Of NamedTypeSymbol).Empty End If End Function ' This is very performance critical for type lookup. Public Overrides Function GetModuleMembers() As ImmutableArray(Of NamedTypeSymbol) If _lazyModuleMembers.IsDefault Then Dim moduleMembers = ArrayBuilder(Of NamedTypeSymbol).GetInstance() ' look at all child declarations to find the modules. For Each childDecl In _declaration.Children If childDecl.Kind = DeclarationKind.Module Then moduleMembers.AddRange(GetModuleMembers(childDecl.Name)) End If Next ImmutableInterlocked.InterlockedCompareExchange(_lazyModuleMembers, moduleMembers.ToImmutableAndFree(), Nothing) End If Return _lazyModuleMembers End Function Friend Overrides Function GetLexicalSortKey() As LexicalSortKey ' WARNING: this should not allocate memory! If Not _lazyLexicalSortKey.IsInitialized Then _lazyLexicalSortKey.SetFrom(_declaration.GetLexicalSortKey(Me.DeclaringCompilation)) End If Return _lazyLexicalSortKey End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return StaticCast(Of Location).From(_declaration.NameLocations) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ComputeDeclaringReferencesCore() End Get End Property Private Function ComputeDeclaringReferencesCore() As ImmutableArray(Of SyntaxReference) Dim declarations As ImmutableArray(Of SingleNamespaceDeclaration) = _declaration.Declarations Dim builder As ArrayBuilder(Of SyntaxReference) = ArrayBuilder(Of SyntaxReference).GetInstance(declarations.Length) ' SyntaxReference in the namespace declaration points to the name node of the namespace decl node not ' namespace decl node we want to return. here we will wrap the original syntax reference in ' the translation syntax reference so that we can lazily manipulate a node return to the caller For Each decl In declarations Dim reference = decl.SyntaxReference If reference IsNot Nothing AndAlso Not reference.SyntaxTree.IsEmbeddedOrMyTemplateTree() Then builder.Add(New NamespaceDeclarationSyntaxReference(reference)) End If Next Return builder.ToImmutableAndFree() End Function Friend Overrides Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean If Me.IsGlobalNamespace Then Return True Else ' Check if any namespace declaration block intersects with the given tree/span. For Each decl In _declaration.Declarations cancellationToken.ThrowIfCancellationRequested() Dim reference = decl.SyntaxReference If reference IsNot Nothing AndAlso reference.SyntaxTree Is tree Then If Not reference.SyntaxTree.IsEmbeddedOrMyTemplateTree() Then Dim syntaxRef = New NamespaceDeclarationSyntaxReference(reference) Dim syntax = syntaxRef.GetSyntax(cancellationToken) If TypeOf syntax Is NamespaceStatementSyntax Then ' Get the parent NamespaceBlockSyntax syntax = syntax.Parent End If If IsDefinedInSourceTree(syntax, tree, definedWithinSpan, cancellationToken) Then Return True End If End If ElseIf decl.IsPartOfRootNamespace ' Root namespace is implicitly defined in every tree Return True End If Next Return False End If End Function ' Force all declaration errors to be generated Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) MyBase.GenerateDeclarationErrors(cancellationToken) ValidateDeclaration(Nothing, cancellationToken) ' Getting all the members will force declaration errors for contained stuff. GetMembers() End Sub ' Force all declaration errors In Tree to be generated Friend Sub GenerateDeclarationErrorsInTree(tree As SyntaxTree, filterSpanWithinTree As TextSpan?, cancellationToken As CancellationToken) ValidateDeclaration(tree, cancellationToken) ' Getting all the members will force declaration errors for contained stuff. GetMembers() End Sub ' Validate a namespace declaration. This is called for each namespace being declared, so ' for example, it is called twice on Namespace X.Y, once with "X" and once with "X.Y". ' It will also be called with the CompilationUnit. Private Sub ValidateDeclaration(tree As SyntaxTree, cancellationToken As CancellationToken) If (_lazyState And StateFlags.DeclarationValidated) <> 0 Then Return End If Dim diagnostics = DiagnosticBag.GetInstance() Dim reportedNamespaceMismatch As Boolean = False ' Check for a few issues with namespace declaration. For Each syntaxRef In _declaration.SyntaxReferences If tree IsNot Nothing AndAlso syntaxRef.SyntaxTree IsNot tree Then Continue For End If Dim currentTree = syntaxRef.SyntaxTree Dim node As VisualBasicSyntaxNode = syntaxRef.GetVisualBasicSyntax(cancellationToken) Select Case node.Kind Case SyntaxKind.IdentifierName ValidateNamespaceNameSyntax(DirectCast(node, IdentifierNameSyntax), diagnostics, reportedNamespaceMismatch) Case SyntaxKind.QualifiedName ValidateNamespaceNameSyntax(DirectCast(node, QualifiedNameSyntax).Right, diagnostics, reportedNamespaceMismatch) Case SyntaxKind.GlobalName ValidateNamespaceGlobalSyntax(DirectCast(node, GlobalNameSyntax), diagnostics) Case SyntaxKind.CompilationUnit ' nothing to validate Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select cancellationToken.ThrowIfCancellationRequested() Next If _containingModule.AtomicSetFlagAndStoreDiagnostics(_lazyState, StateFlags.DeclarationValidated, 0, New BindingDiagnosticBag(diagnostics)) Then DeclaringCompilation.SymbolDeclaredEvent(Me) End If diagnostics.Free() End Sub ' Validate a particular namespace name. Private Sub ValidateNamespaceNameSyntax(node As SimpleNameSyntax, diagnostics As DiagnosticBag, ByRef reportedNamespaceMismatch As Boolean) If (node.Identifier.GetTypeCharacter() <> TypeCharacter.None) Then Dim diag = New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_TypecharNotallowed), node.GetLocation()) diagnostics.Add(diag) End If ' Warning should only be reported for the first mismatch for each namespace to ' avoid reporting a large number of warnings in projects with many files. ' This is by design ' TODO: do we really want to omit these warnings and display a new one after each fix? ' VS can display errors and warnings separately in the IDE, so it may be ok to flood the users with ' these warnings. If Not reportedNamespaceMismatch AndAlso String.Compare(node.Identifier.ValueText, Me.Name, StringComparison.Ordinal) <> 0 Then ' all namespace names from the declarations match following the VB identifier comparison rules, ' so we just need to check when they are not matching using case sensitive comparison. ' filename is the one where the correct declaration occurred in Dev10 ' TODO: report "related location" rather than including path in the message: Dim path = GetSourcePathForDeclaration() Dim diag = New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_NamespaceCaseMismatch3, node.Identifier.ValueText, Me.Name, path), node.GetLocation()) diagnostics.Add(diag) reportedNamespaceMismatch = True End If ' TODO: once the declarations are sorted, one might cache the filename if the first declaration matches the case. ' then GetFilenameForDeclaration is only needed if the mismatch occurs before any matching declaration. End Sub ' Validate that Global namespace name can't be nested inside another namespace. Private Sub ValidateNamespaceGlobalSyntax(node As GlobalNameSyntax, diagnostics As DiagnosticBag) Dim ancestorNode = node.Parent Dim seenNamespaceBlock As Boolean = False ' Go up the syntax hierarchy and make sure we only hit one namespace block (our own). While ancestorNode IsNot Nothing If ancestorNode.Kind = SyntaxKind.NamespaceBlock Then If seenNamespaceBlock Then ' Our namespace block is nested within another. That's a no-no. Dim diag = New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_NestedGlobalNamespace), node.GetLocation()) diagnostics.Add(diag) Else seenNamespaceBlock = True End If End If ancestorNode = ancestorNode.Parent End While End Sub ''' <summary> ''' Gets the filename of the first declaration that matches the given namespace name case sensitively. ''' </summary> Private Function GetSourcePathForDeclaration() As Object Debug.Assert(_declaration.Declarations.Length > 0) ' unfortunately we cannot initialize with the filename of the first declaration because that filename might be nothing. Dim path = Nothing For Each declaration In _declaration.Declarations If String.Compare(Me.Name, declaration.Name, StringComparison.Ordinal) = 0 Then If declaration.IsPartOfRootNamespace Then 'path = StringConstants.ProjectSettingLocationName path = New LocalizableErrorArgument(ERRID.IDS_ProjectSettingsLocationName) ElseIf declaration.SyntaxReference IsNot Nothing AndAlso declaration.SyntaxReference.SyntaxTree.FilePath IsNot Nothing Then Dim otherPath = declaration.SyntaxReference.SyntaxTree.FilePath If path Is Nothing Then path = otherPath ElseIf String.Compare(path.ToString, otherPath.ToString, StringComparison.Ordinal) > 0 Then path = otherPath End If End If End If Next Return path End Function ''' <summary> ''' Return the set of types that should be checked for presence of extension methods in order to build ''' a map of extension methods for the namespace. ''' </summary> Friend Overrides ReadOnly Property TypesToCheckForExtensionMethods As ImmutableArray(Of NamedTypeSymbol) Get If _containingModule.MightContainExtensionMethods Then ' Note that we are using GetModuleMembers because only Modules can contain extension methods in source. Return Me.GetModuleMembers() End If Return ImmutableArray(Of NamedTypeSymbol).Empty End Get End Property ''' <summary> ''' Does this namespace have multiple different case-sensitive spellings ''' (i.e., "Namespace GOO" and "Namespace goo". Includes parent namespace(s). ''' </summary> Friend ReadOnly Property HasMultipleSpellings As Boolean Get Return (_lazyState And StateFlags.HasMultipleSpellings) <> 0 End Get End Property ''' <summary> ''' Get the fully qualified namespace name using the spelling used in the declaration enclosing the given ''' syntax tree and location. ''' I.e., if this namespace was declared with: ''' Namespace zAp ''' Namespace GOO.bar ''' 'location ''' End Namespace ''' End Namespace ''' Namespace ZAP ''' Namespace goo.bar ''' End Namespace ''' End Namespace ''' ''' It would return "ProjectNamespace.zAp.GOO.bar". ''' </summary> Friend Function GetDeclarationSpelling(tree As SyntaxTree, location As Integer) As String If Not HasMultipleSpellings Then ' Only one spelling. Just return that. Return ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) Else ' Since the declaration builder has already resolved things like "Global", qualified names, etc, ' just find the declaration that encloses the location (as opposed to recreating the name ' by walking the syntax) Dim containingDecl = _declaration.Declarations.FirstOrDefault(Function(decl) Dim nsBlock As NamespaceBlockSyntax = decl.GetNamespaceBlockSyntax() Return nsBlock IsNot Nothing AndAlso nsBlock.SyntaxTree Is tree AndAlso nsBlock.Span.Contains(location) End Function) If containingDecl Is Nothing Then ' Could be project namespace, which has no namespace block syntax. containingDecl = _declaration.Declarations.FirstOrDefault(Function(decl) decl.GetNamespaceBlockSyntax() Is Nothing) End If Dim containingDeclName = If(containingDecl IsNot Nothing, containingDecl.Name, Me.Name) Dim containingNamespace = TryCast(Me.ContainingNamespace, SourceNamespaceSymbol) Dim fullDeclName As String If containingNamespace IsNot Nothing AndAlso containingNamespace.Name <> "" Then fullDeclName = containingNamespace.GetDeclarationSpelling(tree, location) + "." + containingDeclName Else fullDeclName = containingDeclName End If Debug.Assert(IdentifierComparison.Equals(fullDeclName, ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat))) Return fullDeclName End If End Function Public ReadOnly Property MergedDeclaration As MergedNamespaceDeclaration Get Return _declaration End Get End Property End Class End Namespace
' 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. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.ImmutableArrayExtensions Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class SourceNamespaceSymbol Inherits PEOrSourceOrMergedNamespaceSymbol Private ReadOnly _declaration As MergedNamespaceDeclaration Private ReadOnly _containingNamespace As SourceNamespaceSymbol Private ReadOnly _containingModule As SourceModuleSymbol Private _nameToMembersMap As Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol)) Private _nameToTypeMembersMap As Dictionary(Of String, ImmutableArray(Of NamedTypeSymbol)) Private _lazyEmbeddedKind As Integer = EmbeddedSymbolKind.Unset ' lazily evaluated state of the symbol (StateFlags) Private _lazyState As Integer <Flags> Private Enum StateFlags As Integer HasMultipleSpellings = &H1 ' ReadOnly: Set if there are multiple declarations with different spellings (casing) AllMembersIsSorted = &H2 ' Set if "m_lazyAllMembers" is sorted. DeclarationValidated = &H4 ' Set by ValidateDeclaration. End Enum ' This caches results of GetModuleMembers() Private _lazyModuleMembers As ImmutableArray(Of NamedTypeSymbol) ' This caches results of GetMembers() Private _lazyAllMembers As ImmutableArray(Of Symbol) Private _lazyLexicalSortKey As LexicalSortKey = LexicalSortKey.NotInitialized Friend Sub New(decl As MergedNamespaceDeclaration, containingNamespace As SourceNamespaceSymbol, containingModule As SourceModuleSymbol) _declaration = decl _containingNamespace = containingNamespace _containingModule = containingModule If (containingNamespace IsNot Nothing AndAlso containingNamespace.HasMultipleSpellings) OrElse decl.HasMultipleSpellings Then _lazyState = StateFlags.HasMultipleSpellings End If End Sub ''' <summary> ''' Register COR types declared in this namespace, if any, in the COR types cache. ''' </summary> Private Sub RegisterDeclaredCorTypes() Dim containingAssembly As AssemblySymbol = Me.ContainingAssembly If (containingAssembly.KeepLookingForDeclaredSpecialTypes) Then ' Register newly declared COR types For Each array In _nameToMembersMap.Values For Each member In array Dim type = TryCast(member, NamedTypeSymbol) If type IsNot Nothing AndAlso type.SpecialType <> SpecialType.None Then containingAssembly.RegisterDeclaredSpecialType(type) If Not containingAssembly.KeepLookingForDeclaredSpecialTypes Then Return End If End If Next Next End If End Sub Public Overrides ReadOnly Property Name As String Get Return _declaration.Name End Get End Property Friend Overrides ReadOnly Property EmbeddedSymbolKind As EmbeddedSymbolKind Get If _lazyEmbeddedKind = EmbeddedSymbolKind.Unset Then Dim value As Integer = EmbeddedSymbolKind.None For Each location In _declaration.NameLocations Debug.Assert(location IsNot Nothing) If location.Kind = LocationKind.None Then Dim embeddedLocation = TryCast(location, EmbeddedTreeLocation) If embeddedLocation IsNot Nothing Then value = value Or embeddedLocation.EmbeddedKind End If End If Next Interlocked.CompareExchange(_lazyEmbeddedKind, value, EmbeddedSymbolKind.Unset) End If Return CType(_lazyEmbeddedKind, EmbeddedSymbolKind) End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return If(_containingNamespace, DirectCast(_containingModule, Symbol)) End Get End Property Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol Get Return _containingModule.ContainingAssembly End Get End Property Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return Me._containingModule End Get End Property Friend Overrides ReadOnly Property Extent As NamespaceExtent Get Return New NamespaceExtent(_containingModule) End Get End Property Private ReadOnly Property NameToMembersMap As Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol)) Get Return GetNameToMembersMap() End Get End Property Private Function GetNameToMembersMap() As Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol)) If _nameToMembersMap Is Nothing Then Dim map = MakeNameToMembersMap() If Interlocked.CompareExchange(_nameToMembersMap, map, Nothing) Is Nothing Then RegisterDeclaredCorTypes() End If End If Return _nameToMembersMap End Function Private Function MakeNameToMembersMap() As Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol)) ' NOTE: Even though the resulting map stores ImmutableArray(Of NamespaceOrTypeSymbol) as ' NOTE: values if the name is mapped into an array of named types, which is frequently ' NOTE: the case, we actually create an array of NamedTypeSymbol[] and wrap it in ' NOTE: ImmutableArray(Of NamespaceOrTypeSymbol) ' NOTE: ' NOTE: This way we can save time and memory in GetNameToTypeMembersMap() -- when we see that ' NOTE: a name maps into values collection containing types only instead of allocating another ' NOTE: array of NamedTypeSymbol[] we downcast the array to ImmutableArray(Of NamedTypeSymbol) Dim builder As New NameToSymbolMapBuilder(_declaration.Children.Length) For Each declaration In _declaration.Children builder.Add(BuildSymbol(declaration)) Next ' TODO(cyrusn): The C# and VB impls differ here. C# reports errors here and VB does not. ' Is that what we want? Return builder.CreateMap() End Function Private Structure NameToSymbolMapBuilder Private ReadOnly _dictionary As Dictionary(Of String, Object) Public Sub New(capacity As Integer) _dictionary = New Dictionary(Of String, Object)(capacity, IdentifierComparison.Comparer) End Sub Public Sub Add(symbol As NamespaceOrTypeSymbol) Dim name As String = symbol.Name Dim item As Object = Nothing If Me._dictionary.TryGetValue(name, item) Then Dim builder = TryCast(item, ArrayBuilder(Of NamespaceOrTypeSymbol)) If builder Is Nothing Then builder = ArrayBuilder(Of NamespaceOrTypeSymbol).GetInstance() builder.Add(DirectCast(item, NamespaceOrTypeSymbol)) Me._dictionary(name) = builder End If builder.Add(symbol) Else Me._dictionary(name) = symbol End If End Sub Public Function CreateMap() As Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol)) Dim result As New Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol))(Me._dictionary.Count, IdentifierComparison.Comparer) For Each kvp In Me._dictionary Dim value As Object = kvp.Value Dim members As ImmutableArray(Of NamespaceOrTypeSymbol) Dim builder = TryCast(value, ArrayBuilder(Of NamespaceOrTypeSymbol)) If builder IsNot Nothing Then Debug.Assert(builder.Count > 1) Dim hasNamespaces As Boolean = False For i = 0 To builder.Count - 1 If builder(i).Kind = SymbolKind.Namespace Then hasNamespaces = True Exit For End If Next If hasNamespaces Then members = builder.ToImmutable() Else members = StaticCast(Of NamespaceOrTypeSymbol).From(builder.ToDowncastedImmutable(Of NamedTypeSymbol)()) End If builder.Free() Else Dim symbol = DirectCast(value, NamespaceOrTypeSymbol) If symbol.Kind = SymbolKind.Namespace Then members = ImmutableArray.Create(Of NamespaceOrTypeSymbol)(symbol) Else members = StaticCast(Of NamespaceOrTypeSymbol).From(ImmutableArray.Create(Of NamedTypeSymbol)(DirectCast(symbol, NamedTypeSymbol))) End If End If result.Add(kvp.Key, members) Next Return result End Function End Structure Private Function BuildSymbol(decl As MergedNamespaceOrTypeDeclaration) As NamespaceOrTypeSymbol Dim namespaceDecl = TryCast(decl, MergedNamespaceDeclaration) If namespaceDecl IsNot Nothing Then Return New SourceNamespaceSymbol(namespaceDecl, Me, _containingModule) Else Dim typeDecl = DirectCast(decl, MergedTypeDeclaration) #If DEBUG Then ' Ensure that the type declaration is either from user code or embedded ' code, but not merged across embedded code/user code boundary. Dim embedded = EmbeddedSymbolKind.Unset For Each ref In typeDecl.SyntaxReferences Dim refKind = ref.SyntaxTree.GetEmbeddedKind() If embedded <> EmbeddedSymbolKind.Unset Then Debug.Assert(embedded = refKind) Else embedded = refKind End If Next Debug.Assert(embedded <> EmbeddedSymbolKind.Unset) #End If Return SourceNamedTypeSymbol.Create(typeDecl, Me, _containingModule) End If End Function Private Function GetNameToTypeMembersMap() As Dictionary(Of String, ImmutableArray(Of NamedTypeSymbol)) If _nameToTypeMembersMap Is Nothing Then ' NOTE: This method depends on MakeNameToMembersMap() on creating a proper ' NOTE: type of the array, see comments in MakeNameToMembersMap() for details Dim dictionary As New Dictionary(Of String, ImmutableArray(Of NamedTypeSymbol))(CaseInsensitiveComparison.Comparer) Dim map As Dictionary(Of String, ImmutableArray(Of NamespaceOrTypeSymbol)) = Me.GetNameToMembersMap() For Each kvp In map Dim members As ImmutableArray(Of NamespaceOrTypeSymbol) = kvp.Value Dim hasType As Boolean = False Dim hasNamespace As Boolean = False For Each symbol In members If symbol.Kind = SymbolKind.NamedType Then hasType = True If hasNamespace Then Exit For End If Else Debug.Assert(symbol.Kind = SymbolKind.Namespace) hasNamespace = True If hasType Then Exit For End If End If Next If hasType Then If hasNamespace Then dictionary.Add(kvp.Key, members.OfType(Of NamedTypeSymbol).AsImmutable()) Else dictionary.Add(kvp.Key, members.As(Of NamedTypeSymbol)) End If End If Next Interlocked.CompareExchange(_nameToTypeMembersMap, dictionary, Nothing) End If Return _nameToTypeMembersMap End Function Public Overloads Overrides Function GetMembers() As ImmutableArray(Of Symbol) If (_lazyState And StateFlags.AllMembersIsSorted) <> 0 Then Return _lazyAllMembers Else Dim allMembers = Me.GetMembersUnordered() If allMembers.Length >= 2 Then allMembers = allMembers.Sort(LexicalOrderSymbolComparer.Instance) ImmutableInterlocked.InterlockedExchange(_lazyAllMembers, allMembers) End If ThreadSafeFlagOperations.Set(_lazyState, StateFlags.AllMembersIsSorted) Return allMembers End If End Function Friend Overloads Overrides Function GetMembersUnordered() As ImmutableArray(Of Symbol) If _lazyAllMembers.IsDefault Then Dim members = StaticCast(Of Symbol).From(Me.GetNameToMembersMap().Flatten()) ImmutableInterlocked.InterlockedCompareExchange(_lazyAllMembers, members, Nothing) End If Return _lazyAllMembers.ConditionallyDeOrder() End Function Public Overloads Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) Dim members As ImmutableArray(Of NamespaceOrTypeSymbol) = Nothing If Me.GetNameToMembersMap().TryGetValue(name, members) Then Return ImmutableArray(Of Symbol).CastUp(members) Else Return ImmutableArray(Of Symbol).Empty End If End Function Friend Overrides Function GetTypeMembersUnordered() As ImmutableArray(Of NamedTypeSymbol) Return Me.GetNameToTypeMembersMap().Flatten() End Function Public Overloads Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol) Return Me.GetNameToTypeMembersMap().Flatten(LexicalOrderSymbolComparer.Instance) End Function Public Overloads Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) Dim members As ImmutableArray(Of NamedTypeSymbol) = Nothing If Me.GetNameToTypeMembersMap().TryGetValue(name, members) Then Return members Else Return ImmutableArray(Of NamedTypeSymbol).Empty End If End Function ' This is very performance critical for type lookup. Public Overrides Function GetModuleMembers() As ImmutableArray(Of NamedTypeSymbol) If _lazyModuleMembers.IsDefault Then Dim moduleMembers = ArrayBuilder(Of NamedTypeSymbol).GetInstance() ' look at all child declarations to find the modules. For Each childDecl In _declaration.Children If childDecl.Kind = DeclarationKind.Module Then moduleMembers.AddRange(GetModuleMembers(childDecl.Name)) End If Next ImmutableInterlocked.InterlockedCompareExchange(_lazyModuleMembers, moduleMembers.ToImmutableAndFree(), Nothing) End If Return _lazyModuleMembers End Function Friend Overrides Function GetLexicalSortKey() As LexicalSortKey ' WARNING: this should not allocate memory! If Not _lazyLexicalSortKey.IsInitialized Then _lazyLexicalSortKey.SetFrom(_declaration.GetLexicalSortKey(Me.DeclaringCompilation)) End If Return _lazyLexicalSortKey End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return StaticCast(Of Location).From(_declaration.NameLocations) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ComputeDeclaringReferencesCore() End Get End Property Private Function ComputeDeclaringReferencesCore() As ImmutableArray(Of SyntaxReference) Dim declarations As ImmutableArray(Of SingleNamespaceDeclaration) = _declaration.Declarations Dim builder As ArrayBuilder(Of SyntaxReference) = ArrayBuilder(Of SyntaxReference).GetInstance(declarations.Length) ' SyntaxReference in the namespace declaration points to the name node of the namespace decl node not ' namespace decl node we want to return. here we will wrap the original syntax reference in ' the translation syntax reference so that we can lazily manipulate a node return to the caller For Each decl In declarations Dim reference = decl.SyntaxReference If reference IsNot Nothing AndAlso Not reference.SyntaxTree.IsEmbeddedOrMyTemplateTree() Then builder.Add(New NamespaceDeclarationSyntaxReference(reference)) End If Next Return builder.ToImmutableAndFree() End Function Friend Overrides Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean If Me.IsGlobalNamespace Then Return True Else ' Check if any namespace declaration block intersects with the given tree/span. For Each decl In _declaration.Declarations cancellationToken.ThrowIfCancellationRequested() Dim reference = decl.SyntaxReference If reference IsNot Nothing AndAlso reference.SyntaxTree Is tree Then If Not reference.SyntaxTree.IsEmbeddedOrMyTemplateTree() Then Dim syntaxRef = New NamespaceDeclarationSyntaxReference(reference) Dim syntax = syntaxRef.GetSyntax(cancellationToken) If TypeOf syntax Is NamespaceStatementSyntax Then ' Get the parent NamespaceBlockSyntax syntax = syntax.Parent End If If IsDefinedInSourceTree(syntax, tree, definedWithinSpan, cancellationToken) Then Return True End If End If ElseIf decl.IsPartOfRootNamespace ' Root namespace is implicitly defined in every tree Return True End If Next Return False End If End Function ' Force all declaration errors to be generated Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) MyBase.GenerateDeclarationErrors(cancellationToken) ValidateDeclaration(Nothing, cancellationToken) ' Getting all the members will force declaration errors for contained stuff. GetMembers() End Sub ' Force all declaration errors In Tree to be generated Friend Sub GenerateDeclarationErrorsInTree(tree As SyntaxTree, filterSpanWithinTree As TextSpan?, cancellationToken As CancellationToken) ValidateDeclaration(tree, cancellationToken) ' Getting all the members will force declaration errors for contained stuff. GetMembers() End Sub ' Validate a namespace declaration. This is called for each namespace being declared, so ' for example, it is called twice on Namespace X.Y, once with "X" and once with "X.Y". ' It will also be called with the CompilationUnit. Private Sub ValidateDeclaration(tree As SyntaxTree, cancellationToken As CancellationToken) If (_lazyState And StateFlags.DeclarationValidated) <> 0 Then Return End If Dim diagnostics = DiagnosticBag.GetInstance() Dim reportedNamespaceMismatch As Boolean = False ' Check for a few issues with namespace declaration. For Each syntaxRef In _declaration.SyntaxReferences If tree IsNot Nothing AndAlso syntaxRef.SyntaxTree IsNot tree Then Continue For End If Dim currentTree = syntaxRef.SyntaxTree Dim node As VisualBasicSyntaxNode = syntaxRef.GetVisualBasicSyntax(cancellationToken) Select Case node.Kind Case SyntaxKind.IdentifierName ValidateNamespaceNameSyntax(DirectCast(node, IdentifierNameSyntax), diagnostics, reportedNamespaceMismatch) Case SyntaxKind.QualifiedName ValidateNamespaceNameSyntax(DirectCast(node, QualifiedNameSyntax).Right, diagnostics, reportedNamespaceMismatch) Case SyntaxKind.GlobalName ValidateNamespaceGlobalSyntax(DirectCast(node, GlobalNameSyntax), diagnostics) Case SyntaxKind.CompilationUnit ' nothing to validate Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select cancellationToken.ThrowIfCancellationRequested() Next If _containingModule.AtomicSetFlagAndStoreDiagnostics(_lazyState, StateFlags.DeclarationValidated, 0, New BindingDiagnosticBag(diagnostics)) Then DeclaringCompilation.SymbolDeclaredEvent(Me) End If diagnostics.Free() End Sub ' Validate a particular namespace name. Private Sub ValidateNamespaceNameSyntax(node As SimpleNameSyntax, diagnostics As DiagnosticBag, ByRef reportedNamespaceMismatch As Boolean) If (node.Identifier.GetTypeCharacter() <> TypeCharacter.None) Then Dim diag = New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_TypecharNotallowed), node.GetLocation()) diagnostics.Add(diag) End If ' Warning should only be reported for the first mismatch for each namespace to ' avoid reporting a large number of warnings in projects with many files. ' This is by design ' TODO: do we really want to omit these warnings and display a new one after each fix? ' VS can display errors and warnings separately in the IDE, so it may be ok to flood the users with ' these warnings. If Not reportedNamespaceMismatch AndAlso String.Compare(node.Identifier.ValueText, Me.Name, StringComparison.Ordinal) <> 0 Then ' all namespace names from the declarations match following the VB identifier comparison rules, ' so we just need to check when they are not matching using case sensitive comparison. ' filename is the one where the correct declaration occurred in Dev10 ' TODO: report "related location" rather than including path in the message: Dim path = GetSourcePathForDeclaration() Dim diag = New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_NamespaceCaseMismatch3, node.Identifier.ValueText, Me.Name, path), node.GetLocation()) diagnostics.Add(diag) reportedNamespaceMismatch = True End If ' TODO: once the declarations are sorted, one might cache the filename if the first declaration matches the case. ' then GetFilenameForDeclaration is only needed if the mismatch occurs before any matching declaration. End Sub ' Validate that Global namespace name can't be nested inside another namespace. Private Sub ValidateNamespaceGlobalSyntax(node As GlobalNameSyntax, diagnostics As DiagnosticBag) Dim ancestorNode = node.Parent Dim seenNamespaceBlock As Boolean = False ' Go up the syntax hierarchy and make sure we only hit one namespace block (our own). While ancestorNode IsNot Nothing If ancestorNode.Kind = SyntaxKind.NamespaceBlock Then If seenNamespaceBlock Then ' Our namespace block is nested within another. That's a no-no. Dim diag = New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_NestedGlobalNamespace), node.GetLocation()) diagnostics.Add(diag) Else seenNamespaceBlock = True End If End If ancestorNode = ancestorNode.Parent End While End Sub ''' <summary> ''' Gets the filename of the first declaration that matches the given namespace name case sensitively. ''' </summary> Private Function GetSourcePathForDeclaration() As Object Debug.Assert(_declaration.Declarations.Length > 0) ' unfortunately we cannot initialize with the filename of the first declaration because that filename might be nothing. Dim path = Nothing For Each declaration In _declaration.Declarations If String.Compare(Me.Name, declaration.Name, StringComparison.Ordinal) = 0 Then If declaration.IsPartOfRootNamespace Then 'path = StringConstants.ProjectSettingLocationName path = New LocalizableErrorArgument(ERRID.IDS_ProjectSettingsLocationName) ElseIf declaration.SyntaxReference IsNot Nothing AndAlso declaration.SyntaxReference.SyntaxTree.FilePath IsNot Nothing Then Dim otherPath = declaration.SyntaxReference.SyntaxTree.FilePath If path Is Nothing Then path = otherPath ElseIf String.Compare(path.ToString, otherPath.ToString, StringComparison.Ordinal) > 0 Then path = otherPath End If End If End If Next Return path End Function ''' <summary> ''' Return the set of types that should be checked for presence of extension methods in order to build ''' a map of extension methods for the namespace. ''' </summary> Friend Overrides ReadOnly Property TypesToCheckForExtensionMethods As ImmutableArray(Of NamedTypeSymbol) Get If _containingModule.MightContainExtensionMethods Then ' Note that we are using GetModuleMembers because only Modules can contain extension methods in source. Return Me.GetModuleMembers() End If Return ImmutableArray(Of NamedTypeSymbol).Empty End Get End Property ''' <summary> ''' Does this namespace have multiple different case-sensitive spellings ''' (i.e., "Namespace GOO" and "Namespace goo". Includes parent namespace(s). ''' </summary> Friend ReadOnly Property HasMultipleSpellings As Boolean Get Return (_lazyState And StateFlags.HasMultipleSpellings) <> 0 End Get End Property ''' <summary> ''' Get the fully qualified namespace name using the spelling used in the declaration enclosing the given ''' syntax tree and location. ''' I.e., if this namespace was declared with: ''' Namespace zAp ''' Namespace GOO.bar ''' 'location ''' End Namespace ''' End Namespace ''' Namespace ZAP ''' Namespace goo.bar ''' End Namespace ''' End Namespace ''' ''' It would return "ProjectNamespace.zAp.GOO.bar". ''' </summary> Friend Function GetDeclarationSpelling(tree As SyntaxTree, location As Integer) As String If Not HasMultipleSpellings Then ' Only one spelling. Just return that. Return ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) Else ' Since the declaration builder has already resolved things like "Global", qualified names, etc, ' just find the declaration that encloses the location (as opposed to recreating the name ' by walking the syntax) Dim containingDecl = _declaration.Declarations.FirstOrDefault(Function(decl) Dim nsBlock As NamespaceBlockSyntax = decl.GetNamespaceBlockSyntax() Return nsBlock IsNot Nothing AndAlso nsBlock.SyntaxTree Is tree AndAlso nsBlock.Span.Contains(location) End Function) If containingDecl Is Nothing Then ' Could be project namespace, which has no namespace block syntax. containingDecl = _declaration.Declarations.FirstOrDefault(Function(decl) decl.GetNamespaceBlockSyntax() Is Nothing) End If Dim containingDeclName = If(containingDecl IsNot Nothing, containingDecl.Name, Me.Name) Dim containingNamespace = TryCast(Me.ContainingNamespace, SourceNamespaceSymbol) Dim fullDeclName As String If containingNamespace IsNot Nothing AndAlso containingNamespace.Name <> "" Then fullDeclName = containingNamespace.GetDeclarationSpelling(tree, location) + "." + containingDeclName Else fullDeclName = containingDeclName End If Debug.Assert(IdentifierComparison.Equals(fullDeclName, ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat))) Return fullDeclName End If End Function Public ReadOnly Property MergedDeclaration As MergedNamespaceDeclaration Get Return _declaration End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/CommandLine/BuildProtocol.cs
// 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 Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using static Microsoft.CodeAnalysis.CommandLine.BuildProtocolConstants; using static Microsoft.CodeAnalysis.CommandLine.CompilerServerLogger; // This file describes data structures about the protocol from client program to server that is // used. The basic protocol is this. // // After the server pipe is connected, it forks off a thread to handle the connection, and creates // a new instance of the pipe to listen for new clients. When it gets a request, it validates // the security and elevation level of the client. If that fails, it disconnects the client. Otherwise, // it handles the request, sends a response (described by Response class) back to the client, then // disconnects the pipe and ends the thread. namespace Microsoft.CodeAnalysis.CommandLine { /// <summary> /// Represents a request from the client. A request is as follows. /// /// Field Name Type Size (bytes) /// ---------------------------------------------------- /// Length Integer 4 /// RequestId Guid 16 /// Language RequestLanguage 4 /// CompilerHash String Variable /// Argument Count UInteger 4 /// Arguments Argument[] Variable /// /// See <see cref="Argument"/> for the format of an /// Argument. /// /// </summary> internal class BuildRequest { /// <summary> /// The maximum size of a request supported by the compiler server. /// </summary> /// <remarks> /// Currently this limit is 5MB. /// </remarks> private const int MaximumRequestSize = 0x500000; public readonly Guid RequestId; public readonly RequestLanguage Language; public readonly ReadOnlyCollection<Argument> Arguments; public readonly string CompilerHash; public BuildRequest(RequestLanguage language, string compilerHash, IEnumerable<Argument> arguments, Guid? requestId = null) { RequestId = requestId ?? Guid.Empty; Language = language; Arguments = new ReadOnlyCollection<Argument>(arguments.ToList()); CompilerHash = compilerHash; Debug.Assert(!string.IsNullOrWhiteSpace(CompilerHash), "A hash value is required to communicate with the server"); } public static BuildRequest Create(RequestLanguage language, IList<string> args, string workingDirectory, string tempDirectory, string compilerHash, Guid? requestId = null, string? keepAlive = null, string? libDirectory = null) { Debug.Assert(!string.IsNullOrWhiteSpace(compilerHash), "CompilerHash is required to send request to the build server"); var requestLength = args.Count + 1 + (libDirectory == null ? 0 : 1); var requestArgs = new List<Argument>(requestLength); requestArgs.Add(new Argument(ArgumentId.CurrentDirectory, 0, workingDirectory)); requestArgs.Add(new Argument(ArgumentId.TempDirectory, 0, tempDirectory)); if (keepAlive != null) { requestArgs.Add(new Argument(ArgumentId.KeepAlive, 0, keepAlive)); } if (libDirectory != null) { requestArgs.Add(new Argument(ArgumentId.LibEnvVariable, 0, libDirectory)); } for (int i = 0; i < args.Count; ++i) { var arg = args[i]; requestArgs.Add(new Argument(ArgumentId.CommandLineArgument, i, arg)); } return new BuildRequest(language, compilerHash, requestArgs, requestId); } public static BuildRequest CreateShutdown() { var requestArgs = new[] { new Argument(ArgumentId.Shutdown, argumentIndex: 0, value: "") }; return new BuildRequest(RequestLanguage.CSharpCompile, GetCommitHash() ?? "", requestArgs); } /// <summary> /// Read a Request from the given stream. /// /// The total request size must be less than <see cref="MaximumRequestSize"/>. /// </summary> /// <returns>null if the Request was too large, the Request otherwise.</returns> public static async Task<BuildRequest> ReadAsync(Stream inStream, CancellationToken cancellationToken) { // Read the length of the request var lengthBuffer = new byte[4]; await ReadAllAsync(inStream, lengthBuffer, 4, cancellationToken).ConfigureAwait(false); var length = BitConverter.ToInt32(lengthBuffer, 0); // Back out if the request is too large if (length > MaximumRequestSize) { throw new ArgumentException($"Request is over {MaximumRequestSize >> 20}MB in length"); } cancellationToken.ThrowIfCancellationRequested(); // Read the full request var requestBuffer = new byte[length]; await ReadAllAsync(inStream, requestBuffer, length, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); // Parse the request into the Request data structure. using var reader = new BinaryReader(new MemoryStream(requestBuffer), Encoding.Unicode); var requestId = readGuid(reader); var language = (RequestLanguage)reader.ReadUInt32(); var compilerHash = reader.ReadString(); uint argumentCount = reader.ReadUInt32(); var argumentsBuilder = new List<Argument>((int)argumentCount); for (int i = 0; i < argumentCount; i++) { cancellationToken.ThrowIfCancellationRequested(); argumentsBuilder.Add(BuildRequest.Argument.ReadFromBinaryReader(reader)); } return new BuildRequest(language, compilerHash, argumentsBuilder, requestId); static Guid readGuid(BinaryReader reader) { const int size = 16; var bytes = new byte[size]; if (size != reader.Read(bytes, 0, size)) { throw new InvalidOperationException(); } return new Guid(bytes); } } /// <summary> /// Write a Request to the stream. /// </summary> public async Task WriteAsync(Stream outStream, CancellationToken cancellationToken = default(CancellationToken)) { using var memoryStream = new MemoryStream(); using var writer = new BinaryWriter(memoryStream, Encoding.Unicode); writer.Write(RequestId.ToByteArray()); writer.Write((uint)Language); writer.Write(CompilerHash); writer.Write(Arguments.Count); foreach (Argument arg in Arguments) { cancellationToken.ThrowIfCancellationRequested(); arg.WriteToBinaryWriter(writer); } writer.Flush(); cancellationToken.ThrowIfCancellationRequested(); // Write the length of the request int length = checked((int)memoryStream.Length); // Back out if the request is too large if (memoryStream.Length > MaximumRequestSize) { throw new ArgumentOutOfRangeException($"Request is over {MaximumRequestSize >> 20}MB in length"); } await outStream.WriteAsync(BitConverter.GetBytes(length), 0, 4, cancellationToken).ConfigureAwait(false); memoryStream.Position = 0; await memoryStream.CopyToAsync(outStream, bufferSize: length, cancellationToken: cancellationToken).ConfigureAwait(false); } /// <summary> /// A command line argument to the compilation. /// An argument is formatted as follows: /// /// Field Name Type Size (bytes) /// -------------------------------------------------- /// ID UInteger 4 /// Index UInteger 4 /// Value String Variable /// /// Strings are encoded via a length prefix as a signed /// 32-bit integer, followed by an array of characters. /// </summary> public struct Argument { public readonly ArgumentId ArgumentId; public readonly int ArgumentIndex; public readonly string? Value; public Argument(ArgumentId argumentId, int argumentIndex, string? value) { ArgumentId = argumentId; ArgumentIndex = argumentIndex; Value = value; } public static Argument ReadFromBinaryReader(BinaryReader reader) { var argId = (ArgumentId)reader.ReadInt32(); var argIndex = reader.ReadInt32(); string? value = ReadLengthPrefixedString(reader); return new Argument(argId, argIndex, value); } public void WriteToBinaryWriter(BinaryWriter writer) { writer.Write((int)ArgumentId); writer.Write(ArgumentIndex); WriteLengthPrefixedString(writer, Value); } } } /// <summary> /// Base class for all possible responses to a request. /// The ResponseType enum should list all possible response types /// and ReadResponse creates the appropriate response subclass based /// on the response type sent by the client. /// The format of a response is: /// /// Field Name Field Type Size (bytes) /// ------------------------------------------------- /// responseLength int (positive) 4 /// responseType enum ResponseType 4 /// responseBody Response subclass variable /// </summary> internal abstract class BuildResponse { public enum ResponseType { // The client and server are using incompatible protocol versions. MismatchedVersion, // The build request completed on the server and the results are contained // in the message. Completed, // The build request could not be run on the server due because it created // an unresolvable inconsistency with analyzers. AnalyzerInconsistency, // The shutdown request completed and the server process information is // contained in the message. Shutdown, // The request was rejected by the server. Rejected, // The server hash did not match the one supplied by the client IncorrectHash, } public abstract ResponseType Type { get; } public async Task WriteAsync(Stream outStream, CancellationToken cancellationToken) { using (var memoryStream = new MemoryStream()) using (var writer = new BinaryWriter(memoryStream, Encoding.Unicode)) { writer.Write((int)Type); AddResponseBody(writer); writer.Flush(); cancellationToken.ThrowIfCancellationRequested(); // Send the response to the client // Write the length of the response int length = checked((int)memoryStream.Length); // There is no way to know the number of bytes written to // the pipe stream. We just have to assume all of them are written. await outStream.WriteAsync(BitConverter.GetBytes(length), 0, 4, cancellationToken).ConfigureAwait(false); memoryStream.Position = 0; await memoryStream.CopyToAsync(outStream, bufferSize: length, cancellationToken: cancellationToken).ConfigureAwait(false); } } protected abstract void AddResponseBody(BinaryWriter writer); /// <summary> /// May throw exceptions if there are pipe problems. /// </summary> /// <param name="stream"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public static async Task<BuildResponse> ReadAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { // Read the response length var lengthBuffer = new byte[4]; await ReadAllAsync(stream, lengthBuffer, 4, cancellationToken).ConfigureAwait(false); var length = BitConverter.ToUInt32(lengthBuffer, 0); // Read the response var responseBuffer = new byte[length]; await ReadAllAsync(stream, responseBuffer, responseBuffer.Length, cancellationToken).ConfigureAwait(false); using (var reader = new BinaryReader(new MemoryStream(responseBuffer), Encoding.Unicode)) { var responseType = (ResponseType)reader.ReadInt32(); switch (responseType) { case ResponseType.Completed: return CompletedBuildResponse.Create(reader); case ResponseType.MismatchedVersion: return new MismatchedVersionBuildResponse(); case ResponseType.IncorrectHash: return new IncorrectHashBuildResponse(); case ResponseType.AnalyzerInconsistency: return AnalyzerInconsistencyBuildResponse.Create(reader); case ResponseType.Shutdown: return ShutdownBuildResponse.Create(reader); case ResponseType.Rejected: return RejectedBuildResponse.Create(reader); default: throw new InvalidOperationException("Received invalid response type from server."); } } } } /// <summary> /// Represents a Response from the server. A response is as follows. /// /// Field Name Type Size (bytes) /// -------------------------------------------------- /// Length UInteger 4 /// ReturnCode Integer 4 /// Output String Variable /// /// Strings are encoded via a character count prefix as a /// 32-bit integer, followed by an array of characters. /// /// </summary> internal sealed class CompletedBuildResponse : BuildResponse { public readonly int ReturnCode; public readonly bool Utf8Output; public readonly string Output; public CompletedBuildResponse(int returnCode, bool utf8output, string? output) { ReturnCode = returnCode; Utf8Output = utf8output; Output = output ?? string.Empty; } public override ResponseType Type => ResponseType.Completed; public static CompletedBuildResponse Create(BinaryReader reader) { var returnCode = reader.ReadInt32(); var utf8Output = reader.ReadBoolean(); var output = ReadLengthPrefixedString(reader); return new CompletedBuildResponse(returnCode, utf8Output, output); } protected override void AddResponseBody(BinaryWriter writer) { writer.Write(ReturnCode); writer.Write(Utf8Output); WriteLengthPrefixedString(writer, Output); } } internal sealed class ShutdownBuildResponse : BuildResponse { public readonly int ServerProcessId; public ShutdownBuildResponse(int serverProcessId) { ServerProcessId = serverProcessId; } public override ResponseType Type => ResponseType.Shutdown; protected override void AddResponseBody(BinaryWriter writer) { writer.Write(ServerProcessId); } public static ShutdownBuildResponse Create(BinaryReader reader) { var serverProcessId = reader.ReadInt32(); return new ShutdownBuildResponse(serverProcessId); } } internal sealed class MismatchedVersionBuildResponse : BuildResponse { public override ResponseType Type => ResponseType.MismatchedVersion; /// <summary> /// MismatchedVersion has no body. /// </summary> protected override void AddResponseBody(BinaryWriter writer) { } } internal sealed class IncorrectHashBuildResponse : BuildResponse { public override ResponseType Type => ResponseType.IncorrectHash; /// <summary> /// IncorrectHash has no body. /// </summary> protected override void AddResponseBody(BinaryWriter writer) { } } internal sealed class AnalyzerInconsistencyBuildResponse : BuildResponse { public override ResponseType Type => ResponseType.AnalyzerInconsistency; public ReadOnlyCollection<string> ErrorMessages { get; } public AnalyzerInconsistencyBuildResponse(ReadOnlyCollection<string> errorMessages) { ErrorMessages = errorMessages; } protected override void AddResponseBody(BinaryWriter writer) { writer.Write(ErrorMessages.Count); foreach (var message in ErrorMessages) { WriteLengthPrefixedString(writer, message); } } public static AnalyzerInconsistencyBuildResponse Create(BinaryReader reader) { var count = reader.ReadInt32(); var list = new List<string>(count); for (var i = 0; i < count; i++) { list.Add(ReadLengthPrefixedString(reader) ?? ""); } return new AnalyzerInconsistencyBuildResponse(new ReadOnlyCollection<string>(list)); } } internal sealed class RejectedBuildResponse : BuildResponse { public string Reason; public override ResponseType Type => ResponseType.Rejected; public RejectedBuildResponse(string reason) { Reason = reason; } protected override void AddResponseBody(BinaryWriter writer) { WriteLengthPrefixedString(writer, Reason); } public static RejectedBuildResponse Create(BinaryReader reader) { var reason = ReadLengthPrefixedString(reader); Debug.Assert(reason is object); return new RejectedBuildResponse(reason); } } // The id numbers below are just random. It's useful to use id numbers // that won't occur accidentally for debugging. internal enum RequestLanguage { CSharpCompile = 0x44532521, VisualBasicCompile = 0x44532522, } /// <summary> /// Constants about the protocol. /// </summary> internal static class BuildProtocolConstants { // Arguments for CSharp and VB Compiler public enum ArgumentId { // The current directory of the client CurrentDirectory = 0x51147221, // A comment line argument. The argument index indicates which one (0 .. N) CommandLineArgument, // The "LIB" environment variable of the client LibEnvVariable, // Request a longer keep alive time for the server KeepAlive, // Request a server shutdown from the client Shutdown, // The directory to use for temporary operations. TempDirectory, } /// <summary> /// Read a string from the Reader where the string is encoded /// as a length prefix (signed 32-bit integer) followed by /// a sequence of characters. /// </summary> public static string? ReadLengthPrefixedString(BinaryReader reader) { var length = reader.ReadInt32(); if (length < 0) { return null; } return new String(reader.ReadChars(length)); } /// <summary> /// Write a string to the Writer where the string is encoded /// as a length prefix (signed 32-bit integer) follows by /// a sequence of characters. /// </summary> public static void WriteLengthPrefixedString(BinaryWriter writer, string? value) { if (value is object) { writer.Write(value.Length); writer.Write(value.ToCharArray()); } else { writer.Write(-1); } } /// <summary> /// Reads the value of <see cref="CommitHashAttribute.Hash"/> of the assembly <see cref="BuildRequest"/> is defined in /// </summary> /// <returns>The hash value of the current assembly or an empty string</returns> public static string? GetCommitHash() { var hashAttributes = typeof(BuildRequest).Assembly.GetCustomAttributes<CommitHashAttribute>(); var hashAttributeCount = hashAttributes.Count(); if (hashAttributeCount != 1) { return null; } return hashAttributes.Single().Hash; } /// <summary> /// This task does not complete until we are completely done reading. /// </summary> internal static async Task ReadAllAsync( Stream stream, byte[] buffer, int count, CancellationToken cancellationToken) { int totalBytesRead = 0; do { int bytesRead = await stream.ReadAsync(buffer, totalBytesRead, count - totalBytesRead, cancellationToken).ConfigureAwait(false); if (bytesRead == 0) { throw new EndOfStreamException("Reached end of stream before end of read."); } totalBytesRead += bytesRead; } while (totalBytesRead < count); } } }
// 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 Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using static Microsoft.CodeAnalysis.CommandLine.BuildProtocolConstants; using static Microsoft.CodeAnalysis.CommandLine.CompilerServerLogger; // This file describes data structures about the protocol from client program to server that is // used. The basic protocol is this. // // After the server pipe is connected, it forks off a thread to handle the connection, and creates // a new instance of the pipe to listen for new clients. When it gets a request, it validates // the security and elevation level of the client. If that fails, it disconnects the client. Otherwise, // it handles the request, sends a response (described by Response class) back to the client, then // disconnects the pipe and ends the thread. namespace Microsoft.CodeAnalysis.CommandLine { /// <summary> /// Represents a request from the client. A request is as follows. /// /// Field Name Type Size (bytes) /// ---------------------------------------------------- /// Length Integer 4 /// RequestId Guid 16 /// Language RequestLanguage 4 /// CompilerHash String Variable /// Argument Count UInteger 4 /// Arguments Argument[] Variable /// /// See <see cref="Argument"/> for the format of an /// Argument. /// /// </summary> internal class BuildRequest { /// <summary> /// The maximum size of a request supported by the compiler server. /// </summary> /// <remarks> /// Currently this limit is 5MB. /// </remarks> private const int MaximumRequestSize = 0x500000; public readonly Guid RequestId; public readonly RequestLanguage Language; public readonly ReadOnlyCollection<Argument> Arguments; public readonly string CompilerHash; public BuildRequest(RequestLanguage language, string compilerHash, IEnumerable<Argument> arguments, Guid? requestId = null) { RequestId = requestId ?? Guid.Empty; Language = language; Arguments = new ReadOnlyCollection<Argument>(arguments.ToList()); CompilerHash = compilerHash; Debug.Assert(!string.IsNullOrWhiteSpace(CompilerHash), "A hash value is required to communicate with the server"); } public static BuildRequest Create(RequestLanguage language, IList<string> args, string workingDirectory, string tempDirectory, string compilerHash, Guid? requestId = null, string? keepAlive = null, string? libDirectory = null) { Debug.Assert(!string.IsNullOrWhiteSpace(compilerHash), "CompilerHash is required to send request to the build server"); var requestLength = args.Count + 1 + (libDirectory == null ? 0 : 1); var requestArgs = new List<Argument>(requestLength); requestArgs.Add(new Argument(ArgumentId.CurrentDirectory, 0, workingDirectory)); requestArgs.Add(new Argument(ArgumentId.TempDirectory, 0, tempDirectory)); if (keepAlive != null) { requestArgs.Add(new Argument(ArgumentId.KeepAlive, 0, keepAlive)); } if (libDirectory != null) { requestArgs.Add(new Argument(ArgumentId.LibEnvVariable, 0, libDirectory)); } for (int i = 0; i < args.Count; ++i) { var arg = args[i]; requestArgs.Add(new Argument(ArgumentId.CommandLineArgument, i, arg)); } return new BuildRequest(language, compilerHash, requestArgs, requestId); } public static BuildRequest CreateShutdown() { var requestArgs = new[] { new Argument(ArgumentId.Shutdown, argumentIndex: 0, value: "") }; return new BuildRequest(RequestLanguage.CSharpCompile, GetCommitHash() ?? "", requestArgs); } /// <summary> /// Read a Request from the given stream. /// /// The total request size must be less than <see cref="MaximumRequestSize"/>. /// </summary> /// <returns>null if the Request was too large, the Request otherwise.</returns> public static async Task<BuildRequest> ReadAsync(Stream inStream, CancellationToken cancellationToken) { // Read the length of the request var lengthBuffer = new byte[4]; await ReadAllAsync(inStream, lengthBuffer, 4, cancellationToken).ConfigureAwait(false); var length = BitConverter.ToInt32(lengthBuffer, 0); // Back out if the request is too large if (length > MaximumRequestSize) { throw new ArgumentException($"Request is over {MaximumRequestSize >> 20}MB in length"); } cancellationToken.ThrowIfCancellationRequested(); // Read the full request var requestBuffer = new byte[length]; await ReadAllAsync(inStream, requestBuffer, length, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); // Parse the request into the Request data structure. using var reader = new BinaryReader(new MemoryStream(requestBuffer), Encoding.Unicode); var requestId = readGuid(reader); var language = (RequestLanguage)reader.ReadUInt32(); var compilerHash = reader.ReadString(); uint argumentCount = reader.ReadUInt32(); var argumentsBuilder = new List<Argument>((int)argumentCount); for (int i = 0; i < argumentCount; i++) { cancellationToken.ThrowIfCancellationRequested(); argumentsBuilder.Add(BuildRequest.Argument.ReadFromBinaryReader(reader)); } return new BuildRequest(language, compilerHash, argumentsBuilder, requestId); static Guid readGuid(BinaryReader reader) { const int size = 16; var bytes = new byte[size]; if (size != reader.Read(bytes, 0, size)) { throw new InvalidOperationException(); } return new Guid(bytes); } } /// <summary> /// Write a Request to the stream. /// </summary> public async Task WriteAsync(Stream outStream, CancellationToken cancellationToken = default(CancellationToken)) { using var memoryStream = new MemoryStream(); using var writer = new BinaryWriter(memoryStream, Encoding.Unicode); writer.Write(RequestId.ToByteArray()); writer.Write((uint)Language); writer.Write(CompilerHash); writer.Write(Arguments.Count); foreach (Argument arg in Arguments) { cancellationToken.ThrowIfCancellationRequested(); arg.WriteToBinaryWriter(writer); } writer.Flush(); cancellationToken.ThrowIfCancellationRequested(); // Write the length of the request int length = checked((int)memoryStream.Length); // Back out if the request is too large if (memoryStream.Length > MaximumRequestSize) { throw new ArgumentOutOfRangeException($"Request is over {MaximumRequestSize >> 20}MB in length"); } await outStream.WriteAsync(BitConverter.GetBytes(length), 0, 4, cancellationToken).ConfigureAwait(false); memoryStream.Position = 0; await memoryStream.CopyToAsync(outStream, bufferSize: length, cancellationToken: cancellationToken).ConfigureAwait(false); } /// <summary> /// A command line argument to the compilation. /// An argument is formatted as follows: /// /// Field Name Type Size (bytes) /// -------------------------------------------------- /// ID UInteger 4 /// Index UInteger 4 /// Value String Variable /// /// Strings are encoded via a length prefix as a signed /// 32-bit integer, followed by an array of characters. /// </summary> public struct Argument { public readonly ArgumentId ArgumentId; public readonly int ArgumentIndex; public readonly string? Value; public Argument(ArgumentId argumentId, int argumentIndex, string? value) { ArgumentId = argumentId; ArgumentIndex = argumentIndex; Value = value; } public static Argument ReadFromBinaryReader(BinaryReader reader) { var argId = (ArgumentId)reader.ReadInt32(); var argIndex = reader.ReadInt32(); string? value = ReadLengthPrefixedString(reader); return new Argument(argId, argIndex, value); } public void WriteToBinaryWriter(BinaryWriter writer) { writer.Write((int)ArgumentId); writer.Write(ArgumentIndex); WriteLengthPrefixedString(writer, Value); } } } /// <summary> /// Base class for all possible responses to a request. /// The ResponseType enum should list all possible response types /// and ReadResponse creates the appropriate response subclass based /// on the response type sent by the client. /// The format of a response is: /// /// Field Name Field Type Size (bytes) /// ------------------------------------------------- /// responseLength int (positive) 4 /// responseType enum ResponseType 4 /// responseBody Response subclass variable /// </summary> internal abstract class BuildResponse { public enum ResponseType { // The client and server are using incompatible protocol versions. MismatchedVersion, // The build request completed on the server and the results are contained // in the message. Completed, // The build request could not be run on the server due because it created // an unresolvable inconsistency with analyzers. AnalyzerInconsistency, // The shutdown request completed and the server process information is // contained in the message. Shutdown, // The request was rejected by the server. Rejected, // The server hash did not match the one supplied by the client IncorrectHash, } public abstract ResponseType Type { get; } public async Task WriteAsync(Stream outStream, CancellationToken cancellationToken) { using (var memoryStream = new MemoryStream()) using (var writer = new BinaryWriter(memoryStream, Encoding.Unicode)) { writer.Write((int)Type); AddResponseBody(writer); writer.Flush(); cancellationToken.ThrowIfCancellationRequested(); // Send the response to the client // Write the length of the response int length = checked((int)memoryStream.Length); // There is no way to know the number of bytes written to // the pipe stream. We just have to assume all of them are written. await outStream.WriteAsync(BitConverter.GetBytes(length), 0, 4, cancellationToken).ConfigureAwait(false); memoryStream.Position = 0; await memoryStream.CopyToAsync(outStream, bufferSize: length, cancellationToken: cancellationToken).ConfigureAwait(false); } } protected abstract void AddResponseBody(BinaryWriter writer); /// <summary> /// May throw exceptions if there are pipe problems. /// </summary> /// <param name="stream"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public static async Task<BuildResponse> ReadAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { // Read the response length var lengthBuffer = new byte[4]; await ReadAllAsync(stream, lengthBuffer, 4, cancellationToken).ConfigureAwait(false); var length = BitConverter.ToUInt32(lengthBuffer, 0); // Read the response var responseBuffer = new byte[length]; await ReadAllAsync(stream, responseBuffer, responseBuffer.Length, cancellationToken).ConfigureAwait(false); using (var reader = new BinaryReader(new MemoryStream(responseBuffer), Encoding.Unicode)) { var responseType = (ResponseType)reader.ReadInt32(); switch (responseType) { case ResponseType.Completed: return CompletedBuildResponse.Create(reader); case ResponseType.MismatchedVersion: return new MismatchedVersionBuildResponse(); case ResponseType.IncorrectHash: return new IncorrectHashBuildResponse(); case ResponseType.AnalyzerInconsistency: return AnalyzerInconsistencyBuildResponse.Create(reader); case ResponseType.Shutdown: return ShutdownBuildResponse.Create(reader); case ResponseType.Rejected: return RejectedBuildResponse.Create(reader); default: throw new InvalidOperationException("Received invalid response type from server."); } } } } /// <summary> /// Represents a Response from the server. A response is as follows. /// /// Field Name Type Size (bytes) /// -------------------------------------------------- /// Length UInteger 4 /// ReturnCode Integer 4 /// Output String Variable /// /// Strings are encoded via a character count prefix as a /// 32-bit integer, followed by an array of characters. /// /// </summary> internal sealed class CompletedBuildResponse : BuildResponse { public readonly int ReturnCode; public readonly bool Utf8Output; public readonly string Output; public CompletedBuildResponse(int returnCode, bool utf8output, string? output) { ReturnCode = returnCode; Utf8Output = utf8output; Output = output ?? string.Empty; } public override ResponseType Type => ResponseType.Completed; public static CompletedBuildResponse Create(BinaryReader reader) { var returnCode = reader.ReadInt32(); var utf8Output = reader.ReadBoolean(); var output = ReadLengthPrefixedString(reader); return new CompletedBuildResponse(returnCode, utf8Output, output); } protected override void AddResponseBody(BinaryWriter writer) { writer.Write(ReturnCode); writer.Write(Utf8Output); WriteLengthPrefixedString(writer, Output); } } internal sealed class ShutdownBuildResponse : BuildResponse { public readonly int ServerProcessId; public ShutdownBuildResponse(int serverProcessId) { ServerProcessId = serverProcessId; } public override ResponseType Type => ResponseType.Shutdown; protected override void AddResponseBody(BinaryWriter writer) { writer.Write(ServerProcessId); } public static ShutdownBuildResponse Create(BinaryReader reader) { var serverProcessId = reader.ReadInt32(); return new ShutdownBuildResponse(serverProcessId); } } internal sealed class MismatchedVersionBuildResponse : BuildResponse { public override ResponseType Type => ResponseType.MismatchedVersion; /// <summary> /// MismatchedVersion has no body. /// </summary> protected override void AddResponseBody(BinaryWriter writer) { } } internal sealed class IncorrectHashBuildResponse : BuildResponse { public override ResponseType Type => ResponseType.IncorrectHash; /// <summary> /// IncorrectHash has no body. /// </summary> protected override void AddResponseBody(BinaryWriter writer) { } } internal sealed class AnalyzerInconsistencyBuildResponse : BuildResponse { public override ResponseType Type => ResponseType.AnalyzerInconsistency; public ReadOnlyCollection<string> ErrorMessages { get; } public AnalyzerInconsistencyBuildResponse(ReadOnlyCollection<string> errorMessages) { ErrorMessages = errorMessages; } protected override void AddResponseBody(BinaryWriter writer) { writer.Write(ErrorMessages.Count); foreach (var message in ErrorMessages) { WriteLengthPrefixedString(writer, message); } } public static AnalyzerInconsistencyBuildResponse Create(BinaryReader reader) { var count = reader.ReadInt32(); var list = new List<string>(count); for (var i = 0; i < count; i++) { list.Add(ReadLengthPrefixedString(reader) ?? ""); } return new AnalyzerInconsistencyBuildResponse(new ReadOnlyCollection<string>(list)); } } internal sealed class RejectedBuildResponse : BuildResponse { public string Reason; public override ResponseType Type => ResponseType.Rejected; public RejectedBuildResponse(string reason) { Reason = reason; } protected override void AddResponseBody(BinaryWriter writer) { WriteLengthPrefixedString(writer, Reason); } public static RejectedBuildResponse Create(BinaryReader reader) { var reason = ReadLengthPrefixedString(reader); Debug.Assert(reason is object); return new RejectedBuildResponse(reason); } } // The id numbers below are just random. It's useful to use id numbers // that won't occur accidentally for debugging. internal enum RequestLanguage { CSharpCompile = 0x44532521, VisualBasicCompile = 0x44532522, } /// <summary> /// Constants about the protocol. /// </summary> internal static class BuildProtocolConstants { // Arguments for CSharp and VB Compiler public enum ArgumentId { // The current directory of the client CurrentDirectory = 0x51147221, // A comment line argument. The argument index indicates which one (0 .. N) CommandLineArgument, // The "LIB" environment variable of the client LibEnvVariable, // Request a longer keep alive time for the server KeepAlive, // Request a server shutdown from the client Shutdown, // The directory to use for temporary operations. TempDirectory, } /// <summary> /// Read a string from the Reader where the string is encoded /// as a length prefix (signed 32-bit integer) followed by /// a sequence of characters. /// </summary> public static string? ReadLengthPrefixedString(BinaryReader reader) { var length = reader.ReadInt32(); if (length < 0) { return null; } return new String(reader.ReadChars(length)); } /// <summary> /// Write a string to the Writer where the string is encoded /// as a length prefix (signed 32-bit integer) follows by /// a sequence of characters. /// </summary> public static void WriteLengthPrefixedString(BinaryWriter writer, string? value) { if (value is object) { writer.Write(value.Length); writer.Write(value.ToCharArray()); } else { writer.Write(-1); } } /// <summary> /// Reads the value of <see cref="CommitHashAttribute.Hash"/> of the assembly <see cref="BuildRequest"/> is defined in /// </summary> /// <returns>The hash value of the current assembly or an empty string</returns> public static string? GetCommitHash() { var hashAttributes = typeof(BuildRequest).Assembly.GetCustomAttributes<CommitHashAttribute>(); var hashAttributeCount = hashAttributes.Count(); if (hashAttributeCount != 1) { return null; } return hashAttributes.Single().Hash; } /// <summary> /// This task does not complete until we are completely done reading. /// </summary> internal static async Task ReadAllAsync( Stream stream, byte[] buffer, int count, CancellationToken cancellationToken) { int totalBytesRead = 0; do { int bytesRead = await stream.ReadAsync(buffer, totalBytesRead, count - totalBytesRead, cancellationToken).ConfigureAwait(false); if (bytesRead == 0) { throw new EndOfStreamException("Reached end of stream before end of read."); } totalBytesRead += bytesRead; } while (totalBytesRead < count); } } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Test/ProjectSystemShim/VisualStudioRuleSetTests.vb
' 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. Imports System.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Roslyn.Test.Utilities Imports IVsAsyncFileChangeEx = Microsoft.VisualStudio.Shell.IVsAsyncFileChangeEx Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim <UseExportProvider> Public Class VisualStudioRuleSetTests Implements IDisposable Private ReadOnly _tempPath As String Public Sub New() _tempPath = Path.Combine(TempRoot.Root, Path.GetRandomFileName()) Directory.CreateDirectory(_tempPath) End Sub Private Sub Dispose() Implements IDisposable.Dispose Directory.Delete(_tempPath, recursive:=True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub SingleFile() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""Warning"" /> </Rules> </RuleSet>" Using workspace = New TestWorkspace() Dim ruleSetPath As String = Path.Combine(_tempPath, "a.ruleset") File.WriteAllText(ruleSetPath, ruleSetSource) Dim fileChangeService = New MockVsFileChangeEx Dim fileChangeWatcher = New FileChangeWatcher(Task.FromResult(Of IVsAsyncFileChangeEx)(fileChangeService)) Dim ruleSetManager = New VisualStudioRuleSetManager(workspace.ExportProvider.GetExportedValue(Of IThreadingContext), fileChangeWatcher, AsynchronousOperationListenerProvider.NullListener) Using visualStudioRuleSet = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) ' Signing up for file change notifications is lazy, so read the rule set to force it. Dim generalDiagnosticOption = visualStudioRuleSet.Target.Value.GetGeneralDiagnosticOption() fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=1, actual:=fileChangeService.WatchedFileCount) End Using fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=0, actual:=fileChangeService.WatchedFileCount) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TwoFiles() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet>" Dim includeSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet>" Dim ruleSetPath As String = Path.Combine(_tempPath, "a.ruleset") File.WriteAllText(ruleSetPath, ruleSetSource) Dim includePath As String = Path.Combine(_tempPath, "file1.ruleset") File.WriteAllText(includePath, includeSource) Using workspace = New TestWorkspace() Dim fileChangeService = New MockVsFileChangeEx Dim fileChangeWatcher = New FileChangeWatcher(Task.FromResult(Of IVsAsyncFileChangeEx)(fileChangeService)) Dim ruleSetManager = New VisualStudioRuleSetManager(workspace.ExportProvider.GetExportedValue(Of IThreadingContext), fileChangeWatcher, AsynchronousOperationListenerProvider.NullListener) Using visualStudioRuleSet = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) ' Signing up for file change notifications is lazy, so read the rule set to force it. Dim generalDiagnosticOption = visualStudioRuleSet.Target.Value.GetGeneralDiagnosticOption() fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=2, actual:=fileChangeService.WatchedFileCount) End Using fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=0, actual:=fileChangeService.WatchedFileCount) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Async Function IncludeUpdated() As Task Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet>" Dim includeSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet>" Dim ruleSetPath As String = Path.Combine(_tempPath, "a.ruleset") File.WriteAllText(ruleSetPath, ruleSetSource) Dim includePath As String = Path.Combine(_tempPath, "file1.ruleset") File.WriteAllText(includePath, includeSource) Using workspace = New TestWorkspace() Dim fileChangeService = New MockVsFileChangeEx Dim fileChangeWatcher = New FileChangeWatcher(Task.FromResult(Of IVsAsyncFileChangeEx)(fileChangeService)) Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider) Dim listener = listenerProvider.GetListener("test") Dim ruleSetManager = New VisualStudioRuleSetManager(workspace.ExportProvider.GetExportedValue(Of IThreadingContext), fileChangeWatcher, listener) Using ruleSet1 = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) Dim handlerCalled As Boolean = False AddHandler ruleSet1.Target.Value.UpdatedOnDisk, Sub() handlerCalled = True ' Signing up for file change notifications is lazy, so read the rule set to force it. Dim generalDiagnosticOption = ruleSet1.Target.Value.GetGeneralDiagnosticOption() fileChangeWatcher.WaitForQueue_TestOnly() fileChangeService.FireUpdate(includePath) Await listenerProvider.GetWaiter("test").ExpeditedWaitAsync() Assert.True(handlerCalled) End Using End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Async Function SameFileRequestedAfterChange() As Task Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""Warning"" /> </Rules> </RuleSet>" Dim ruleSetPath As String = Path.Combine(_tempPath, "a.ruleset") File.WriteAllText(ruleSetPath, ruleSetSource) Using workspace = New TestWorkspace() Dim fileChangeService = New MockVsFileChangeEx Dim fileChangeWatcher = New FileChangeWatcher(Task.FromResult(Of IVsAsyncFileChangeEx)(fileChangeService)) Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider) Dim listener = listenerProvider.GetListener("test") Dim ruleSetManager = New VisualStudioRuleSetManager(workspace.ExportProvider.GetExportedValue(Of IThreadingContext), fileChangeWatcher, listener) Using ruleSet1 = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) ' Signing up for file change notifications is lazy, so read the rule set to force it. Dim generalDiagnosticOption = ruleSet1.Target.Value.GetGeneralDiagnosticOption() fileChangeWatcher.WaitForQueue_TestOnly() fileChangeService.FireUpdate(ruleSetPath) Await listenerProvider.GetWaiter("test").ExpeditedWaitAsync() Using ruleSet2 = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) ' Signing up for file change notifications is lazy, so read the rule set to force it. generalDiagnosticOption = ruleSet2.Target.Value.GetGeneralDiagnosticOption() fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=1, actual:=fileChangeService.WatchedFileCount) Assert.NotSame(ruleSet1.Target, ruleSet2.Target) End Using End Using fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=0, actual:=fileChangeService.WatchedFileCount) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub SameFileRequestedMultipleTimes() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""Warning"" /> </Rules> </RuleSet>" Dim ruleSetPath As String = Path.Combine(_tempPath, "a.ruleset") File.WriteAllText(ruleSetPath, ruleSetSource) Using workspace = New TestWorkspace() Dim fileChangeService = New MockVsFileChangeEx Dim fileChangeWatcher = New FileChangeWatcher(Task.FromResult(Of IVsAsyncFileChangeEx)(fileChangeService)) Dim ruleSetManager = New VisualStudioRuleSetManager(workspace.ExportProvider.GetExportedValue(Of IThreadingContext), fileChangeWatcher, AsynchronousOperationListenerProvider.NullListener) Using ruleSet1 = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) ' Signing up for file change notifications is lazy, so read the rule set to force it. Dim generalDiagnosticOption = ruleSet1.Target.Value.GetGeneralDiagnosticOption() Using ruleSet2 = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=1, actual:=fileChangeService.WatchedFileCount) Assert.Same(ruleSet1.Target, ruleSet2.Target) End Using End Using fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=0, actual:=fileChangeService.WatchedFileCount) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub FileWithError() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""BlahBlahBlah"" /> </Rules> </RuleSet>" Dim ruleSetPath As String = Path.Combine(_tempPath, "a.ruleset") File.WriteAllText(ruleSetPath, ruleSetSource) Using workspace = New TestWorkspace() Dim fileChangeService = New MockVsFileChangeEx Dim fileChangeWatcher = New FileChangeWatcher(Task.FromResult(Of IVsAsyncFileChangeEx)(fileChangeService)) Dim ruleSetManager = New VisualStudioRuleSetManager(workspace.ExportProvider.GetExportedValue(Of IThreadingContext), fileChangeWatcher, AsynchronousOperationListenerProvider.NullListener) Using ruleSet = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) Dim generalDiagnosticOption = ruleSet.Target.Value.GetGeneralDiagnosticOption() fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=ReportDiagnostic.Default, actual:=generalDiagnosticOption) Dim exception = ruleSet.Target.Value.GetException() Assert.NotNull(exception) End Using End Using End Sub End Class End Namespace
' 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. Imports System.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Roslyn.Test.Utilities Imports IVsAsyncFileChangeEx = Microsoft.VisualStudio.Shell.IVsAsyncFileChangeEx Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim <UseExportProvider> Public Class VisualStudioRuleSetTests Implements IDisposable Private ReadOnly _tempPath As String Public Sub New() _tempPath = Path.Combine(TempRoot.Root, Path.GetRandomFileName()) Directory.CreateDirectory(_tempPath) End Sub Private Sub Dispose() Implements IDisposable.Dispose Directory.Delete(_tempPath, recursive:=True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub SingleFile() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""Warning"" /> </Rules> </RuleSet>" Using workspace = New TestWorkspace() Dim ruleSetPath As String = Path.Combine(_tempPath, "a.ruleset") File.WriteAllText(ruleSetPath, ruleSetSource) Dim fileChangeService = New MockVsFileChangeEx Dim fileChangeWatcher = New FileChangeWatcher(Task.FromResult(Of IVsAsyncFileChangeEx)(fileChangeService)) Dim ruleSetManager = New VisualStudioRuleSetManager(workspace.ExportProvider.GetExportedValue(Of IThreadingContext), fileChangeWatcher, AsynchronousOperationListenerProvider.NullListener) Using visualStudioRuleSet = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) ' Signing up for file change notifications is lazy, so read the rule set to force it. Dim generalDiagnosticOption = visualStudioRuleSet.Target.Value.GetGeneralDiagnosticOption() fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=1, actual:=fileChangeService.WatchedFileCount) End Using fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=0, actual:=fileChangeService.WatchedFileCount) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TwoFiles() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet>" Dim includeSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet>" Dim ruleSetPath As String = Path.Combine(_tempPath, "a.ruleset") File.WriteAllText(ruleSetPath, ruleSetSource) Dim includePath As String = Path.Combine(_tempPath, "file1.ruleset") File.WriteAllText(includePath, includeSource) Using workspace = New TestWorkspace() Dim fileChangeService = New MockVsFileChangeEx Dim fileChangeWatcher = New FileChangeWatcher(Task.FromResult(Of IVsAsyncFileChangeEx)(fileChangeService)) Dim ruleSetManager = New VisualStudioRuleSetManager(workspace.ExportProvider.GetExportedValue(Of IThreadingContext), fileChangeWatcher, AsynchronousOperationListenerProvider.NullListener) Using visualStudioRuleSet = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) ' Signing up for file change notifications is lazy, so read the rule set to force it. Dim generalDiagnosticOption = visualStudioRuleSet.Target.Value.GetGeneralDiagnosticOption() fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=2, actual:=fileChangeService.WatchedFileCount) End Using fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=0, actual:=fileChangeService.WatchedFileCount) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Async Function IncludeUpdated() As Task Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet>" Dim includeSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet>" Dim ruleSetPath As String = Path.Combine(_tempPath, "a.ruleset") File.WriteAllText(ruleSetPath, ruleSetSource) Dim includePath As String = Path.Combine(_tempPath, "file1.ruleset") File.WriteAllText(includePath, includeSource) Using workspace = New TestWorkspace() Dim fileChangeService = New MockVsFileChangeEx Dim fileChangeWatcher = New FileChangeWatcher(Task.FromResult(Of IVsAsyncFileChangeEx)(fileChangeService)) Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider) Dim listener = listenerProvider.GetListener("test") Dim ruleSetManager = New VisualStudioRuleSetManager(workspace.ExportProvider.GetExportedValue(Of IThreadingContext), fileChangeWatcher, listener) Using ruleSet1 = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) Dim handlerCalled As Boolean = False AddHandler ruleSet1.Target.Value.UpdatedOnDisk, Sub() handlerCalled = True ' Signing up for file change notifications is lazy, so read the rule set to force it. Dim generalDiagnosticOption = ruleSet1.Target.Value.GetGeneralDiagnosticOption() fileChangeWatcher.WaitForQueue_TestOnly() fileChangeService.FireUpdate(includePath) Await listenerProvider.GetWaiter("test").ExpeditedWaitAsync() Assert.True(handlerCalled) End Using End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Async Function SameFileRequestedAfterChange() As Task Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""Warning"" /> </Rules> </RuleSet>" Dim ruleSetPath As String = Path.Combine(_tempPath, "a.ruleset") File.WriteAllText(ruleSetPath, ruleSetSource) Using workspace = New TestWorkspace() Dim fileChangeService = New MockVsFileChangeEx Dim fileChangeWatcher = New FileChangeWatcher(Task.FromResult(Of IVsAsyncFileChangeEx)(fileChangeService)) Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider) Dim listener = listenerProvider.GetListener("test") Dim ruleSetManager = New VisualStudioRuleSetManager(workspace.ExportProvider.GetExportedValue(Of IThreadingContext), fileChangeWatcher, listener) Using ruleSet1 = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) ' Signing up for file change notifications is lazy, so read the rule set to force it. Dim generalDiagnosticOption = ruleSet1.Target.Value.GetGeneralDiagnosticOption() fileChangeWatcher.WaitForQueue_TestOnly() fileChangeService.FireUpdate(ruleSetPath) Await listenerProvider.GetWaiter("test").ExpeditedWaitAsync() Using ruleSet2 = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) ' Signing up for file change notifications is lazy, so read the rule set to force it. generalDiagnosticOption = ruleSet2.Target.Value.GetGeneralDiagnosticOption() fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=1, actual:=fileChangeService.WatchedFileCount) Assert.NotSame(ruleSet1.Target, ruleSet2.Target) End Using End Using fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=0, actual:=fileChangeService.WatchedFileCount) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub SameFileRequestedMultipleTimes() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""Warning"" /> </Rules> </RuleSet>" Dim ruleSetPath As String = Path.Combine(_tempPath, "a.ruleset") File.WriteAllText(ruleSetPath, ruleSetSource) Using workspace = New TestWorkspace() Dim fileChangeService = New MockVsFileChangeEx Dim fileChangeWatcher = New FileChangeWatcher(Task.FromResult(Of IVsAsyncFileChangeEx)(fileChangeService)) Dim ruleSetManager = New VisualStudioRuleSetManager(workspace.ExportProvider.GetExportedValue(Of IThreadingContext), fileChangeWatcher, AsynchronousOperationListenerProvider.NullListener) Using ruleSet1 = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) ' Signing up for file change notifications is lazy, so read the rule set to force it. Dim generalDiagnosticOption = ruleSet1.Target.Value.GetGeneralDiagnosticOption() Using ruleSet2 = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=1, actual:=fileChangeService.WatchedFileCount) Assert.Same(ruleSet1.Target, ruleSet2.Target) End Using End Using fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=0, actual:=fileChangeService.WatchedFileCount) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub FileWithError() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""BlahBlahBlah"" /> </Rules> </RuleSet>" Dim ruleSetPath As String = Path.Combine(_tempPath, "a.ruleset") File.WriteAllText(ruleSetPath, ruleSetSource) Using workspace = New TestWorkspace() Dim fileChangeService = New MockVsFileChangeEx Dim fileChangeWatcher = New FileChangeWatcher(Task.FromResult(Of IVsAsyncFileChangeEx)(fileChangeService)) Dim ruleSetManager = New VisualStudioRuleSetManager(workspace.ExportProvider.GetExportedValue(Of IThreadingContext), fileChangeWatcher, AsynchronousOperationListenerProvider.NullListener) Using ruleSet = ruleSetManager.GetOrCreateRuleSet(ruleSetPath) Dim generalDiagnosticOption = ruleSet.Target.Value.GetGeneralDiagnosticOption() fileChangeWatcher.WaitForQueue_TestOnly() Assert.Equal(expected:=ReportDiagnostic.Default, actual:=generalDiagnosticOption) Dim exception = ruleSet.Target.Value.GetException() Assert.NotNull(exception) End Using End Using End Sub End Class End Namespace
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/Parser/BlockContexts/StatementBlockContext.vb
' 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. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------- ' Contains the definition of the BlockContext '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class StatementBlockContext Inherits ExecutableStatementContext Friend Sub New(kind As SyntaxKind, statement As StatementSyntax, prevContext As BlockContext) MyBase.New(kind, statement, prevContext) End Sub Friend Overrides Function CreateBlockSyntax(statement As StatementSyntax) As VisualBasicSyntaxNode Dim endStmt As EndBlockStatementSyntax = DirectCast(statement, EndBlockStatementSyntax) Dim result As VisualBasicSyntaxNode Select Case BlockKind Case SyntaxKind.WhileBlock Dim beginStmt As WhileStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.WhileBlock(beginStmt, Body(), endStmt) Case SyntaxKind.WithBlock Dim beginStmt As WithStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.WithBlock(beginStmt, Body(), endStmt) Case SyntaxKind.SyncLockBlock Dim beginStmt As SyncLockStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.SyncLockBlock(beginStmt, Body(), endStmt) Case SyntaxKind.UsingBlock Dim beginStmt As UsingStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.UsingBlock(beginStmt, Body(), endStmt) Case Else Throw ExceptionUtilities.UnexpectedValue(BlockKind) End Select FreeStatements() Return result End Function End Class End Namespace
' 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. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------- ' Contains the definition of the BlockContext '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class StatementBlockContext Inherits ExecutableStatementContext Friend Sub New(kind As SyntaxKind, statement As StatementSyntax, prevContext As BlockContext) MyBase.New(kind, statement, prevContext) End Sub Friend Overrides Function CreateBlockSyntax(statement As StatementSyntax) As VisualBasicSyntaxNode Dim endStmt As EndBlockStatementSyntax = DirectCast(statement, EndBlockStatementSyntax) Dim result As VisualBasicSyntaxNode Select Case BlockKind Case SyntaxKind.WhileBlock Dim beginStmt As WhileStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.WhileBlock(beginStmt, Body(), endStmt) Case SyntaxKind.WithBlock Dim beginStmt As WithStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.WithBlock(beginStmt, Body(), endStmt) Case SyntaxKind.SyncLockBlock Dim beginStmt As SyncLockStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.SyncLockBlock(beginStmt, Body(), endStmt) Case SyntaxKind.UsingBlock Dim beginStmt As UsingStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.UsingBlock(beginStmt, Body(), endStmt) Case Else Throw ExceptionUtilities.UnexpectedValue(BlockKind) End Select FreeStatements() Return result End Function End Class End Namespace
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/CodeAnalysisTest/Collections/DebuggerAttributes.cs
// 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. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Diagnostics/DebuggerAttributes.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UnitTests.Collections { internal class DebuggerAttributeInfo { public object Instance { get; } public IEnumerable<PropertyInfo> Properties { get; } public DebuggerAttributeInfo(object instance, IEnumerable<PropertyInfo> properties) { Instance = instance; Properties = properties; } } internal static class DebuggerAttributes { internal static object? GetFieldValue(object obj, string fieldName) { var fieldInfo = GetField(obj, fieldName) ?? throw new InvalidOperationException(); return fieldInfo.GetValue(obj); } internal static void InvokeDebuggerTypeProxyProperties(object obj) { DebuggerAttributeInfo info = ValidateDebuggerTypeProxyProperties(obj.GetType(), obj); foreach (PropertyInfo pi in info.Properties) { pi.GetValue(info.Instance, null); } } internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(object obj) { return ValidateDebuggerTypeProxyProperties(obj.GetType(), obj); } internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(Type type, object obj) { return ValidateDebuggerTypeProxyProperties(type, type.GenericTypeArguments, obj); } internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(Type type, Type[] genericTypeArguments, object obj) { Type proxyType = GetProxyType(type, genericTypeArguments); // Create an instance of the proxy type, and make sure we can access all of the instance properties // on the type without exception object proxyInstance = Activator.CreateInstance(proxyType, obj) ?? throw ExceptionUtilities.Unreachable; IEnumerable<PropertyInfo> properties = GetDebuggerVisibleProperties(proxyType); return new DebuggerAttributeInfo(proxyInstance, properties); } public static DebuggerBrowsableState? GetDebuggerBrowsableState(MemberInfo info) { CustomAttributeData? debuggerBrowsableAttribute = info.CustomAttributes .SingleOrDefault(a => a.AttributeType == typeof(DebuggerBrowsableAttribute)); // Enums in attribute constructors are boxed as ints, so cast to int? first. return (DebuggerBrowsableState?)(int?)debuggerBrowsableAttribute?.ConstructorArguments.Single().Value; } public static IEnumerable<FieldInfo> GetDebuggerVisibleFields(Type debuggerAttributeType) { // The debugger doesn't evaluate non-public members of type proxies. IEnumerable<FieldInfo> visibleFields = debuggerAttributeType.GetFields() .Where(fi => fi.IsPublic && GetDebuggerBrowsableState(fi) != DebuggerBrowsableState.Never); return visibleFields; } public static IEnumerable<PropertyInfo> GetDebuggerVisibleProperties(Type debuggerAttributeType) { // The debugger doesn't evaluate non-public members of type proxies. GetGetMethod returns null if the getter is non-public. IEnumerable<PropertyInfo> visibleProperties = debuggerAttributeType.GetProperties() .Where(pi => pi.GetGetMethod() != null && GetDebuggerBrowsableState(pi) != DebuggerBrowsableState.Never); return visibleProperties; } public static object? GetProxyObject(object obj) => Activator.CreateInstance(GetProxyType(obj), obj); public static Type GetProxyType(object obj) => GetProxyType(obj.GetType()); public static Type GetProxyType(Type type) => GetProxyType(type, type.GenericTypeArguments); private static Type GetProxyType(Type type, Type[] genericTypeArguments) { // Get the DebuggerTypeProxyAttribute for obj var attrs = type.GetTypeInfo().CustomAttributes .Where(a => a.AttributeType == typeof(DebuggerTypeProxyAttribute)) .ToArray(); if (attrs.Length != 1) { throw new InvalidOperationException($"Expected one DebuggerTypeProxyAttribute on {type}."); } CustomAttributeData cad = attrs[0]; Type? proxyType = cad.ConstructorArguments[0].ArgumentType == typeof(Type) ? (Type?)cad.ConstructorArguments[0].Value : Type.GetType((string)cad.ConstructorArguments[0].Value!); if (proxyType is null) throw new InvalidOperationException("Expected a non-null proxy type"); if (genericTypeArguments.Length > 0) { proxyType = proxyType.MakeGenericType(genericTypeArguments); } return proxyType; } internal static string ValidateDebuggerDisplayReferences(object obj) { // Get the DebuggerDisplayAttribute for obj var objType = obj.GetType(); var attrs = objType.GetTypeInfo().CustomAttributes .Where(a => a.AttributeType == typeof(DebuggerDisplayAttribute)) .ToArray(); if (attrs.Length != 1) { throw new InvalidOperationException($"Expected one DebuggerDisplayAttribute on {objType}."); } var cad = attrs[0]; // Get the text of the DebuggerDisplayAttribute string attrText = (string?)cad.ConstructorArguments[0].Value ?? throw new InvalidOperationException("Expected a non-null text"); var segments = attrText.Split(new[] { '{', '}' }); if (segments.Length % 2 == 0) { throw new InvalidOperationException($"The DebuggerDisplayAttribute for {objType} lacks a closing brace."); } if (segments.Length == 1) { throw new InvalidOperationException($"The DebuggerDisplayAttribute for {objType} doesn't reference any expressions."); } var sb = new StringBuilder(); for (int i = 0; i < segments.Length; i += 2) { string literal = segments[i]; sb.Append(literal); if (i + 1 < segments.Length) { string reference = segments[i + 1]; bool noQuotes = reference.EndsWith(",nq"); reference = reference.Replace(",nq", string.Empty); // Evaluate the reference. if (!TryEvaluateReference(obj, reference, out object? member)) { throw new InvalidOperationException($"The DebuggerDisplayAttribute for {objType} contains the expression \"{reference}\"."); } string? memberString = GetDebuggerMemberString(member, noQuotes); sb.Append(memberString); } } return sb.ToString(); } private static string? GetDebuggerMemberString(object? member, bool noQuotes) { string? memberString = "null"; if (member != null) { memberString = member.ToString(); if (member is string) { if (!noQuotes) { memberString = '"' + memberString + '"'; } } else if (!IsPrimitiveType(member)) { memberString = '{' + memberString + '}'; } } return memberString; } private static bool IsPrimitiveType(object obj) => obj is byte || obj is sbyte || obj is short || obj is ushort || obj is int || obj is uint || obj is long || obj is ulong || obj is float || obj is double; private static bool TryEvaluateReference(object obj, string reference, out object? member) { PropertyInfo? pi = GetProperty(obj, reference); if (pi != null) { member = pi.GetValue(obj); return true; } FieldInfo? fi = GetField(obj, reference); if (fi != null) { member = fi.GetValue(obj); return true; } member = null; return false; } private static FieldInfo? GetField(object obj, string fieldName) { for (Type? t = obj.GetType(); t != null; t = t.GetTypeInfo().BaseType) { FieldInfo? fi = t.GetTypeInfo().GetDeclaredField(fieldName); if (fi != null) { return fi; } } return null; } private static PropertyInfo? GetProperty(object obj, string propertyName) { for (Type? t = obj.GetType(); t != null; t = t.GetTypeInfo().BaseType) { PropertyInfo? pi = t.GetTypeInfo().GetDeclaredProperty(propertyName); if (pi != null) { return pi; } } return null; } } }
// 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. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Diagnostics/DebuggerAttributes.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UnitTests.Collections { internal class DebuggerAttributeInfo { public object Instance { get; } public IEnumerable<PropertyInfo> Properties { get; } public DebuggerAttributeInfo(object instance, IEnumerable<PropertyInfo> properties) { Instance = instance; Properties = properties; } } internal static class DebuggerAttributes { internal static object? GetFieldValue(object obj, string fieldName) { var fieldInfo = GetField(obj, fieldName) ?? throw new InvalidOperationException(); return fieldInfo.GetValue(obj); } internal static void InvokeDebuggerTypeProxyProperties(object obj) { DebuggerAttributeInfo info = ValidateDebuggerTypeProxyProperties(obj.GetType(), obj); foreach (PropertyInfo pi in info.Properties) { pi.GetValue(info.Instance, null); } } internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(object obj) { return ValidateDebuggerTypeProxyProperties(obj.GetType(), obj); } internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(Type type, object obj) { return ValidateDebuggerTypeProxyProperties(type, type.GenericTypeArguments, obj); } internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(Type type, Type[] genericTypeArguments, object obj) { Type proxyType = GetProxyType(type, genericTypeArguments); // Create an instance of the proxy type, and make sure we can access all of the instance properties // on the type without exception object proxyInstance = Activator.CreateInstance(proxyType, obj) ?? throw ExceptionUtilities.Unreachable; IEnumerable<PropertyInfo> properties = GetDebuggerVisibleProperties(proxyType); return new DebuggerAttributeInfo(proxyInstance, properties); } public static DebuggerBrowsableState? GetDebuggerBrowsableState(MemberInfo info) { CustomAttributeData? debuggerBrowsableAttribute = info.CustomAttributes .SingleOrDefault(a => a.AttributeType == typeof(DebuggerBrowsableAttribute)); // Enums in attribute constructors are boxed as ints, so cast to int? first. return (DebuggerBrowsableState?)(int?)debuggerBrowsableAttribute?.ConstructorArguments.Single().Value; } public static IEnumerable<FieldInfo> GetDebuggerVisibleFields(Type debuggerAttributeType) { // The debugger doesn't evaluate non-public members of type proxies. IEnumerable<FieldInfo> visibleFields = debuggerAttributeType.GetFields() .Where(fi => fi.IsPublic && GetDebuggerBrowsableState(fi) != DebuggerBrowsableState.Never); return visibleFields; } public static IEnumerable<PropertyInfo> GetDebuggerVisibleProperties(Type debuggerAttributeType) { // The debugger doesn't evaluate non-public members of type proxies. GetGetMethod returns null if the getter is non-public. IEnumerable<PropertyInfo> visibleProperties = debuggerAttributeType.GetProperties() .Where(pi => pi.GetGetMethod() != null && GetDebuggerBrowsableState(pi) != DebuggerBrowsableState.Never); return visibleProperties; } public static object? GetProxyObject(object obj) => Activator.CreateInstance(GetProxyType(obj), obj); public static Type GetProxyType(object obj) => GetProxyType(obj.GetType()); public static Type GetProxyType(Type type) => GetProxyType(type, type.GenericTypeArguments); private static Type GetProxyType(Type type, Type[] genericTypeArguments) { // Get the DebuggerTypeProxyAttribute for obj var attrs = type.GetTypeInfo().CustomAttributes .Where(a => a.AttributeType == typeof(DebuggerTypeProxyAttribute)) .ToArray(); if (attrs.Length != 1) { throw new InvalidOperationException($"Expected one DebuggerTypeProxyAttribute on {type}."); } CustomAttributeData cad = attrs[0]; Type? proxyType = cad.ConstructorArguments[0].ArgumentType == typeof(Type) ? (Type?)cad.ConstructorArguments[0].Value : Type.GetType((string)cad.ConstructorArguments[0].Value!); if (proxyType is null) throw new InvalidOperationException("Expected a non-null proxy type"); if (genericTypeArguments.Length > 0) { proxyType = proxyType.MakeGenericType(genericTypeArguments); } return proxyType; } internal static string ValidateDebuggerDisplayReferences(object obj) { // Get the DebuggerDisplayAttribute for obj var objType = obj.GetType(); var attrs = objType.GetTypeInfo().CustomAttributes .Where(a => a.AttributeType == typeof(DebuggerDisplayAttribute)) .ToArray(); if (attrs.Length != 1) { throw new InvalidOperationException($"Expected one DebuggerDisplayAttribute on {objType}."); } var cad = attrs[0]; // Get the text of the DebuggerDisplayAttribute string attrText = (string?)cad.ConstructorArguments[0].Value ?? throw new InvalidOperationException("Expected a non-null text"); var segments = attrText.Split(new[] { '{', '}' }); if (segments.Length % 2 == 0) { throw new InvalidOperationException($"The DebuggerDisplayAttribute for {objType} lacks a closing brace."); } if (segments.Length == 1) { throw new InvalidOperationException($"The DebuggerDisplayAttribute for {objType} doesn't reference any expressions."); } var sb = new StringBuilder(); for (int i = 0; i < segments.Length; i += 2) { string literal = segments[i]; sb.Append(literal); if (i + 1 < segments.Length) { string reference = segments[i + 1]; bool noQuotes = reference.EndsWith(",nq"); reference = reference.Replace(",nq", string.Empty); // Evaluate the reference. if (!TryEvaluateReference(obj, reference, out object? member)) { throw new InvalidOperationException($"The DebuggerDisplayAttribute for {objType} contains the expression \"{reference}\"."); } string? memberString = GetDebuggerMemberString(member, noQuotes); sb.Append(memberString); } } return sb.ToString(); } private static string? GetDebuggerMemberString(object? member, bool noQuotes) { string? memberString = "null"; if (member != null) { memberString = member.ToString(); if (member is string) { if (!noQuotes) { memberString = '"' + memberString + '"'; } } else if (!IsPrimitiveType(member)) { memberString = '{' + memberString + '}'; } } return memberString; } private static bool IsPrimitiveType(object obj) => obj is byte || obj is sbyte || obj is short || obj is ushort || obj is int || obj is uint || obj is long || obj is ulong || obj is float || obj is double; private static bool TryEvaluateReference(object obj, string reference, out object? member) { PropertyInfo? pi = GetProperty(obj, reference); if (pi != null) { member = pi.GetValue(obj); return true; } FieldInfo? fi = GetField(obj, reference); if (fi != null) { member = fi.GetValue(obj); return true; } member = null; return false; } private static FieldInfo? GetField(object obj, string fieldName) { for (Type? t = obj.GetType(); t != null; t = t.GetTypeInfo().BaseType) { FieldInfo? fi = t.GetTypeInfo().GetDeclaredField(fieldName); if (fi != null) { return fi; } } return null; } private static PropertyInfo? GetProperty(object obj, string propertyName) { for (Type? t = obj.GetType(); t != null; t = t.GetTypeInfo().BaseType) { PropertyInfo? pi = t.GetTypeInfo().GetDeclaredProperty(propertyName); if (pi != null) { return pi; } } return null; } } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/CodeActions/Annotations/ConflictAnnotation.cs
// 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. namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// Apply this annotation to a SyntaxNode to indicate a conflict may exist that requires user understanding and acknowledgment before taking action. /// </summary> public static class ConflictAnnotation { public const string Kind = "CodeAction_Conflict"; public static SyntaxAnnotation Create(string description) => new(Kind, description); public static string? GetDescription(SyntaxAnnotation annotation) => annotation.Data; } }
// 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. namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// Apply this annotation to a SyntaxNode to indicate a conflict may exist that requires user understanding and acknowledgment before taking action. /// </summary> public static class ConflictAnnotation { public const string Kind = "CodeAction_Conflict"; public static SyntaxAnnotation Create(string description) => new(Kind, description); public static string? GetDescription(SyntaxAnnotation annotation) => annotation.Data; } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Test/CodeModel/MethodXML/MethodXMLTests_CSQuotes.vb
' 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. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.MethodXML Partial Public Class MethodXMLTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSQuotes_ForLoopAndComments() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { // Goo int i = 0; // comment after local // hello comment! for (int i = 0; i &lt; 10; i++) // Goo { } // Goo2 // Goo3 } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Int32</Type> <Name>i</Name> <Expression> <Literal> <Number type="System.Int32">0</Number> </Literal> </Expression> </Local> <Comment> hello comment!</Comment> <Quote line="7">for (int i = 0; i &lt; 10; i++) // Goo { }</Quote> <Comment> Goo3</Comment> </Block> Test(definition, expected) End Sub End Class End Namespace
' 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. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.MethodXML Partial Public Class MethodXMLTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSQuotes_ForLoopAndComments() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { // Goo int i = 0; // comment after local // hello comment! for (int i = 0; i &lt; 10; i++) // Goo { } // Goo2 // Goo3 } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Int32</Type> <Name>i</Name> <Expression> <Literal> <Number type="System.Int32">0</Number> </Literal> </Expression> </Local> <Comment> hello comment!</Comment> <Quote line="7">for (int i = 0; i &lt; 10; i++) // Goo { }</Quote> <Comment> Goo3</Comment> </Block> Test(definition, expected) End Sub End Class End Namespace
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest2/Recommendations/InterfaceKeywordRecommenderTests.cs
// 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class InterfaceKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPartial() { await VerifyKeywordAsync( @"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealedPublic() => await VerifyAbsenceAsync(@"sealed public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInterface() => await VerifyAbsenceAsync(@"interface $$"); } }
// 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class InterfaceKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPartial() { await VerifyKeywordAsync( @"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealedPublic() => await VerifyAbsenceAsync(@"sealed public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInterface() => await VerifyAbsenceAsync(@"interface $$"); } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Test/Venus/DocumentService_IntegrationTests.vb
' 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. Imports System.Collections.Immutable Imports System.ComponentModel.Composition Imports System.Threading Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Media Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.CSharp.Syntax Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.FindUsages Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.LanguageServices.CodeLens Imports Microsoft.VisualStudio.LanguageServices.FindUsages Imports Microsoft.VisualStudio.OLE.Interop Imports Microsoft.VisualStudio.Shell Imports Microsoft.VisualStudio.Shell.FindAllReferences Imports Microsoft.VisualStudio.Shell.TableControl Imports Microsoft.VisualStudio.Shell.TableManager Imports Microsoft.VisualStudio.Text Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus <UseExportProvider> Public Class DocumentService_IntegrationTests Private Shared ReadOnly s_compositionWithMockDiagnosticUpdateSourceRegistrationService As TestComposition = EditorTestCompositions.EditorFeatures _ .AddExcludedPartTypes(GetType(IDiagnosticUpdateSourceRegistrationService)) _ .AddParts(GetType(MockDiagnosticUpdateSourceRegistrationService)) <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestFindUsageIntegration() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class {|Original:C|} { [|C|]$$ c; } </Document> <Document FilePath="Mapped.cs"> class {|Definition:C1|} { [|C1|] c; }reference </Document> </Project> </Workspace> ' TODO: Use VisualStudioTestComposition or move the feature down to EditorFeatures and avoid dependency on IServiceProvider. ' https://github.com/dotnet/roslyn/issues/46279 Dim composition = EditorTestCompositions.EditorFeatures.AddParts(GetType(MockServiceProvider)) Using workspace = TestWorkspace.Create(input, composition:=composition, documentServiceProvider:=TestDocumentServiceProvider.Instance) Dim presenter = New StreamingFindUsagesPresenter(workspace, workspace.ExportProvider.AsExportProvider()) Dim tuple = presenter.StartSearch("test", supportsReferences:=True) Dim context = tuple.context Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim startDocument = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Assert.NotNull(startDocument) Dim findRefsService = startDocument.GetLanguageService(Of IFindUsagesService) Await findRefsService.FindReferencesAsync(startDocument, cursorPosition, context, CancellationToken.None) Dim definitionDocument = workspace.Documents.First(Function(d) d.AnnotatedSpans.ContainsKey("Definition")) Dim definitionText = Await workspace.CurrentSolution.GetDocument(definitionDocument.Id).GetTextAsync() Dim definitionSpan = definitionDocument.AnnotatedSpans("Definition").Single() Dim referenceSpan = definitionDocument.SelectedSpans.First() Dim expected = { (definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(definitionSpan).Start, definitionText.Lines.GetLineFromPosition(definitionSpan.Start).ToString().Trim()), (definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString().Trim())} Dim factory = TestFindAllReferencesService.Instance.LastWindow.MyTableManager.LastSink.LastFactory Dim snapshot = factory.GetCurrentSnapshot() Dim actual = New List(Of (String, LinePosition, String)) For i = 0 To snapshot.Count - 1 Dim name As Object = Nothing Dim line As Object = Nothing Dim position As Object = Nothing Dim content As Object = Nothing Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.DocumentName, name)) Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.Line, line)) Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.Column, position)) Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.Text, content)) actual.Add((DirectCast(name, String), New LinePosition(CType(line, Integer), CType(position, Integer)), DirectCast(content, String))) Next ' confirm that all FAR results are mapped to ones in mapped.cs file rather than ones in original.cs AssertEx.SetEqual(expected, actual) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCodeLensIntegration() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class {|Original:C|} { [|C|] c { get; }; } </Document> <Document FilePath="Mapped.cs"> class {|Definition:C1|} { [|C1|] c { get; }; }reference </Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, documentServiceProvider:=TestDocumentServiceProvider.Instance) Dim codelensService = New RemoteCodeLensReferencesService() Dim originalDocument = workspace.Documents.First(Function(d) d.AnnotatedSpans.ContainsKey("Original")) Dim startDocument = workspace.CurrentSolution.GetDocument(originalDocument.Id) Assert.NotNull(startDocument) Dim root = Await startDocument.GetSyntaxRootAsync() Dim node = root.FindNode(originalDocument.AnnotatedSpans("Original").First()).AncestorsAndSelf().OfType(Of ClassDeclarationSyntax).First() Dim results = Await codelensService.FindReferenceLocationsAsync(workspace.CurrentSolution, startDocument.Id, node, CancellationToken.None) Assert.True(results.HasValue) Dim definitionDocument = workspace.Documents.First(Function(d) d.AnnotatedSpans.ContainsKey("Definition")) Dim definitionText = Await workspace.CurrentSolution.GetDocument(definitionDocument.Id).GetTextAsync() Dim referenceSpan = definitionDocument.SelectedSpans.First() Dim expected = {(definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString())} Dim actual = New List(Of (String, LinePosition, String)) For Each result In results.Value actual.Add((result.FilePath, New LinePosition(result.LineNumber, result.ColumnNumber), result.ReferenceLineText)) Next ' confirm that all FAR results are mapped to ones in mapped.cs file rather than ones in original.cs AssertEx.SetEqual(expected, actual) End Using End Function <InlineData(True)> <InlineData(False)> <WpfTheory, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestDocumentOperationCanApplyChange(ignoreUnchangeableDocuments As Boolean) As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class C { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, documentServiceProvider:=TestDocumentServiceProvider.Instance, ignoreUnchangeableDocumentsWhenApplyingChanges:=ignoreUnchangeableDocuments) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) ' made a change Dim newDocument = document.WithText(SourceText.From("")) ' confirm the change Assert.Equal(String.Empty, (Await newDocument.GetTextAsync()).ToString()) ' confirm apply changes are not supported Assert.False(document.CanApplyChange()) Assert.Equal(ignoreUnchangeableDocuments, workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges) ' see whether changes can be applied to the solution If ignoreUnchangeableDocuments Then Assert.True(workspace.TryApplyChanges(newDocument.Project.Solution)) ' Changes should not be made if Workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges is true Dim currentDocument = workspace.CurrentSolution.GetDocument(document.Id) Assert.True(currentDocument.GetTextSynchronously(CancellationToken.None).ContentEquals(document.GetTextSynchronously(CancellationToken.None))) Else ' should throw if Workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges is false Assert.Throws(Of NotSupportedException)(Sub() workspace.TryApplyChanges(newDocument.Project.Solution)) End If End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestDocumentOperationCanApplySupportDiagnostics() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, composition:=s_compositionWithMockDiagnosticUpdateSourceRegistrationService, documentServiceProvider:=TestDocumentServiceProvider.Instance) Dim analyzerReference = New TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()) workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences({analyzerReference})) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) Dim model = Await document.GetSemanticModelAsync() ' confirm there are errors Assert.True(model.GetDiagnostics().Any()) Assert.IsType(Of MockDiagnosticUpdateSourceRegistrationService)(workspace.GetService(Of IDiagnosticUpdateSourceRegistrationService)()) Dim diagnosticService = Assert.IsType(Of DiagnosticAnalyzerService)(workspace.GetService(Of IDiagnosticAnalyzerService)()) ' confirm diagnostic support is off for the document Assert.False(document.SupportsDiagnostics()) ' register the workspace to the service diagnosticService.CreateIncrementalAnalyzer(workspace) ' confirm that IDE doesn't report the diagnostics Dim diagnostics = Await diagnosticService.GetDiagnosticsAsync(workspace.CurrentSolution, documentId:=document.Id) Assert.False(diagnostics.Any()) End Using End Function Private Class TestDocumentServiceProvider Implements IDocumentServiceProvider Public Shared ReadOnly Instance As TestDocumentServiceProvider = New TestDocumentServiceProvider() Public Function GetService(Of TService As {Class, IDocumentService})() As TService Implements IDocumentServiceProvider.GetService If TypeOf SpanMapper.Instance Is TService Then Return TryCast(SpanMapper.Instance, TService) ElseIf TypeOf Excerpter.Instance Is TService Then Return TryCast(Excerpter.Instance, TService) ElseIf TypeOf DocumentOperations.Instance Is TService Then Return TryCast(DocumentOperations.Instance, TService) End If Return Nothing End Function Private Class SpanMapper Implements ISpanMappingService Public Shared ReadOnly Instance As SpanMapper = New SpanMapper() Public ReadOnly Property SupportsMappingImportDirectives As Boolean = False Implements ISpanMappingService.SupportsMappingImportDirectives Public Async Function MapSpansAsync(document As Document, spans As IEnumerable(Of TextSpan), cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of MappedSpanResult)) Implements ISpanMappingService.MapSpansAsync Dim testWorkspace = DirectCast(document.Project.Solution.Workspace, TestWorkspace) Dim testDocument = testWorkspace.GetTestDocument(document.Id) Dim mappedTestDocument = testWorkspace.Documents.First(Function(d) d.Id <> testDocument.Id) Dim mappedDocument = testWorkspace.CurrentSolution.GetDocument(mappedTestDocument.Id) Dim mappedSource = Await mappedDocument.GetTextAsync(cancellationToken).ConfigureAwait(False) Dim results = New List(Of MappedSpanResult) For Each span In spans If testDocument.AnnotatedSpans("Original").First() = span Then Dim mappedSpan = mappedTestDocument.AnnotatedSpans("Definition").First() Dim lineSpan = mappedSource.Lines.GetLinePositionSpan(mappedSpan) results.Add(New MappedSpanResult(mappedDocument.FilePath, lineSpan, mappedSpan)) ElseIf testDocument.SelectedSpans.First() = span Then Dim mappedSpan = mappedTestDocument.SelectedSpans.First() Dim lineSpan = mappedSource.Lines.GetLinePositionSpan(mappedSpan) results.Add(New MappedSpanResult(mappedDocument.FilePath, lineSpan, mappedSpan)) Else Throw New Exception("shouldn't reach here") End If Next Return results.ToImmutableArray() End Function Public Function GetMappedTextChangesAsync(oldDocument As Document, newDocument As Document, cancellationToken As CancellationToken) _ As Task(Of ImmutableArray(Of (mappedFilePath As String, mappedTextChange As Microsoft.CodeAnalysis.Text.TextChange))) _ Implements ISpanMappingService.GetMappedTextChangesAsync Throw New NotImplementedException() End Function End Class Private Class Excerpter Implements IDocumentExcerptService Public Shared ReadOnly Instance As Excerpter = New Excerpter() Public Async Function TryExcerptAsync(document As Document, span As TextSpan, mode As ExcerptMode, cancellationToken As CancellationToken) As Task(Of ExcerptResult?) Implements IDocumentExcerptService.TryExcerptAsync Dim testWorkspace = DirectCast(document.Project.Solution.Workspace, TestWorkspace) Dim testDocument = testWorkspace.GetTestDocument(document.Id) Dim mappedTestDocument = testWorkspace.Documents.First(Function(d) d.Id <> testDocument.Id) Dim mappedDocument = testWorkspace.CurrentSolution.GetDocument(mappedTestDocument.Id) Dim mappedSource = Await mappedDocument.GetTextAsync(cancellationToken).ConfigureAwait(False) Dim mappedSpan As TextSpan If testDocument.AnnotatedSpans("Original").First() = span Then mappedSpan = mappedTestDocument.AnnotatedSpans("Definition").First() ElseIf testDocument.SelectedSpans.First() = span Then mappedSpan = mappedTestDocument.SelectedSpans.First() Else Throw New Exception("shouldn't reach here") End If Dim line = mappedSource.Lines.GetLineFromPosition(mappedSpan.Start) Return New ExcerptResult(mappedSource.GetSubText(line.Span), New TextSpan(mappedSpan.Start - line.Start, mappedSpan.Length), ImmutableArray.Create(New ClassifiedSpan(New TextSpan(0, line.Span.Length), ClassificationTypeNames.Text)), document, span) End Function End Class Private Class DocumentOperations Implements IDocumentOperationService Public Shared ReadOnly Instance As DocumentOperations = New DocumentOperations() Public ReadOnly Property CanApplyChange As Boolean Implements IDocumentOperationService.CanApplyChange Get Return False End Get End Property Public ReadOnly Property SupportDiagnostics As Boolean Implements IDocumentOperationService.SupportDiagnostics Get Return False End Get End Property End Class End Class <PartNotDiscoverable> <Export(GetType(SVsServiceProvider))> Private Class MockServiceProvider Implements SVsServiceProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function GetService(serviceType As Type) As Object Implements SVsServiceProvider.GetService If GetType(SVsFindAllReferences) = serviceType Then Return TestFindAllReferencesService.Instance End If Return Nothing End Function End Class Private Class TestFindAllReferencesService Implements IFindAllReferencesService Public Shared ReadOnly Instance As TestFindAllReferencesService = New TestFindAllReferencesService() ' this mock is not thread-safe. don't use it concurrently Public LastWindow As FindAllReferencesWindow Public Function StartSearch(label As String) As IFindAllReferencesWindow Implements IFindAllReferencesService.StartSearch LastWindow = New FindAllReferencesWindow(label) Return LastWindow End Function End Class Private Class FindAllReferencesWindow Implements IFindAllReferencesWindow Public ReadOnly Label As String Public ReadOnly MyTableControl As WpfTableControl = New WpfTableControl() Public ReadOnly MyTableManager As TableManager = New TableManager() Public Sub New(label As String) Me.Label = label End Sub Public ReadOnly Property TableControl As IWpfTableControl Implements IFindAllReferencesWindow.TableControl Get Return MyTableControl End Get End Property Public ReadOnly Property Manager As ITableManager Implements IFindAllReferencesWindow.Manager Get Return MyTableManager End Get End Property Public Property Title As String Implements IFindAllReferencesWindow.Title Public Event Closed As EventHandler Implements IFindAllReferencesWindow.Closed #Region "Not Implemented" Public Sub AddCommandTarget(target As IOleCommandTarget, ByRef [next] As IOleCommandTarget) Implements IFindAllReferencesWindow.AddCommandTarget Throw New NotImplementedException() End Sub #End Region Public Sub SetProgress(progress As Double) Implements IFindAllReferencesWindow.SetProgress End Sub Public Sub SetProgress(completed As Integer, maximum As Integer) Implements IFindAllReferencesWindow.SetProgress End Sub End Class Private Class TableDataSink Implements ITableDataSink ' not thread safe. it should never be used concurrently Public LastFactory As ITableEntriesSnapshotFactory Public Property IsStable As Boolean Implements ITableDataSink.IsStable Public Sub AddFactory(newFactory As ITableEntriesSnapshotFactory, Optional removeAllFactories As Boolean = False) Implements ITableDataSink.AddFactory LastFactory = newFactory End Sub Public Sub FactorySnapshotChanged(factory As ITableEntriesSnapshotFactory) Implements ITableDataSink.FactorySnapshotChanged LastFactory = factory End Sub #Region "Not Implemented" Public Sub AddEntries(newEntries As IReadOnlyList(Of ITableEntry), Optional removeAllEntries As Boolean = False) Implements ITableDataSink.AddEntries Throw New NotImplementedException() End Sub Public Sub RemoveEntries(oldEntries As IReadOnlyList(Of ITableEntry)) Implements ITableDataSink.RemoveEntries Throw New NotImplementedException() End Sub Public Sub ReplaceEntries(oldEntries As IReadOnlyList(Of ITableEntry), newEntries As IReadOnlyList(Of ITableEntry)) Implements ITableDataSink.ReplaceEntries Throw New NotImplementedException() End Sub Public Sub RemoveAllEntries() Implements ITableDataSink.RemoveAllEntries Throw New NotImplementedException() End Sub Public Sub AddSnapshot(newSnapshot As ITableEntriesSnapshot, Optional removeAllSnapshots As Boolean = False) Implements ITableDataSink.AddSnapshot Throw New NotImplementedException() End Sub Public Sub RemoveSnapshot(oldSnapshot As ITableEntriesSnapshot) Implements ITableDataSink.RemoveSnapshot Throw New NotImplementedException() End Sub Public Sub RemoveAllSnapshots() Implements ITableDataSink.RemoveAllSnapshots Throw New NotImplementedException() End Sub Public Sub ReplaceSnapshot(oldSnapshot As ITableEntriesSnapshot, newSnapshot As ITableEntriesSnapshot) Implements ITableDataSink.ReplaceSnapshot Throw New NotImplementedException() End Sub Public Sub RemoveFactory(oldFactory As ITableEntriesSnapshotFactory) Implements ITableDataSink.RemoveFactory Throw New NotImplementedException() End Sub Public Sub ReplaceFactory(oldFactory As ITableEntriesSnapshotFactory, newFactory As ITableEntriesSnapshotFactory) Implements ITableDataSink.ReplaceFactory Throw New NotImplementedException() End Sub Public Sub RemoveAllFactories() Implements ITableDataSink.RemoveAllFactories Throw New NotImplementedException() End Sub #End Region End Class Private Class TableManager Implements ITableManager Private ReadOnly _sources As List(Of ITableDataSource) = New List(Of ITableDataSource)() Public LastSink As TableDataSink Public ReadOnly Property Identifier As String Implements ITableManager.Identifier Get Return "Test" End Get End Property Public ReadOnly Property Sources As IReadOnlyList(Of ITableDataSource) Implements ITableManager.Sources Get Return _sources End Get End Property Public Event SourcesChanged As EventHandler Implements ITableManager.SourcesChanged Public Function AddSource(source As ITableDataSource, ParamArray columns() As String) As Boolean Implements ITableManager.AddSource Return AddSource(source, columns.ToImmutableArray()) End Function Public Function AddSource(source As ITableDataSource, columns As IReadOnlyCollection(Of String)) As Boolean Implements ITableManager.AddSource LastSink = New TableDataSink() source.Subscribe(LastSink) _sources.Add(source) Return True End Function Public Function RemoveSource(source As ITableDataSource) As Boolean Implements ITableManager.RemoveSource Return _sources.Remove(source) End Function #Region "Not Implemented" Public Function GetColumnsForSources(sources As IEnumerable(Of ITableDataSource)) As IReadOnlyList(Of String) Implements ITableManager.GetColumnsForSources Throw New NotImplementedException() End Function #End Region End Class Private Class WpfTableControl Implements IWpfTableControl2 Public Event GroupingsChanged As EventHandler Implements IWpfTableControl2.GroupingsChanged Private _states As List(Of ColumnState) = New List(Of ColumnState)({New ColumnState2(StandardTableColumnDefinitions2.Definition, isVisible:=True, width:=10)}) Public ReadOnly Property ColumnStates As IReadOnlyList(Of ColumnState) Implements IWpfTableControl.ColumnStates Get Return _states End Get End Property Public Sub SetColumnStates(states As IEnumerable(Of ColumnState)) Implements IWpfTableControl2.SetColumnStates _states = states.ToList() End Sub Public ReadOnly Property ColumnDefinitionManager As ITableColumnDefinitionManager Implements IWpfTableControl.ColumnDefinitionManager Get Return Nothing End Get End Property #Region "Not Implemented" Public ReadOnly Property IsDataStable As Boolean Implements IWpfTableControl2.IsDataStable Get Throw New NotImplementedException() End Get End Property Public Property NavigationBehavior As TableEntryNavigationBehavior Implements IWpfTableControl2.NavigationBehavior Get Throw New NotImplementedException() End Get Set(value As TableEntryNavigationBehavior) Throw New NotImplementedException() End Set End Property Public Property KeepSelectionInView As Boolean Implements IWpfTableControl2.KeepSelectionInView Get Throw New NotImplementedException() End Get Set(value As Boolean) Throw New NotImplementedException() End Set End Property Public Property ShowGroupingLine As Boolean Implements IWpfTableControl2.ShowGroupingLine Get Throw New NotImplementedException() End Get Set(value As Boolean) Throw New NotImplementedException() End Set End Property Public Property RaiseDataUnstableChangeDelay As TimeSpan Implements IWpfTableControl2.RaiseDataUnstableChangeDelay Get Throw New NotImplementedException() End Get Set(value As TimeSpan) Throw New NotImplementedException() End Set End Property Public Property SelectedItemActiveBackground As Brush Implements IWpfTableControl2.SelectedItemActiveBackground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public Property SelectedItemActiveForeground As Brush Implements IWpfTableControl2.SelectedItemActiveForeground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public Property SelectedItemInactiveBackground As Brush Implements IWpfTableControl2.SelectedItemInactiveBackground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public Property SelectedItemInactiveForeground As Brush Implements IWpfTableControl2.SelectedItemInactiveForeground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public ReadOnly Property Manager As ITableManager Implements IWpfTableControl.Manager Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property Control As FrameworkElement Implements IWpfTableControl.Control Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property AutoSubscribe As Boolean Implements IWpfTableControl.AutoSubscribe Get Throw New NotImplementedException() End Get End Property Public Property SortFunction As Comparison(Of ITableEntryHandle) Implements IWpfTableControl.SortFunction Get Throw New NotImplementedException() End Get Set(value As Comparison(Of ITableEntryHandle)) Throw New NotImplementedException() End Set End Property Public Property SelectionMode As SelectionMode Implements IWpfTableControl.SelectionMode Get Throw New NotImplementedException() End Get Set(value As SelectionMode) Throw New NotImplementedException() End Set End Property Public ReadOnly Property Entries As IEnumerable(Of ITableEntryHandle) Implements IWpfTableControl.Entries Get Throw New NotImplementedException() End Get End Property Public Property SelectedEntries As IEnumerable(Of ITableEntryHandle) Implements IWpfTableControl.SelectedEntries Get Throw New NotImplementedException() End Get Set(value As IEnumerable(Of ITableEntryHandle)) Throw New NotImplementedException() End Set End Property Public ReadOnly Property SelectedEntry As ITableEntryHandle Implements IWpfTableControl.SelectedEntry Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property SelectedOrFirstEntry As ITableEntryHandle Implements IWpfTableControl.SelectedOrFirstEntry Get Throw New NotImplementedException() End Get End Property Public Event DataStabilityChanged As EventHandler Implements IWpfTableControl2.DataStabilityChanged Public Event FiltersChanged As EventHandler(Of FiltersChangedEventArgs) Implements IWpfTableControl.FiltersChanged Public Event PreEntriesChanged As EventHandler Implements IWpfTableControl.PreEntriesChanged Public Event EntriesChanged As EventHandler(Of EntriesChangedEventArgs) Implements IWpfTableControl.EntriesChanged Public Sub SubscribeToDataSource(source As ITableDataSource) Implements IWpfTableControl.SubscribeToDataSource Throw New NotImplementedException() End Sub Public Sub SelectAll() Implements IWpfTableControl.SelectAll Throw New NotImplementedException() End Sub Public Sub UnselectAll() Implements IWpfTableControl.UnselectAll Throw New NotImplementedException() End Sub Public Sub RefreshUI() Implements IWpfTableControl.RefreshUI Throw New NotImplementedException() End Sub Public Function GetAllFilters() As IEnumerable(Of Tuple(Of String, IEntryFilter)) Implements IWpfTableControl2.GetAllFilters Throw New NotImplementedException() End Function Public Function UnsubscribeFromDataSource(source As ITableDataSource) As Boolean Implements IWpfTableControl.UnsubscribeFromDataSource Throw New NotImplementedException() End Function Public Function SetFilter(key As String, newFilter As IEntryFilter) As IEntryFilter Implements IWpfTableControl.SetFilter Throw New NotImplementedException() End Function Public Function GetFilter(key As String) As IEntryFilter Implements IWpfTableControl.GetFilter Throw New NotImplementedException() End Function Public Function ForceUpdateAsync() As Task(Of EntriesChangedEventArgs) Implements IWpfTableControl.ForceUpdateAsync Throw New NotImplementedException() End Function Public Sub Dispose() Implements IDisposable.Dispose End Sub #End Region End Class End Class End Namespace
' 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. Imports System.Collections.Immutable Imports System.ComponentModel.Composition Imports System.Threading Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Media Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.CSharp.Syntax Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.FindUsages Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.LanguageServices.CodeLens Imports Microsoft.VisualStudio.LanguageServices.FindUsages Imports Microsoft.VisualStudio.OLE.Interop Imports Microsoft.VisualStudio.Shell Imports Microsoft.VisualStudio.Shell.FindAllReferences Imports Microsoft.VisualStudio.Shell.TableControl Imports Microsoft.VisualStudio.Shell.TableManager Imports Microsoft.VisualStudio.Text Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus <UseExportProvider> Public Class DocumentService_IntegrationTests Private Shared ReadOnly s_compositionWithMockDiagnosticUpdateSourceRegistrationService As TestComposition = EditorTestCompositions.EditorFeatures _ .AddExcludedPartTypes(GetType(IDiagnosticUpdateSourceRegistrationService)) _ .AddParts(GetType(MockDiagnosticUpdateSourceRegistrationService)) <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestFindUsageIntegration() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class {|Original:C|} { [|C|]$$ c; } </Document> <Document FilePath="Mapped.cs"> class {|Definition:C1|} { [|C1|] c; }reference </Document> </Project> </Workspace> ' TODO: Use VisualStudioTestComposition or move the feature down to EditorFeatures and avoid dependency on IServiceProvider. ' https://github.com/dotnet/roslyn/issues/46279 Dim composition = EditorTestCompositions.EditorFeatures.AddParts(GetType(MockServiceProvider)) Using workspace = TestWorkspace.Create(input, composition:=composition, documentServiceProvider:=TestDocumentServiceProvider.Instance) Dim presenter = New StreamingFindUsagesPresenter(workspace, workspace.ExportProvider.AsExportProvider()) Dim tuple = presenter.StartSearch("test", supportsReferences:=True) Dim context = tuple.context Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim startDocument = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Assert.NotNull(startDocument) Dim findRefsService = startDocument.GetLanguageService(Of IFindUsagesService) Await findRefsService.FindReferencesAsync(startDocument, cursorPosition, context, CancellationToken.None) Dim definitionDocument = workspace.Documents.First(Function(d) d.AnnotatedSpans.ContainsKey("Definition")) Dim definitionText = Await workspace.CurrentSolution.GetDocument(definitionDocument.Id).GetTextAsync() Dim definitionSpan = definitionDocument.AnnotatedSpans("Definition").Single() Dim referenceSpan = definitionDocument.SelectedSpans.First() Dim expected = { (definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(definitionSpan).Start, definitionText.Lines.GetLineFromPosition(definitionSpan.Start).ToString().Trim()), (definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString().Trim())} Dim factory = TestFindAllReferencesService.Instance.LastWindow.MyTableManager.LastSink.LastFactory Dim snapshot = factory.GetCurrentSnapshot() Dim actual = New List(Of (String, LinePosition, String)) For i = 0 To snapshot.Count - 1 Dim name As Object = Nothing Dim line As Object = Nothing Dim position As Object = Nothing Dim content As Object = Nothing Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.DocumentName, name)) Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.Line, line)) Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.Column, position)) Assert.True(snapshot.TryGetValue(i, StandardTableKeyNames.Text, content)) actual.Add((DirectCast(name, String), New LinePosition(CType(line, Integer), CType(position, Integer)), DirectCast(content, String))) Next ' confirm that all FAR results are mapped to ones in mapped.cs file rather than ones in original.cs AssertEx.SetEqual(expected, actual) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCodeLensIntegration() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class {|Original:C|} { [|C|] c { get; }; } </Document> <Document FilePath="Mapped.cs"> class {|Definition:C1|} { [|C1|] c { get; }; }reference </Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, documentServiceProvider:=TestDocumentServiceProvider.Instance) Dim codelensService = New RemoteCodeLensReferencesService() Dim originalDocument = workspace.Documents.First(Function(d) d.AnnotatedSpans.ContainsKey("Original")) Dim startDocument = workspace.CurrentSolution.GetDocument(originalDocument.Id) Assert.NotNull(startDocument) Dim root = Await startDocument.GetSyntaxRootAsync() Dim node = root.FindNode(originalDocument.AnnotatedSpans("Original").First()).AncestorsAndSelf().OfType(Of ClassDeclarationSyntax).First() Dim results = Await codelensService.FindReferenceLocationsAsync(workspace.CurrentSolution, startDocument.Id, node, CancellationToken.None) Assert.True(results.HasValue) Dim definitionDocument = workspace.Documents.First(Function(d) d.AnnotatedSpans.ContainsKey("Definition")) Dim definitionText = Await workspace.CurrentSolution.GetDocument(definitionDocument.Id).GetTextAsync() Dim referenceSpan = definitionDocument.SelectedSpans.First() Dim expected = {(definitionDocument.Name, definitionText.Lines.GetLinePositionSpan(referenceSpan).Start, definitionText.Lines.GetLineFromPosition(referenceSpan.Start).ToString())} Dim actual = New List(Of (String, LinePosition, String)) For Each result In results.Value actual.Add((result.FilePath, New LinePosition(result.LineNumber, result.ColumnNumber), result.ReferenceLineText)) Next ' confirm that all FAR results are mapped to ones in mapped.cs file rather than ones in original.cs AssertEx.SetEqual(expected, actual) End Using End Function <InlineData(True)> <InlineData(False)> <WpfTheory, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestDocumentOperationCanApplyChange(ignoreUnchangeableDocuments As Boolean) As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class C { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, documentServiceProvider:=TestDocumentServiceProvider.Instance, ignoreUnchangeableDocumentsWhenApplyingChanges:=ignoreUnchangeableDocuments) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) ' made a change Dim newDocument = document.WithText(SourceText.From("")) ' confirm the change Assert.Equal(String.Empty, (Await newDocument.GetTextAsync()).ToString()) ' confirm apply changes are not supported Assert.False(document.CanApplyChange()) Assert.Equal(ignoreUnchangeableDocuments, workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges) ' see whether changes can be applied to the solution If ignoreUnchangeableDocuments Then Assert.True(workspace.TryApplyChanges(newDocument.Project.Solution)) ' Changes should not be made if Workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges is true Dim currentDocument = workspace.CurrentSolution.GetDocument(document.Id) Assert.True(currentDocument.GetTextSynchronously(CancellationToken.None).ContentEquals(document.GetTextSynchronously(CancellationToken.None))) Else ' should throw if Workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges is false Assert.Throws(Of NotSupportedException)(Sub() workspace.TryApplyChanges(newDocument.Project.Solution)) End If End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestDocumentOperationCanApplySupportDiagnostics() As System.Threading.Tasks.Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Original.cs"> class { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, composition:=s_compositionWithMockDiagnosticUpdateSourceRegistrationService, documentServiceProvider:=TestDocumentServiceProvider.Instance) Dim analyzerReference = New TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()) workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences({analyzerReference})) Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) Dim model = Await document.GetSemanticModelAsync() ' confirm there are errors Assert.True(model.GetDiagnostics().Any()) Assert.IsType(Of MockDiagnosticUpdateSourceRegistrationService)(workspace.GetService(Of IDiagnosticUpdateSourceRegistrationService)()) Dim diagnosticService = Assert.IsType(Of DiagnosticAnalyzerService)(workspace.GetService(Of IDiagnosticAnalyzerService)()) ' confirm diagnostic support is off for the document Assert.False(document.SupportsDiagnostics()) ' register the workspace to the service diagnosticService.CreateIncrementalAnalyzer(workspace) ' confirm that IDE doesn't report the diagnostics Dim diagnostics = Await diagnosticService.GetDiagnosticsAsync(workspace.CurrentSolution, documentId:=document.Id) Assert.False(diagnostics.Any()) End Using End Function Private Class TestDocumentServiceProvider Implements IDocumentServiceProvider Public Shared ReadOnly Instance As TestDocumentServiceProvider = New TestDocumentServiceProvider() Public Function GetService(Of TService As {Class, IDocumentService})() As TService Implements IDocumentServiceProvider.GetService If TypeOf SpanMapper.Instance Is TService Then Return TryCast(SpanMapper.Instance, TService) ElseIf TypeOf Excerpter.Instance Is TService Then Return TryCast(Excerpter.Instance, TService) ElseIf TypeOf DocumentOperations.Instance Is TService Then Return TryCast(DocumentOperations.Instance, TService) End If Return Nothing End Function Private Class SpanMapper Implements ISpanMappingService Public Shared ReadOnly Instance As SpanMapper = New SpanMapper() Public ReadOnly Property SupportsMappingImportDirectives As Boolean = False Implements ISpanMappingService.SupportsMappingImportDirectives Public Async Function MapSpansAsync(document As Document, spans As IEnumerable(Of TextSpan), cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of MappedSpanResult)) Implements ISpanMappingService.MapSpansAsync Dim testWorkspace = DirectCast(document.Project.Solution.Workspace, TestWorkspace) Dim testDocument = testWorkspace.GetTestDocument(document.Id) Dim mappedTestDocument = testWorkspace.Documents.First(Function(d) d.Id <> testDocument.Id) Dim mappedDocument = testWorkspace.CurrentSolution.GetDocument(mappedTestDocument.Id) Dim mappedSource = Await mappedDocument.GetTextAsync(cancellationToken).ConfigureAwait(False) Dim results = New List(Of MappedSpanResult) For Each span In spans If testDocument.AnnotatedSpans("Original").First() = span Then Dim mappedSpan = mappedTestDocument.AnnotatedSpans("Definition").First() Dim lineSpan = mappedSource.Lines.GetLinePositionSpan(mappedSpan) results.Add(New MappedSpanResult(mappedDocument.FilePath, lineSpan, mappedSpan)) ElseIf testDocument.SelectedSpans.First() = span Then Dim mappedSpan = mappedTestDocument.SelectedSpans.First() Dim lineSpan = mappedSource.Lines.GetLinePositionSpan(mappedSpan) results.Add(New MappedSpanResult(mappedDocument.FilePath, lineSpan, mappedSpan)) Else Throw New Exception("shouldn't reach here") End If Next Return results.ToImmutableArray() End Function Public Function GetMappedTextChangesAsync(oldDocument As Document, newDocument As Document, cancellationToken As CancellationToken) _ As Task(Of ImmutableArray(Of (mappedFilePath As String, mappedTextChange As Microsoft.CodeAnalysis.Text.TextChange))) _ Implements ISpanMappingService.GetMappedTextChangesAsync Throw New NotImplementedException() End Function End Class Private Class Excerpter Implements IDocumentExcerptService Public Shared ReadOnly Instance As Excerpter = New Excerpter() Public Async Function TryExcerptAsync(document As Document, span As TextSpan, mode As ExcerptMode, cancellationToken As CancellationToken) As Task(Of ExcerptResult?) Implements IDocumentExcerptService.TryExcerptAsync Dim testWorkspace = DirectCast(document.Project.Solution.Workspace, TestWorkspace) Dim testDocument = testWorkspace.GetTestDocument(document.Id) Dim mappedTestDocument = testWorkspace.Documents.First(Function(d) d.Id <> testDocument.Id) Dim mappedDocument = testWorkspace.CurrentSolution.GetDocument(mappedTestDocument.Id) Dim mappedSource = Await mappedDocument.GetTextAsync(cancellationToken).ConfigureAwait(False) Dim mappedSpan As TextSpan If testDocument.AnnotatedSpans("Original").First() = span Then mappedSpan = mappedTestDocument.AnnotatedSpans("Definition").First() ElseIf testDocument.SelectedSpans.First() = span Then mappedSpan = mappedTestDocument.SelectedSpans.First() Else Throw New Exception("shouldn't reach here") End If Dim line = mappedSource.Lines.GetLineFromPosition(mappedSpan.Start) Return New ExcerptResult(mappedSource.GetSubText(line.Span), New TextSpan(mappedSpan.Start - line.Start, mappedSpan.Length), ImmutableArray.Create(New ClassifiedSpan(New TextSpan(0, line.Span.Length), ClassificationTypeNames.Text)), document, span) End Function End Class Private Class DocumentOperations Implements IDocumentOperationService Public Shared ReadOnly Instance As DocumentOperations = New DocumentOperations() Public ReadOnly Property CanApplyChange As Boolean Implements IDocumentOperationService.CanApplyChange Get Return False End Get End Property Public ReadOnly Property SupportDiagnostics As Boolean Implements IDocumentOperationService.SupportDiagnostics Get Return False End Get End Property End Class End Class <PartNotDiscoverable> <Export(GetType(SVsServiceProvider))> Private Class MockServiceProvider Implements SVsServiceProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function GetService(serviceType As Type) As Object Implements SVsServiceProvider.GetService If GetType(SVsFindAllReferences) = serviceType Then Return TestFindAllReferencesService.Instance End If Return Nothing End Function End Class Private Class TestFindAllReferencesService Implements IFindAllReferencesService Public Shared ReadOnly Instance As TestFindAllReferencesService = New TestFindAllReferencesService() ' this mock is not thread-safe. don't use it concurrently Public LastWindow As FindAllReferencesWindow Public Function StartSearch(label As String) As IFindAllReferencesWindow Implements IFindAllReferencesService.StartSearch LastWindow = New FindAllReferencesWindow(label) Return LastWindow End Function End Class Private Class FindAllReferencesWindow Implements IFindAllReferencesWindow Public ReadOnly Label As String Public ReadOnly MyTableControl As WpfTableControl = New WpfTableControl() Public ReadOnly MyTableManager As TableManager = New TableManager() Public Sub New(label As String) Me.Label = label End Sub Public ReadOnly Property TableControl As IWpfTableControl Implements IFindAllReferencesWindow.TableControl Get Return MyTableControl End Get End Property Public ReadOnly Property Manager As ITableManager Implements IFindAllReferencesWindow.Manager Get Return MyTableManager End Get End Property Public Property Title As String Implements IFindAllReferencesWindow.Title Public Event Closed As EventHandler Implements IFindAllReferencesWindow.Closed #Region "Not Implemented" Public Sub AddCommandTarget(target As IOleCommandTarget, ByRef [next] As IOleCommandTarget) Implements IFindAllReferencesWindow.AddCommandTarget Throw New NotImplementedException() End Sub #End Region Public Sub SetProgress(progress As Double) Implements IFindAllReferencesWindow.SetProgress End Sub Public Sub SetProgress(completed As Integer, maximum As Integer) Implements IFindAllReferencesWindow.SetProgress End Sub End Class Private Class TableDataSink Implements ITableDataSink ' not thread safe. it should never be used concurrently Public LastFactory As ITableEntriesSnapshotFactory Public Property IsStable As Boolean Implements ITableDataSink.IsStable Public Sub AddFactory(newFactory As ITableEntriesSnapshotFactory, Optional removeAllFactories As Boolean = False) Implements ITableDataSink.AddFactory LastFactory = newFactory End Sub Public Sub FactorySnapshotChanged(factory As ITableEntriesSnapshotFactory) Implements ITableDataSink.FactorySnapshotChanged LastFactory = factory End Sub #Region "Not Implemented" Public Sub AddEntries(newEntries As IReadOnlyList(Of ITableEntry), Optional removeAllEntries As Boolean = False) Implements ITableDataSink.AddEntries Throw New NotImplementedException() End Sub Public Sub RemoveEntries(oldEntries As IReadOnlyList(Of ITableEntry)) Implements ITableDataSink.RemoveEntries Throw New NotImplementedException() End Sub Public Sub ReplaceEntries(oldEntries As IReadOnlyList(Of ITableEntry), newEntries As IReadOnlyList(Of ITableEntry)) Implements ITableDataSink.ReplaceEntries Throw New NotImplementedException() End Sub Public Sub RemoveAllEntries() Implements ITableDataSink.RemoveAllEntries Throw New NotImplementedException() End Sub Public Sub AddSnapshot(newSnapshot As ITableEntriesSnapshot, Optional removeAllSnapshots As Boolean = False) Implements ITableDataSink.AddSnapshot Throw New NotImplementedException() End Sub Public Sub RemoveSnapshot(oldSnapshot As ITableEntriesSnapshot) Implements ITableDataSink.RemoveSnapshot Throw New NotImplementedException() End Sub Public Sub RemoveAllSnapshots() Implements ITableDataSink.RemoveAllSnapshots Throw New NotImplementedException() End Sub Public Sub ReplaceSnapshot(oldSnapshot As ITableEntriesSnapshot, newSnapshot As ITableEntriesSnapshot) Implements ITableDataSink.ReplaceSnapshot Throw New NotImplementedException() End Sub Public Sub RemoveFactory(oldFactory As ITableEntriesSnapshotFactory) Implements ITableDataSink.RemoveFactory Throw New NotImplementedException() End Sub Public Sub ReplaceFactory(oldFactory As ITableEntriesSnapshotFactory, newFactory As ITableEntriesSnapshotFactory) Implements ITableDataSink.ReplaceFactory Throw New NotImplementedException() End Sub Public Sub RemoveAllFactories() Implements ITableDataSink.RemoveAllFactories Throw New NotImplementedException() End Sub #End Region End Class Private Class TableManager Implements ITableManager Private ReadOnly _sources As List(Of ITableDataSource) = New List(Of ITableDataSource)() Public LastSink As TableDataSink Public ReadOnly Property Identifier As String Implements ITableManager.Identifier Get Return "Test" End Get End Property Public ReadOnly Property Sources As IReadOnlyList(Of ITableDataSource) Implements ITableManager.Sources Get Return _sources End Get End Property Public Event SourcesChanged As EventHandler Implements ITableManager.SourcesChanged Public Function AddSource(source As ITableDataSource, ParamArray columns() As String) As Boolean Implements ITableManager.AddSource Return AddSource(source, columns.ToImmutableArray()) End Function Public Function AddSource(source As ITableDataSource, columns As IReadOnlyCollection(Of String)) As Boolean Implements ITableManager.AddSource LastSink = New TableDataSink() source.Subscribe(LastSink) _sources.Add(source) Return True End Function Public Function RemoveSource(source As ITableDataSource) As Boolean Implements ITableManager.RemoveSource Return _sources.Remove(source) End Function #Region "Not Implemented" Public Function GetColumnsForSources(sources As IEnumerable(Of ITableDataSource)) As IReadOnlyList(Of String) Implements ITableManager.GetColumnsForSources Throw New NotImplementedException() End Function #End Region End Class Private Class WpfTableControl Implements IWpfTableControl2 Public Event GroupingsChanged As EventHandler Implements IWpfTableControl2.GroupingsChanged Private _states As List(Of ColumnState) = New List(Of ColumnState)({New ColumnState2(StandardTableColumnDefinitions2.Definition, isVisible:=True, width:=10)}) Public ReadOnly Property ColumnStates As IReadOnlyList(Of ColumnState) Implements IWpfTableControl.ColumnStates Get Return _states End Get End Property Public Sub SetColumnStates(states As IEnumerable(Of ColumnState)) Implements IWpfTableControl2.SetColumnStates _states = states.ToList() End Sub Public ReadOnly Property ColumnDefinitionManager As ITableColumnDefinitionManager Implements IWpfTableControl.ColumnDefinitionManager Get Return Nothing End Get End Property #Region "Not Implemented" Public ReadOnly Property IsDataStable As Boolean Implements IWpfTableControl2.IsDataStable Get Throw New NotImplementedException() End Get End Property Public Property NavigationBehavior As TableEntryNavigationBehavior Implements IWpfTableControl2.NavigationBehavior Get Throw New NotImplementedException() End Get Set(value As TableEntryNavigationBehavior) Throw New NotImplementedException() End Set End Property Public Property KeepSelectionInView As Boolean Implements IWpfTableControl2.KeepSelectionInView Get Throw New NotImplementedException() End Get Set(value As Boolean) Throw New NotImplementedException() End Set End Property Public Property ShowGroupingLine As Boolean Implements IWpfTableControl2.ShowGroupingLine Get Throw New NotImplementedException() End Get Set(value As Boolean) Throw New NotImplementedException() End Set End Property Public Property RaiseDataUnstableChangeDelay As TimeSpan Implements IWpfTableControl2.RaiseDataUnstableChangeDelay Get Throw New NotImplementedException() End Get Set(value As TimeSpan) Throw New NotImplementedException() End Set End Property Public Property SelectedItemActiveBackground As Brush Implements IWpfTableControl2.SelectedItemActiveBackground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public Property SelectedItemActiveForeground As Brush Implements IWpfTableControl2.SelectedItemActiveForeground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public Property SelectedItemInactiveBackground As Brush Implements IWpfTableControl2.SelectedItemInactiveBackground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public Property SelectedItemInactiveForeground As Brush Implements IWpfTableControl2.SelectedItemInactiveForeground Get Throw New NotImplementedException() End Get Set(value As Brush) Throw New NotImplementedException() End Set End Property Public ReadOnly Property Manager As ITableManager Implements IWpfTableControl.Manager Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property Control As FrameworkElement Implements IWpfTableControl.Control Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property AutoSubscribe As Boolean Implements IWpfTableControl.AutoSubscribe Get Throw New NotImplementedException() End Get End Property Public Property SortFunction As Comparison(Of ITableEntryHandle) Implements IWpfTableControl.SortFunction Get Throw New NotImplementedException() End Get Set(value As Comparison(Of ITableEntryHandle)) Throw New NotImplementedException() End Set End Property Public Property SelectionMode As SelectionMode Implements IWpfTableControl.SelectionMode Get Throw New NotImplementedException() End Get Set(value As SelectionMode) Throw New NotImplementedException() End Set End Property Public ReadOnly Property Entries As IEnumerable(Of ITableEntryHandle) Implements IWpfTableControl.Entries Get Throw New NotImplementedException() End Get End Property Public Property SelectedEntries As IEnumerable(Of ITableEntryHandle) Implements IWpfTableControl.SelectedEntries Get Throw New NotImplementedException() End Get Set(value As IEnumerable(Of ITableEntryHandle)) Throw New NotImplementedException() End Set End Property Public ReadOnly Property SelectedEntry As ITableEntryHandle Implements IWpfTableControl.SelectedEntry Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property SelectedOrFirstEntry As ITableEntryHandle Implements IWpfTableControl.SelectedOrFirstEntry Get Throw New NotImplementedException() End Get End Property Public Event DataStabilityChanged As EventHandler Implements IWpfTableControl2.DataStabilityChanged Public Event FiltersChanged As EventHandler(Of FiltersChangedEventArgs) Implements IWpfTableControl.FiltersChanged Public Event PreEntriesChanged As EventHandler Implements IWpfTableControl.PreEntriesChanged Public Event EntriesChanged As EventHandler(Of EntriesChangedEventArgs) Implements IWpfTableControl.EntriesChanged Public Sub SubscribeToDataSource(source As ITableDataSource) Implements IWpfTableControl.SubscribeToDataSource Throw New NotImplementedException() End Sub Public Sub SelectAll() Implements IWpfTableControl.SelectAll Throw New NotImplementedException() End Sub Public Sub UnselectAll() Implements IWpfTableControl.UnselectAll Throw New NotImplementedException() End Sub Public Sub RefreshUI() Implements IWpfTableControl.RefreshUI Throw New NotImplementedException() End Sub Public Function GetAllFilters() As IEnumerable(Of Tuple(Of String, IEntryFilter)) Implements IWpfTableControl2.GetAllFilters Throw New NotImplementedException() End Function Public Function UnsubscribeFromDataSource(source As ITableDataSource) As Boolean Implements IWpfTableControl.UnsubscribeFromDataSource Throw New NotImplementedException() End Function Public Function SetFilter(key As String, newFilter As IEntryFilter) As IEntryFilter Implements IWpfTableControl.SetFilter Throw New NotImplementedException() End Function Public Function GetFilter(key As String) As IEntryFilter Implements IWpfTableControl.GetFilter Throw New NotImplementedException() End Function Public Function ForceUpdateAsync() As Task(Of EntriesChangedEventArgs) Implements IWpfTableControl.ForceUpdateAsync Throw New NotImplementedException() End Function Public Sub Dispose() Implements IDisposable.Dispose End Sub #End Region End Class End Class End Namespace
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest/InitializeParameter/InitializeMemberFromParameterTests.cs
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.InitializeParameter; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InitializeParameter { public partial class InitializeMemberFromParameterTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpInitializeMemberFromParameterCodeRefactoringProvider(); private readonly NamingStylesTestOptionSets options = new NamingStylesTestOptionSets(LanguageNames.CSharp); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithSameName() { await TestInRegularAndScript1Async( @" class C { private string s; public C([||]string s) { } }", @" class C { private string s; public C(string s) { this.s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestEndOfParameter1() { await TestInRegularAndScript1Async( @" class C { private string s; public C(string s[||]) { } }", @" class C { private string s; public C(string s) { this.s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestEndOfParameter2() { await TestInRegularAndScript1Async( @" class C { private string s; public C(string s[||], string t) { } }", @" class C { private string s; public C(string s, string t) { this.s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithUnderscoreName() { await TestInRegularAndScript1Async( @" class C { private string _s; public C([||]string s) { } }", @" class C { private string _s; public C(string s) { _s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeWritableProperty() { await TestInRegularAndScript1Async( @" class C { private string S { get; } public C([||]string s) { } }", @" class C { private string S { get; } public C(string s) { S = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithDifferentName() { await TestInRegularAndScriptAsync( @" class C { private string t; public C([||]string s) { } }", @" class C { private string t; public C(string s) { S = s; } public string S { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeNonWritableProperty() { await TestInRegularAndScript1Async( @" class C { private string S => null; public C([||]string s) { } }", @" class C { private string S => null; public string S1 { get; } public C(string s) { S1 = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeDoesNotUsePropertyWithUnrelatedName() { await TestInRegularAndScriptAsync( @" class C { private string T { get; } public C([||]string s) { } }", @" class C { private string T { get; } public string S { get; } public C(string s) { S = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithWrongType1() { await TestInRegularAndScript1Async( @" class C { private int s; public C([||]string s) { } }", @" class C { private int s; public C(string s) { S = s; } public string S { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithWrongType2() { await TestInRegularAndScript1Async( @" class C { private int s; public C([||]string s) { } }", @" class C { private readonly string s1; private int s; public C(string s) { s1 = s; } }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithConvertibleType() { await TestInRegularAndScriptAsync( @" class C { private object s; public C([||]string s) { } }", @" class C { private object s; public C(string s) { this.s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestWhenAlreadyInitialized1() { await TestMissingInRegularAndScriptAsync( @" class C { private int s; private int x; public C([||]string s) { x = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestWhenAlreadyInitialized2() { await TestMissingInRegularAndScriptAsync( @" class C { private int s; private int x; public C([||]string s) { x = s ?? throw new Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestWhenAlreadyInitialized3() { await TestInRegularAndScript1Async( @" class C { private int s; public C([||]string s) { s = 0; } }", @" class C { private int s; public C([||]string s) { s = 0; S = s; } public string S { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation1() { await TestInRegularAndScript1Async( @" class C { private string s; private string t; public C([||]string s, string t) { this.t = t; } }", @" class C { private string s; private string t; public C(string s, string t) { this.s = s; this.t = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation2() { await TestInRegularAndScript1Async( @" class C { private string s; private string t; public C(string s, [||]string t) { this.s = s; } }", @" class C { private string s; private string t; public C(string s, string t) { this.s = s; this.t = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation3() { await TestInRegularAndScript1Async( @" class C { private string s; public C([||]string s) { if (true) { } } }", @" class C { private string s; public C(string s) { if (true) { } this.s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestNotInMethod() { await TestMissingInRegularAndScriptAsync( @" class C { private string s; public void M([||]string s) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation4() { await TestInRegularAndScript1Async( @" class C { private string s; private string t; public C(string s, [||]string t) => this.s = s; }", @" class C { private string s; private string t; public C(string s, string t) { this.s = s; this.t = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation5() { await TestInRegularAndScript1Async( @" class C { private string s; private string t; public C([||]string s, string t) => this.t = t; }", @" class C { private string s; private string t; public C(string s, string t) { this.s = s; this.t = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation6() { await TestInRegularAndScript1Async( @" class C { public C(string s, [||]string t) { S = s; } public string S { get; } }", @" class C { public C(string s, string t) { S = s; T = t; } public string S { get; } public string T { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation7() { await TestInRegularAndScript1Async( @" class C { public C([||]string s, string t) { T = t; } public string T { get; } }", @" class C { public C(string s, string t) { S = s; T = t; } public string S { get; } public string T { get; } }"); } [WorkItem(19956, "https://github.com/dotnet/roslyn/issues/19956")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestNoBlock() { await TestInRegularAndScript1Async( @" class C { private string s; public C(string s[||]) }", @" class C { private string s; public C(string s) { this.s = s; } }"); } [WorkItem(29190, "https://github.com/dotnet/roslyn/issues/29190")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithParameterNameSelected1() { await TestInRegularAndScript1Async( @" class C { private string s; public C(string [|s|]) { } }", @" class C { private string s; public C(string s) { this.s = s; } }"); } [WorkItem(29190, "https://github.com/dotnet/roslyn/issues/29190")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeField_ParameterNameSelected2() { await TestInRegularAndScript1Async( @" class C { private string s; public C(string [|s|], int i) { } }", @" class C { private string s; public C(string s, int i) { this.s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeClassProperty_RequiredAccessibilityOmitIfDefault() { await TestInRegularAndScript1Async( @" class C { readonly int test = 5; public C(int test, int [|test2|]) { } }", @" class C { readonly int test = 5; public C(int test, int test2) { Test2 = test2; } public int Test2 { get; } }", index: 0, parameters: OmitIfDefault_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeClassProperty_RequiredAccessibilityNever() { await TestInRegularAndScript1Async( @" class C { readonly int test = 5; public C(int test, int [|test2|]) { } }", @" class C { readonly int test = 5; public C(int test, int test2) { Test2 = test2; } public int Test2 { get; } }", index: 0, parameters: Never_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeClassProperty_RequiredAccessibilityAlways() { await TestInRegularAndScript1Async( @" class C { readonly int test = 5; public C(int test, int [|test2|]) { } }", @" class C { readonly int test = 5; public C(int test, int test2) { Test2 = test2; } public int Test2 { get; } }", index: 0, parameters: Always_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeClassField_RequiredAccessibilityOmitIfDefault() { await TestInRegularAndScript1Async( @" class C { readonly int test = 5; public C(int test, int [|test2|]) { } }", @" class C { readonly int test = 5; readonly int test2; public C(int test, int test2) { this.test2 = test2; } }", index: 1, parameters: OmitIfDefault_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeClassField_RequiredAccessibilityNever() { await TestInRegularAndScript1Async( @" class C { readonly int test = 5; public C(int test, int [|test2|]) { } }", @" class C { readonly int test = 5; readonly int test2; public C(int test, int test2) { this.test2 = test2; } }", index: 1, parameters: Never_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeClassField_RequiredAccessibilityAlways() { await TestInRegularAndScript1Async( @" class C { readonly int test = 5; public C(int test, int [|test2|]) { } }", @" class C { readonly int test = 5; private readonly int test2; public C(int test, int test2) { this.test2 = test2; } }", index: 1, parameters: Always_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeStructProperty_RequiredAccessibilityOmitIfDefault() { await TestInRegularAndScript1Async( @" struct S { public Test(int [|test|]) { } }", @" struct S { public Test(int test) { Test = test; } public int Test { get; } }", index: 0, parameters: OmitIfDefault_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeStructProperty_RequiredAccessibilityNever() { await TestInRegularAndScript1Async( @" struct S { public Test(int [|test|]) { } }", @" struct S { public Test(int test) { Test = test; } public int Test { get; } }", index: 0, parameters: Never_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeStructProperty_RequiredAccessibilityAlways() { await TestInRegularAndScript1Async( @" struct S { public Test(int [|test|]) { } }", @" struct S { public Test(int test) { Test = test; } public int Test { get; } }", index: 0, parameters: Always_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeStructField_RequiredAccessibilityOmitIfDefault() { await TestInRegularAndScript1Async( @" struct S { public Test(int [|test|]) { } }", @" struct S { readonly int test; public Test(int test) { this.test = test; } }", index: 1, parameters: OmitIfDefault_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeStructField_RequiredAccessibilityNever() { await TestInRegularAndScript1Async( @" struct S { public Test(int [|test|]) { } }", @" struct S { readonly int test; public Test(int test) { this.test = test; } }", index: 1, parameters: Never_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeStructField_RequiredAccessibilityAlways() { await TestInRegularAndScript1Async( @" struct S { public Test(int [|test|]) { } }", @" struct S { private readonly int test; public Test(int test) { this.test = test; } }", index: 1, parameters: Always_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestNoParameterNamingStyle_CreateAndInitField() { await TestInRegularAndScript1Async( @" class C { public C([||]string s) { } }", @" class C { private readonly string _s; public C(string s) { _s = s; } }", index: 1, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonParameterNamingStyle_CreateAndInitField() { await TestInRegularAndScript1Async( @" class C { public C([||]string t_s) { } }", @" class C { private readonly string _s; public C(string t_s) { _s = t_s; } }", index: 1, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSpecifiedParameterNamingStyle_CreateAndInitField() { await TestInRegularAndScript1Async( @" class C { public C([||]string p_s_End) { } }", @" class C { private readonly string _s; public C(string p_s_End) { _s = p_s_End; } }", index: 1, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle_CreateAndInitField() { await TestInRegularAndScript1Async( @" class C { public C([||]string t_p_s_End) { } }", @" class C { private readonly string _s; public C(string t_p_s_End) { _s = t_p_s_End; } }", index: 1, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle2_CreateAndInitField() { await TestInRegularAndScript1Async( @" class C { public C([||]string p_t_s) { } }", @" class C { private readonly string _s; public C([||]string p_t_s) { _s = p_t_s; } }", index: 1, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestNoParameterNamingStyle_CreateAndInitProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string s) { } }", @" class C { public C(string s) { S = s; } public string S { get; } }", parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonParameterNamingStyle_CreateAndInitProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string t_s) { } }", @" class C { public C(string t_s) { S = t_s; } public string S { get; } }", parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSpecifiedParameterNamingStyle_CreateAndInitProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string p_s_End) { } }", @" class C { public C(string p_s_End) { S = p_s_End; } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle_CreateAndInitProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string t_p_s_End) { } }", @" class C { public C(string t_p_s_End) { S = t_p_s_End; } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle2_CreateAndInitProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string p_t_s_End) { } }", @" class C { public C([||]string p_t_s_End) { S = p_t_s_End; } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestNoParameterNamingStyle_InitializeField() { await TestInRegularAndScript1Async( @" class C { private readonly string _s; public C([||]string s) { } }", @" class C { private readonly string _s; public C(string s) { _s = s; } }", index: 0, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonParameterNamingStyle_InitializeField() { await TestInRegularAndScript1Async( @" class C { private readonly string _s; public C([||]string t_s) { } }", @" class C { private readonly string _s; public C(string t_s) { _s = t_s; } }", index: 0, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSpecifiedParameterNamingStyle_InitializeField() { await TestInRegularAndScript1Async( @" class C { private readonly string _s; public C([||]string p_s_End) { } }", @" class C { private readonly string _s; public C(string p_s_End) { _s = p_s_End; } }", index: 0, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle_InitializeField() { await TestInRegularAndScript1Async( @" class C { private readonly string _s; public C([||]string t_p_s_End) { } }", @" class C { private readonly string _s; public C(string t_p_s_End) { _s = t_p_s_End; } }", index: 0, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle2_InitializeField() { await TestInRegularAndScript1Async( @" class C { private readonly string _s; public C([||]string p_t_s_End) { } }", @" class C { private readonly string _s; public C([||]string p_t_s_End) { _s = p_t_s_End; } }", index: 0, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestNoParameterNamingStyle_InitializeProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string s) { } public string S { get; } }", @" class C { public C(string s) { S = s; } public string S { get; } }", parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonParameterNamingStyle_InitializeProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string t_s) { } public string S { get; } }", @" class C { public C(string t_s) { S = t_s; } public string S { get; } }", parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSpecifiedParameterNamingStyle_InitializeProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string p_s_End) { } public string S { get; } }", @" class C { public C(string p_s_End) { S = p_s_End; } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle_InitializeProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string t_p_s_End) { } public string S { get; } }", @" class C { public C(string t_p_s_End) { S = t_p_s_End; } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle2_InitializeProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string p_t_s_End) { } public string S { get; } }", @" class C { public C([||]string p_t_s_End) { S = p_t_s_End; } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestBaseNameEmpty() { await TestMissingAsync( @" class C { public C([||]string p__End) { } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSomeBaseNamesEmpty() { // Currently, this case does not offer a refactoring because selecting multiple parameters // is not supported. If multiple parameters are supported in the future, this case should // be updated to verify that only the parameter name that does not have an empty base is offered. await TestMissingAsync( @" class C { public C([|string p__End, string p_test_t|]) { } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } private TestParameters OmitIfDefault_Warning => new TestParameters(options: Option(CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault, NotificationOption2.Warning)); private TestParameters Never_Warning => new TestParameters(options: Option(CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Never, NotificationOption2.Warning)); private TestParameters Always_Warning => new TestParameters(options: Option(CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Always, NotificationOption2.Warning)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCreateFieldWithTopLevelNullability() { await TestInRegularAndScript1Async( @" #nullable enable class C { public C([||]string? s) { } }", @" #nullable enable class C { private readonly string? _s; public C(string? s) { _s = s; } }", index: 1, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCreatePropertyWithTopLevelNullability() { await TestInRegularAndScript1Async( @" #nullable enable class C { public C([||]string? s) { } }", @" #nullable enable class C { public C(string? s) { S = s; } public string? S { get; } }", parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); } [WorkItem(24526, "https://github.com/dotnet/roslyn/issues/24526")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSingleLineBlock_BraceOnNextLine() { await TestInRegularAndScript1Async( @" class C { public C([||]string s) { } }", @" class C { public C(string s) { S = s; } public string S { get; } }"); } [WorkItem(24526, "https://github.com/dotnet/roslyn/issues/24526")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSingleLineBlock_BraceOnSameLine() { await TestInRegularAndScriptAsync( @" class C { public C([||]string s) { } }", @" class C { public C(string s) { S = s; } public string S { get; } }", options: this.Option(CSharpFormattingOptions2.NewLinesForBracesInMethods, false)); } [WorkItem(23308, "https://github.com/dotnet/roslyn/issues/23308")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateFieldIfParameterFollowsExistingFieldAssignment() { await TestInRegularAndScript1Async( @" class C { private readonly string s; public C(string s, [||]int i) { this.s = s; } }", @" class C { private readonly string s; private readonly int i; public C(string s, int i) { this.s = s; this.i = i; } }"); } [WorkItem(23308, "https://github.com/dotnet/roslyn/issues/23308")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateFieldIfParameterPrecedesExistingFieldAssignment() { await TestInRegularAndScript1Async( @" class C { private readonly string s; public C([||]int i, string s) { this.s = s; } }", @" class C { private readonly int i; private readonly string s; public C(int i, string s) { this.i = i; this.s = s; } }"); } [WorkItem(41824, "https://github.com/dotnet/roslyn/issues/41824")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestMissingInArgList() { await TestMissingInRegularAndScriptAsync( @" class C { private static void M() { M2(__arglist(1, 2, 3, 5, 6)); } public static void M2([||]__arglist) { } }"); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingFields1() { await TestInRegularAndScript1Async( @" class C { public C([||]int i, int j, int k) { } }", @" class C { private readonly int i; private readonly int j; private readonly int k; public C(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } }", index: 3); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingFields2() { await TestInRegularAndScript1Async( @" class C { private readonly int i; public C(int i, [||]int j, int k) { this.i = i; } }", @" class C { private readonly int i; private readonly int j; private readonly int k; public C(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } }", index: 2); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingFields3() { await TestInRegularAndScript1Async( @" class C { private readonly int j; public C([||]int i, int j, int k) { this.j = j; } }", @" class C { private readonly int i; private readonly int j; private readonly int k; public C(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } }", index: 2); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingFields4() { await TestInRegularAndScript1Async( @" class C { private readonly int k; public C([||]int i, int j, int k) { this.k = k; } }", @" class C { private readonly int i; private readonly int j; private readonly int k; public C(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } }", index: 2); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingProperties1() { await TestInRegularAndScript1Async( @" class C { public C([||]int i, int j, int k) { } }", @" class C { public C(int i, int j, int k) { I = i; J = j; K = k; } public int I { get; } public int J { get; } public int K { get; } }", index: 2); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingProperties2() { await TestInRegularAndScript1Async( @" class C { private readonly int i; public C(int i, [||]int j, int k) { this.i = i; } }", @" class C { private readonly int i; public C(int i, int j, int k) { this.i = i; J = j; K = k; } public int J { get; } public int K { get; } }", index: 3); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingProperties3() { await TestInRegularAndScript1Async( @" class C { private readonly int j; public C([||]int i, int j, int k) { this.j = j; } }", @" class C { private readonly int j; public C(int i, int j, int k) { I = i; this.j = j; K = k; } public int I { get; } public int K { get; } }", index: 3); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingProperties4() { await TestInRegularAndScript1Async( @" class C { private readonly int k; public C([||]int i, int j, int k) { this.k = k; } }", @" class C { private readonly int k; public C(int i, int j, int k) { I = i; J = j; this.k = k; } public int I { get; } public int J { get; } }", index: 3); } [WorkItem(53467, "https://github.com/dotnet/roslyn/issues/53467")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestMissingWhenTypeNotInCompilation() { await TestMissingInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1""> <Document> public class Foo { public Foo(int prop1) { Prop1 = prop1; } public int Prop1 { get; } } public class Bar : Foo { public Bar(int prop1, int [||]prop2) : base(prop1) { } } </Document> </Project> </Workspace>"); } } }
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.InitializeParameter; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InitializeParameter { public partial class InitializeMemberFromParameterTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpInitializeMemberFromParameterCodeRefactoringProvider(); private readonly NamingStylesTestOptionSets options = new NamingStylesTestOptionSets(LanguageNames.CSharp); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithSameName() { await TestInRegularAndScript1Async( @" class C { private string s; public C([||]string s) { } }", @" class C { private string s; public C(string s) { this.s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestEndOfParameter1() { await TestInRegularAndScript1Async( @" class C { private string s; public C(string s[||]) { } }", @" class C { private string s; public C(string s) { this.s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestEndOfParameter2() { await TestInRegularAndScript1Async( @" class C { private string s; public C(string s[||], string t) { } }", @" class C { private string s; public C(string s, string t) { this.s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithUnderscoreName() { await TestInRegularAndScript1Async( @" class C { private string _s; public C([||]string s) { } }", @" class C { private string _s; public C(string s) { _s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeWritableProperty() { await TestInRegularAndScript1Async( @" class C { private string S { get; } public C([||]string s) { } }", @" class C { private string S { get; } public C(string s) { S = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithDifferentName() { await TestInRegularAndScriptAsync( @" class C { private string t; public C([||]string s) { } }", @" class C { private string t; public C(string s) { S = s; } public string S { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeNonWritableProperty() { await TestInRegularAndScript1Async( @" class C { private string S => null; public C([||]string s) { } }", @" class C { private string S => null; public string S1 { get; } public C(string s) { S1 = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeDoesNotUsePropertyWithUnrelatedName() { await TestInRegularAndScriptAsync( @" class C { private string T { get; } public C([||]string s) { } }", @" class C { private string T { get; } public string S { get; } public C(string s) { S = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithWrongType1() { await TestInRegularAndScript1Async( @" class C { private int s; public C([||]string s) { } }", @" class C { private int s; public C(string s) { S = s; } public string S { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithWrongType2() { await TestInRegularAndScript1Async( @" class C { private int s; public C([||]string s) { } }", @" class C { private readonly string s1; private int s; public C(string s) { s1 = s; } }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithConvertibleType() { await TestInRegularAndScriptAsync( @" class C { private object s; public C([||]string s) { } }", @" class C { private object s; public C(string s) { this.s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestWhenAlreadyInitialized1() { await TestMissingInRegularAndScriptAsync( @" class C { private int s; private int x; public C([||]string s) { x = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestWhenAlreadyInitialized2() { await TestMissingInRegularAndScriptAsync( @" class C { private int s; private int x; public C([||]string s) { x = s ?? throw new Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestWhenAlreadyInitialized3() { await TestInRegularAndScript1Async( @" class C { private int s; public C([||]string s) { s = 0; } }", @" class C { private int s; public C([||]string s) { s = 0; S = s; } public string S { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation1() { await TestInRegularAndScript1Async( @" class C { private string s; private string t; public C([||]string s, string t) { this.t = t; } }", @" class C { private string s; private string t; public C(string s, string t) { this.s = s; this.t = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation2() { await TestInRegularAndScript1Async( @" class C { private string s; private string t; public C(string s, [||]string t) { this.s = s; } }", @" class C { private string s; private string t; public C(string s, string t) { this.s = s; this.t = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation3() { await TestInRegularAndScript1Async( @" class C { private string s; public C([||]string s) { if (true) { } } }", @" class C { private string s; public C(string s) { if (true) { } this.s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestNotInMethod() { await TestMissingInRegularAndScriptAsync( @" class C { private string s; public void M([||]string s) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation4() { await TestInRegularAndScript1Async( @" class C { private string s; private string t; public C(string s, [||]string t) => this.s = s; }", @" class C { private string s; private string t; public C(string s, string t) { this.s = s; this.t = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation5() { await TestInRegularAndScript1Async( @" class C { private string s; private string t; public C([||]string s, string t) => this.t = t; }", @" class C { private string s; private string t; public C(string s, string t) { this.s = s; this.t = t; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation6() { await TestInRegularAndScript1Async( @" class C { public C(string s, [||]string t) { S = s; } public string S { get; } }", @" class C { public C(string s, string t) { S = s; T = t; } public string S { get; } public string T { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInsertionLocation7() { await TestInRegularAndScript1Async( @" class C { public C([||]string s, string t) { T = t; } public string T { get; } }", @" class C { public C(string s, string t) { S = s; T = t; } public string S { get; } public string T { get; } }"); } [WorkItem(19956, "https://github.com/dotnet/roslyn/issues/19956")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestNoBlock() { await TestInRegularAndScript1Async( @" class C { private string s; public C(string s[||]) }", @" class C { private string s; public C(string s) { this.s = s; } }"); } [WorkItem(29190, "https://github.com/dotnet/roslyn/issues/29190")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeFieldWithParameterNameSelected1() { await TestInRegularAndScript1Async( @" class C { private string s; public C(string [|s|]) { } }", @" class C { private string s; public C(string s) { this.s = s; } }"); } [WorkItem(29190, "https://github.com/dotnet/roslyn/issues/29190")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeField_ParameterNameSelected2() { await TestInRegularAndScript1Async( @" class C { private string s; public C(string [|s|], int i) { } }", @" class C { private string s; public C(string s, int i) { this.s = s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeClassProperty_RequiredAccessibilityOmitIfDefault() { await TestInRegularAndScript1Async( @" class C { readonly int test = 5; public C(int test, int [|test2|]) { } }", @" class C { readonly int test = 5; public C(int test, int test2) { Test2 = test2; } public int Test2 { get; } }", index: 0, parameters: OmitIfDefault_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeClassProperty_RequiredAccessibilityNever() { await TestInRegularAndScript1Async( @" class C { readonly int test = 5; public C(int test, int [|test2|]) { } }", @" class C { readonly int test = 5; public C(int test, int test2) { Test2 = test2; } public int Test2 { get; } }", index: 0, parameters: Never_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeClassProperty_RequiredAccessibilityAlways() { await TestInRegularAndScript1Async( @" class C { readonly int test = 5; public C(int test, int [|test2|]) { } }", @" class C { readonly int test = 5; public C(int test, int test2) { Test2 = test2; } public int Test2 { get; } }", index: 0, parameters: Always_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeClassField_RequiredAccessibilityOmitIfDefault() { await TestInRegularAndScript1Async( @" class C { readonly int test = 5; public C(int test, int [|test2|]) { } }", @" class C { readonly int test = 5; readonly int test2; public C(int test, int test2) { this.test2 = test2; } }", index: 1, parameters: OmitIfDefault_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeClassField_RequiredAccessibilityNever() { await TestInRegularAndScript1Async( @" class C { readonly int test = 5; public C(int test, int [|test2|]) { } }", @" class C { readonly int test = 5; readonly int test2; public C(int test, int test2) { this.test2 = test2; } }", index: 1, parameters: Never_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeClassField_RequiredAccessibilityAlways() { await TestInRegularAndScript1Async( @" class C { readonly int test = 5; public C(int test, int [|test2|]) { } }", @" class C { readonly int test = 5; private readonly int test2; public C(int test, int test2) { this.test2 = test2; } }", index: 1, parameters: Always_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeStructProperty_RequiredAccessibilityOmitIfDefault() { await TestInRegularAndScript1Async( @" struct S { public Test(int [|test|]) { } }", @" struct S { public Test(int test) { Test = test; } public int Test { get; } }", index: 0, parameters: OmitIfDefault_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeStructProperty_RequiredAccessibilityNever() { await TestInRegularAndScript1Async( @" struct S { public Test(int [|test|]) { } }", @" struct S { public Test(int test) { Test = test; } public int Test { get; } }", index: 0, parameters: Never_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeStructProperty_RequiredAccessibilityAlways() { await TestInRegularAndScript1Async( @" struct S { public Test(int [|test|]) { } }", @" struct S { public Test(int test) { Test = test; } public int Test { get; } }", index: 0, parameters: Always_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeStructField_RequiredAccessibilityOmitIfDefault() { await TestInRegularAndScript1Async( @" struct S { public Test(int [|test|]) { } }", @" struct S { readonly int test; public Test(int test) { this.test = test; } }", index: 1, parameters: OmitIfDefault_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeStructField_RequiredAccessibilityNever() { await TestInRegularAndScript1Async( @" struct S { public Test(int [|test|]) { } }", @" struct S { readonly int test; public Test(int test) { this.test = test; } }", index: 1, parameters: Never_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestInitializeStructField_RequiredAccessibilityAlways() { await TestInRegularAndScript1Async( @" struct S { public Test(int [|test|]) { } }", @" struct S { private readonly int test; public Test(int test) { this.test = test; } }", index: 1, parameters: Always_Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestNoParameterNamingStyle_CreateAndInitField() { await TestInRegularAndScript1Async( @" class C { public C([||]string s) { } }", @" class C { private readonly string _s; public C(string s) { _s = s; } }", index: 1, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonParameterNamingStyle_CreateAndInitField() { await TestInRegularAndScript1Async( @" class C { public C([||]string t_s) { } }", @" class C { private readonly string _s; public C(string t_s) { _s = t_s; } }", index: 1, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSpecifiedParameterNamingStyle_CreateAndInitField() { await TestInRegularAndScript1Async( @" class C { public C([||]string p_s_End) { } }", @" class C { private readonly string _s; public C(string p_s_End) { _s = p_s_End; } }", index: 1, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle_CreateAndInitField() { await TestInRegularAndScript1Async( @" class C { public C([||]string t_p_s_End) { } }", @" class C { private readonly string _s; public C(string t_p_s_End) { _s = t_p_s_End; } }", index: 1, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle2_CreateAndInitField() { await TestInRegularAndScript1Async( @" class C { public C([||]string p_t_s) { } }", @" class C { private readonly string _s; public C([||]string p_t_s) { _s = p_t_s; } }", index: 1, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestNoParameterNamingStyle_CreateAndInitProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string s) { } }", @" class C { public C(string s) { S = s; } public string S { get; } }", parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonParameterNamingStyle_CreateAndInitProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string t_s) { } }", @" class C { public C(string t_s) { S = t_s; } public string S { get; } }", parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSpecifiedParameterNamingStyle_CreateAndInitProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string p_s_End) { } }", @" class C { public C(string p_s_End) { S = p_s_End; } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle_CreateAndInitProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string t_p_s_End) { } }", @" class C { public C(string t_p_s_End) { S = t_p_s_End; } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle2_CreateAndInitProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string p_t_s_End) { } }", @" class C { public C([||]string p_t_s_End) { S = p_t_s_End; } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestNoParameterNamingStyle_InitializeField() { await TestInRegularAndScript1Async( @" class C { private readonly string _s; public C([||]string s) { } }", @" class C { private readonly string _s; public C(string s) { _s = s; } }", index: 0, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonParameterNamingStyle_InitializeField() { await TestInRegularAndScript1Async( @" class C { private readonly string _s; public C([||]string t_s) { } }", @" class C { private readonly string _s; public C(string t_s) { _s = t_s; } }", index: 0, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSpecifiedParameterNamingStyle_InitializeField() { await TestInRegularAndScript1Async( @" class C { private readonly string _s; public C([||]string p_s_End) { } }", @" class C { private readonly string _s; public C(string p_s_End) { _s = p_s_End; } }", index: 0, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle_InitializeField() { await TestInRegularAndScript1Async( @" class C { private readonly string _s; public C([||]string t_p_s_End) { } }", @" class C { private readonly string _s; public C(string t_p_s_End) { _s = t_p_s_End; } }", index: 0, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle2_InitializeField() { await TestInRegularAndScript1Async( @" class C { private readonly string _s; public C([||]string p_t_s_End) { } }", @" class C { private readonly string _s; public C([||]string p_t_s_End) { _s = p_t_s_End; } }", index: 0, parameters: new TestParameters(options: options.MergeStyles(options.FieldNamesAreCamelCaseWithUnderscorePrefix, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestNoParameterNamingStyle_InitializeProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string s) { } public string S { get; } }", @" class C { public C(string s) { S = s; } public string S { get; } }", parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonParameterNamingStyle_InitializeProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string t_s) { } public string S { get; } }", @" class C { public C(string t_s) { S = t_s; } public string S { get; } }", parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSpecifiedParameterNamingStyle_InitializeProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string p_s_End) { } public string S { get; } }", @" class C { public C(string p_s_End) { S = p_s_End; } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle_InitializeProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string t_p_s_End) { } public string S { get; } }", @" class C { public C(string t_p_s_End) { S = t_p_s_End; } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCommonAndSpecifiedParameterNamingStyle2_InitializeProperty() { await TestInRegularAndScript1Async( @" class C { public C([||]string p_t_s_End) { } public string S { get; } }", @" class C { public C([||]string p_t_s_End) { S = p_t_s_End; } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestBaseNameEmpty() { await TestMissingAsync( @" class C { public C([||]string p__End) { } public string S { get; } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSomeBaseNamesEmpty() { // Currently, this case does not offer a refactoring because selecting multiple parameters // is not supported. If multiple parameters are supported in the future, this case should // be updated to verify that only the parameter name that does not have an empty base is offered. await TestMissingAsync( @" class C { public C([|string p__End, string p_test_t|]) { } }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix))); } private TestParameters OmitIfDefault_Warning => new TestParameters(options: Option(CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault, NotificationOption2.Warning)); private TestParameters Never_Warning => new TestParameters(options: Option(CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Never, NotificationOption2.Warning)); private TestParameters Always_Warning => new TestParameters(options: Option(CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Always, NotificationOption2.Warning)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCreateFieldWithTopLevelNullability() { await TestInRegularAndScript1Async( @" #nullable enable class C { public C([||]string? s) { } }", @" #nullable enable class C { private readonly string? _s; public C(string? s) { _s = s; } }", index: 1, parameters: new TestParameters(options: options.FieldNamesAreCamelCaseWithUnderscorePrefix)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCreatePropertyWithTopLevelNullability() { await TestInRegularAndScript1Async( @" #nullable enable class C { public C([||]string? s) { } }", @" #nullable enable class C { public C(string? s) { S = s; } public string? S { get; } }", parameters: new TestParameters(options: options.PropertyNamesArePascalCase)); } [WorkItem(24526, "https://github.com/dotnet/roslyn/issues/24526")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSingleLineBlock_BraceOnNextLine() { await TestInRegularAndScript1Async( @" class C { public C([||]string s) { } }", @" class C { public C(string s) { S = s; } public string S { get; } }"); } [WorkItem(24526, "https://github.com/dotnet/roslyn/issues/24526")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestSingleLineBlock_BraceOnSameLine() { await TestInRegularAndScriptAsync( @" class C { public C([||]string s) { } }", @" class C { public C(string s) { S = s; } public string S { get; } }", options: this.Option(CSharpFormattingOptions2.NewLinesForBracesInMethods, false)); } [WorkItem(23308, "https://github.com/dotnet/roslyn/issues/23308")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateFieldIfParameterFollowsExistingFieldAssignment() { await TestInRegularAndScript1Async( @" class C { private readonly string s; public C(string s, [||]int i) { this.s = s; } }", @" class C { private readonly string s; private readonly int i; public C(string s, int i) { this.s = s; this.i = i; } }"); } [WorkItem(23308, "https://github.com/dotnet/roslyn/issues/23308")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateFieldIfParameterPrecedesExistingFieldAssignment() { await TestInRegularAndScript1Async( @" class C { private readonly string s; public C([||]int i, string s) { this.s = s; } }", @" class C { private readonly int i; private readonly string s; public C(int i, string s) { this.i = i; this.s = s; } }"); } [WorkItem(41824, "https://github.com/dotnet/roslyn/issues/41824")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestMissingInArgList() { await TestMissingInRegularAndScriptAsync( @" class C { private static void M() { M2(__arglist(1, 2, 3, 5, 6)); } public static void M2([||]__arglist) { } }"); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingFields1() { await TestInRegularAndScript1Async( @" class C { public C([||]int i, int j, int k) { } }", @" class C { private readonly int i; private readonly int j; private readonly int k; public C(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } }", index: 3); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingFields2() { await TestInRegularAndScript1Async( @" class C { private readonly int i; public C(int i, [||]int j, int k) { this.i = i; } }", @" class C { private readonly int i; private readonly int j; private readonly int k; public C(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } }", index: 2); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingFields3() { await TestInRegularAndScript1Async( @" class C { private readonly int j; public C([||]int i, int j, int k) { this.j = j; } }", @" class C { private readonly int i; private readonly int j; private readonly int k; public C(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } }", index: 2); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingFields4() { await TestInRegularAndScript1Async( @" class C { private readonly int k; public C([||]int i, int j, int k) { this.k = k; } }", @" class C { private readonly int i; private readonly int j; private readonly int k; public C(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } }", index: 2); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingProperties1() { await TestInRegularAndScript1Async( @" class C { public C([||]int i, int j, int k) { } }", @" class C { public C(int i, int j, int k) { I = i; J = j; K = k; } public int I { get; } public int J { get; } public int K { get; } }", index: 2); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingProperties2() { await TestInRegularAndScript1Async( @" class C { private readonly int i; public C(int i, [||]int j, int k) { this.i = i; } }", @" class C { private readonly int i; public C(int i, int j, int k) { this.i = i; J = j; K = k; } public int J { get; } public int K { get; } }", index: 3); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingProperties3() { await TestInRegularAndScript1Async( @" class C { private readonly int j; public C([||]int i, int j, int k) { this.j = j; } }", @" class C { private readonly int j; public C(int i, int j, int k) { I = i; this.j = j; K = k; } public int I { get; } public int K { get; } }", index: 3); } [WorkItem(35665, "https://github.com/dotnet/roslyn/issues/35665")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestGenerateRemainingProperties4() { await TestInRegularAndScript1Async( @" class C { private readonly int k; public C([||]int i, int j, int k) { this.k = k; } }", @" class C { private readonly int k; public C(int i, int j, int k) { I = i; J = j; this.k = k; } public int I { get; } public int J { get; } }", index: 3); } [WorkItem(53467, "https://github.com/dotnet/roslyn/issues/53467")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestMissingWhenTypeNotInCompilation() { await TestMissingInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1""> <Document> public class Foo { public Foo(int prop1) { Prop1 = prop1; } public int Prop1 { get; } } public class Bar : Foo { public Bar(int prop1, int [||]prop2) : base(prop1) { } } </Document> </Project> </Workspace>"); } } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/CSharp/Portable/Classification/Worker_Preprocesser.cs
// 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.Classification; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal partial class Worker { private void ClassifyPreprocessorDirective(DirectiveTriviaSyntax node) { if (!_textSpan.OverlapsWith(node.Span)) { return; } switch (node.Kind()) { case SyntaxKind.IfDirectiveTrivia: ClassifyIfDirective((IfDirectiveTriviaSyntax)node); break; case SyntaxKind.ElifDirectiveTrivia: ClassifyElifDirective((ElifDirectiveTriviaSyntax)node); break; case SyntaxKind.ElseDirectiveTrivia: ClassifyElseDirective((ElseDirectiveTriviaSyntax)node); break; case SyntaxKind.EndIfDirectiveTrivia: ClassifyEndIfDirective((EndIfDirectiveTriviaSyntax)node); break; case SyntaxKind.RegionDirectiveTrivia: ClassifyRegionDirective((RegionDirectiveTriviaSyntax)node); break; case SyntaxKind.EndRegionDirectiveTrivia: ClassifyEndRegionDirective((EndRegionDirectiveTriviaSyntax)node); break; case SyntaxKind.ErrorDirectiveTrivia: ClassifyErrorDirective((ErrorDirectiveTriviaSyntax)node); break; case SyntaxKind.WarningDirectiveTrivia: ClassifyWarningDirective((WarningDirectiveTriviaSyntax)node); break; case SyntaxKind.BadDirectiveTrivia: ClassifyBadDirective((BadDirectiveTriviaSyntax)node); break; case SyntaxKind.DefineDirectiveTrivia: ClassifyDefineDirective((DefineDirectiveTriviaSyntax)node); break; case SyntaxKind.UndefDirectiveTrivia: ClassifyUndefDirective((UndefDirectiveTriviaSyntax)node); break; case SyntaxKind.LineDirectiveTrivia: ClassifyLineDirective((LineDirectiveTriviaSyntax)node); break; case SyntaxKind.LineSpanDirectiveTrivia: ClassifyLineSpanDirective((LineSpanDirectiveTriviaSyntax)node); break; case SyntaxKind.PragmaChecksumDirectiveTrivia: ClassifyPragmaChecksumDirective((PragmaChecksumDirectiveTriviaSyntax)node); break; case SyntaxKind.PragmaWarningDirectiveTrivia: ClassifyPragmaWarningDirective((PragmaWarningDirectiveTriviaSyntax)node); break; case SyntaxKind.ReferenceDirectiveTrivia: ClassifyReferenceDirective((ReferenceDirectiveTriviaSyntax)node); break; case SyntaxKind.LoadDirectiveTrivia: ClassifyLoadDirective((LoadDirectiveTriviaSyntax)node); break; case SyntaxKind.NullableDirectiveTrivia: ClassifyNullableDirective((NullableDirectiveTriviaSyntax)node); break; } } private void ClassifyDirectiveTrivia(DirectiveTriviaSyntax node, bool allowComments = true) { var lastToken = node.EndOfDirectiveToken.GetPreviousToken(includeSkipped: false); foreach (var trivia in lastToken.TrailingTrivia) { // skip initial whitespace if (trivia.Kind() == SyntaxKind.WhitespaceTrivia) { continue; } ClassifyPreprocessorTrivia(trivia, allowComments); } foreach (var trivia in node.EndOfDirectiveToken.LeadingTrivia) { ClassifyPreprocessorTrivia(trivia, allowComments); } } private void ClassifyPreprocessorTrivia(SyntaxTrivia trivia, bool allowComments) { if (allowComments && trivia.Kind() == SyntaxKind.SingleLineCommentTrivia) { AddClassification(trivia, ClassificationTypeNames.Comment); } else { AddClassification(trivia, ClassificationTypeNames.PreprocessorText); } } private void ClassifyPreprocessorExpression(ExpressionSyntax? node) { if (node == null) { return; } if (node is LiteralExpressionSyntax literal) { // true or false AddClassification(literal.Token, ClassificationTypeNames.Keyword); } else if (node is IdentifierNameSyntax identifier) { // DEBUG AddClassification(identifier.Identifier, ClassificationTypeNames.Identifier); } else if (node is ParenthesizedExpressionSyntax parenExpression) { // (true) AddClassification(parenExpression.OpenParenToken, ClassificationTypeNames.Punctuation); ClassifyPreprocessorExpression(parenExpression.Expression); AddClassification(parenExpression.CloseParenToken, ClassificationTypeNames.Punctuation); } else if (node is PrefixUnaryExpressionSyntax prefixExpression) { // ! AddClassification(prefixExpression.OperatorToken, ClassificationTypeNames.Operator); ClassifyPreprocessorExpression(prefixExpression.Operand); } else if (node is BinaryExpressionSyntax binaryExpression) { // &&, ||, ==, != ClassifyPreprocessorExpression(binaryExpression.Left); AddClassification(binaryExpression.OperatorToken, ClassificationTypeNames.Operator); ClassifyPreprocessorExpression(binaryExpression.Right); } } private void ClassifyIfDirective(IfDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.IfKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyPreprocessorExpression(node.Condition); ClassifyDirectiveTrivia(node); } private void ClassifyElifDirective(ElifDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ElifKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyPreprocessorExpression(node.Condition); ClassifyDirectiveTrivia(node); } private void ClassifyElseDirective(ElseDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ElseKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyEndIfDirective(EndIfDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.EndIfKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyErrorDirective(ErrorDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ErrorKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node, allowComments: false); } private void ClassifyWarningDirective(WarningDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.WarningKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node, allowComments: false); } private void ClassifyRegionDirective(RegionDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.RegionKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node, allowComments: false); } private void ClassifyEndRegionDirective(EndRegionDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.EndRegionKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyDefineDirective(DefineDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.DefineKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.Name, ClassificationTypeNames.Identifier); ClassifyDirectiveTrivia(node); } private void ClassifyUndefDirective(UndefDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.UndefKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.Name, ClassificationTypeNames.Identifier); ClassifyDirectiveTrivia(node); } private void ClassifyBadDirective(BadDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.Identifier, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyLineDirective(LineDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.LineKeyword, ClassificationTypeNames.PreprocessorKeyword); switch (node.Line.Kind()) { case SyntaxKind.HiddenKeyword: case SyntaxKind.DefaultKeyword: AddClassification(node.Line, ClassificationTypeNames.PreprocessorKeyword); break; case SyntaxKind.NumericLiteralToken: AddClassification(node.Line, ClassificationTypeNames.NumericLiteral); break; } AddOptionalClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyLineSpanDirective(LineSpanDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.LineKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyLineDirectivePosition(node.Start); AddClassification(node.MinusToken, ClassificationTypeNames.Operator); ClassifyLineDirectivePosition(node.End); AddOptionalClassification(node.CharacterOffset, ClassificationTypeNames.NumericLiteral); AddOptionalClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void AddOptionalClassification(SyntaxToken token, string classification) { if (token.Kind() != SyntaxKind.None) { AddClassification(token, classification); } } private void ClassifyLineDirectivePosition(LineDirectivePositionSyntax node) { AddClassification(node.OpenParenToken, ClassificationTypeNames.Punctuation); AddClassification(node.Line, ClassificationTypeNames.NumericLiteral); AddClassification(node.CommaToken, ClassificationTypeNames.Punctuation); AddClassification(node.Character, ClassificationTypeNames.NumericLiteral); AddClassification(node.CloseParenToken, ClassificationTypeNames.Punctuation); } private void ClassifyPragmaChecksumDirective(PragmaChecksumDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.PragmaKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ChecksumKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.File, ClassificationTypeNames.StringLiteral); AddClassification(node.Guid, ClassificationTypeNames.StringLiteral); AddClassification(node.Bytes, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyPragmaWarningDirective(PragmaWarningDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.PragmaKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.WarningKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.DisableOrRestoreKeyword, ClassificationTypeNames.PreprocessorKeyword); foreach (var nodeOrToken in node.ErrorCodes.GetWithSeparators()) { ClassifyNodeOrToken(nodeOrToken); } if (node.ErrorCodes.Count == 0) { // When there are no error codes, we need to classify the directive's trivia. // (When there are error codes, ClassifyNodeOrToken above takes care of that.) ClassifyDirectiveTrivia(node); } } private void ClassifyReferenceDirective(ReferenceDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ReferenceKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyLoadDirective(LoadDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.LoadKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyNullableDirective(NullableDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.NullableKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.SettingToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.TargetToken, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } } }
// 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.Classification; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal partial class Worker { private void ClassifyPreprocessorDirective(DirectiveTriviaSyntax node) { if (!_textSpan.OverlapsWith(node.Span)) { return; } switch (node.Kind()) { case SyntaxKind.IfDirectiveTrivia: ClassifyIfDirective((IfDirectiveTriviaSyntax)node); break; case SyntaxKind.ElifDirectiveTrivia: ClassifyElifDirective((ElifDirectiveTriviaSyntax)node); break; case SyntaxKind.ElseDirectiveTrivia: ClassifyElseDirective((ElseDirectiveTriviaSyntax)node); break; case SyntaxKind.EndIfDirectiveTrivia: ClassifyEndIfDirective((EndIfDirectiveTriviaSyntax)node); break; case SyntaxKind.RegionDirectiveTrivia: ClassifyRegionDirective((RegionDirectiveTriviaSyntax)node); break; case SyntaxKind.EndRegionDirectiveTrivia: ClassifyEndRegionDirective((EndRegionDirectiveTriviaSyntax)node); break; case SyntaxKind.ErrorDirectiveTrivia: ClassifyErrorDirective((ErrorDirectiveTriviaSyntax)node); break; case SyntaxKind.WarningDirectiveTrivia: ClassifyWarningDirective((WarningDirectiveTriviaSyntax)node); break; case SyntaxKind.BadDirectiveTrivia: ClassifyBadDirective((BadDirectiveTriviaSyntax)node); break; case SyntaxKind.DefineDirectiveTrivia: ClassifyDefineDirective((DefineDirectiveTriviaSyntax)node); break; case SyntaxKind.UndefDirectiveTrivia: ClassifyUndefDirective((UndefDirectiveTriviaSyntax)node); break; case SyntaxKind.LineDirectiveTrivia: ClassifyLineDirective((LineDirectiveTriviaSyntax)node); break; case SyntaxKind.LineSpanDirectiveTrivia: ClassifyLineSpanDirective((LineSpanDirectiveTriviaSyntax)node); break; case SyntaxKind.PragmaChecksumDirectiveTrivia: ClassifyPragmaChecksumDirective((PragmaChecksumDirectiveTriviaSyntax)node); break; case SyntaxKind.PragmaWarningDirectiveTrivia: ClassifyPragmaWarningDirective((PragmaWarningDirectiveTriviaSyntax)node); break; case SyntaxKind.ReferenceDirectiveTrivia: ClassifyReferenceDirective((ReferenceDirectiveTriviaSyntax)node); break; case SyntaxKind.LoadDirectiveTrivia: ClassifyLoadDirective((LoadDirectiveTriviaSyntax)node); break; case SyntaxKind.NullableDirectiveTrivia: ClassifyNullableDirective((NullableDirectiveTriviaSyntax)node); break; } } private void ClassifyDirectiveTrivia(DirectiveTriviaSyntax node, bool allowComments = true) { var lastToken = node.EndOfDirectiveToken.GetPreviousToken(includeSkipped: false); foreach (var trivia in lastToken.TrailingTrivia) { // skip initial whitespace if (trivia.Kind() == SyntaxKind.WhitespaceTrivia) { continue; } ClassifyPreprocessorTrivia(trivia, allowComments); } foreach (var trivia in node.EndOfDirectiveToken.LeadingTrivia) { ClassifyPreprocessorTrivia(trivia, allowComments); } } private void ClassifyPreprocessorTrivia(SyntaxTrivia trivia, bool allowComments) { if (allowComments && trivia.Kind() == SyntaxKind.SingleLineCommentTrivia) { AddClassification(trivia, ClassificationTypeNames.Comment); } else { AddClassification(trivia, ClassificationTypeNames.PreprocessorText); } } private void ClassifyPreprocessorExpression(ExpressionSyntax? node) { if (node == null) { return; } if (node is LiteralExpressionSyntax literal) { // true or false AddClassification(literal.Token, ClassificationTypeNames.Keyword); } else if (node is IdentifierNameSyntax identifier) { // DEBUG AddClassification(identifier.Identifier, ClassificationTypeNames.Identifier); } else if (node is ParenthesizedExpressionSyntax parenExpression) { // (true) AddClassification(parenExpression.OpenParenToken, ClassificationTypeNames.Punctuation); ClassifyPreprocessorExpression(parenExpression.Expression); AddClassification(parenExpression.CloseParenToken, ClassificationTypeNames.Punctuation); } else if (node is PrefixUnaryExpressionSyntax prefixExpression) { // ! AddClassification(prefixExpression.OperatorToken, ClassificationTypeNames.Operator); ClassifyPreprocessorExpression(prefixExpression.Operand); } else if (node is BinaryExpressionSyntax binaryExpression) { // &&, ||, ==, != ClassifyPreprocessorExpression(binaryExpression.Left); AddClassification(binaryExpression.OperatorToken, ClassificationTypeNames.Operator); ClassifyPreprocessorExpression(binaryExpression.Right); } } private void ClassifyIfDirective(IfDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.IfKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyPreprocessorExpression(node.Condition); ClassifyDirectiveTrivia(node); } private void ClassifyElifDirective(ElifDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ElifKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyPreprocessorExpression(node.Condition); ClassifyDirectiveTrivia(node); } private void ClassifyElseDirective(ElseDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ElseKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyEndIfDirective(EndIfDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.EndIfKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyErrorDirective(ErrorDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ErrorKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node, allowComments: false); } private void ClassifyWarningDirective(WarningDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.WarningKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node, allowComments: false); } private void ClassifyRegionDirective(RegionDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.RegionKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node, allowComments: false); } private void ClassifyEndRegionDirective(EndRegionDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.EndRegionKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyDefineDirective(DefineDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.DefineKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.Name, ClassificationTypeNames.Identifier); ClassifyDirectiveTrivia(node); } private void ClassifyUndefDirective(UndefDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.UndefKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.Name, ClassificationTypeNames.Identifier); ClassifyDirectiveTrivia(node); } private void ClassifyBadDirective(BadDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.Identifier, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyLineDirective(LineDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.LineKeyword, ClassificationTypeNames.PreprocessorKeyword); switch (node.Line.Kind()) { case SyntaxKind.HiddenKeyword: case SyntaxKind.DefaultKeyword: AddClassification(node.Line, ClassificationTypeNames.PreprocessorKeyword); break; case SyntaxKind.NumericLiteralToken: AddClassification(node.Line, ClassificationTypeNames.NumericLiteral); break; } AddOptionalClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyLineSpanDirective(LineSpanDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.LineKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyLineDirectivePosition(node.Start); AddClassification(node.MinusToken, ClassificationTypeNames.Operator); ClassifyLineDirectivePosition(node.End); AddOptionalClassification(node.CharacterOffset, ClassificationTypeNames.NumericLiteral); AddOptionalClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void AddOptionalClassification(SyntaxToken token, string classification) { if (token.Kind() != SyntaxKind.None) { AddClassification(token, classification); } } private void ClassifyLineDirectivePosition(LineDirectivePositionSyntax node) { AddClassification(node.OpenParenToken, ClassificationTypeNames.Punctuation); AddClassification(node.Line, ClassificationTypeNames.NumericLiteral); AddClassification(node.CommaToken, ClassificationTypeNames.Punctuation); AddClassification(node.Character, ClassificationTypeNames.NumericLiteral); AddClassification(node.CloseParenToken, ClassificationTypeNames.Punctuation); } private void ClassifyPragmaChecksumDirective(PragmaChecksumDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.PragmaKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ChecksumKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.File, ClassificationTypeNames.StringLiteral); AddClassification(node.Guid, ClassificationTypeNames.StringLiteral); AddClassification(node.Bytes, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyPragmaWarningDirective(PragmaWarningDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.PragmaKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.WarningKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.DisableOrRestoreKeyword, ClassificationTypeNames.PreprocessorKeyword); foreach (var nodeOrToken in node.ErrorCodes.GetWithSeparators()) { ClassifyNodeOrToken(nodeOrToken); } if (node.ErrorCodes.Count == 0) { // When there are no error codes, we need to classify the directive's trivia. // (When there are error codes, ClassifyNodeOrToken above takes care of that.) ClassifyDirectiveTrivia(node); } } private void ClassifyReferenceDirective(ReferenceDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ReferenceKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyLoadDirective(LoadDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.LoadKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyNullableDirective(NullableDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.NullableKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.SettingToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.TargetToken, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/GenerateTypeDialog_InProc.cs
// 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 System.Linq; using System.Threading; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType; using Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class GenerateTypeDialog_InProc : AbstractCodeRefactorDialog_InProc<GenerateTypeDialog, GenerateTypeDialog.TestAccessor> { private GenerateTypeDialog_InProc() { } public static GenerateTypeDialog_InProc Create() => new GenerateTypeDialog_InProc(); public override void VerifyOpen() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { // Thread.Yield is insufficient; something in the light bulb must be relying on a UI thread // message at lower priority than the Background priority used in testing. WaitForApplicationIdle(Helper.HangMitigatingTimeout); continue; } WaitForApplicationIdle(Helper.HangMitigatingTimeout); return; } } } public bool CloseWindow() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null) { return false; } } ClickCancel(); return true; } public void ClickOK() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token)); } } public void ClickCancel() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token)); } } public void SetAccessibility(string accessibility) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AccessListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, accessibility)); }); } } public void SetKind(string kind) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().KindListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, kind)); }); } } public void SetTargetProject(string projectName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().ProjectListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, projectName)); }); } } public void SetTargetFileToNewName(string newFileName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().CreateNewFileRadioButton.SimulateClickAsync(JoinableTaskFactory)); Contract.ThrowIfFalse(await dialog.GetTestAccessor().CreateNewFileComboBox.SimulateSelectItemAsync(JoinableTaskFactory, newFileName, mustExist: false)); }); } } public void SetTargetFileToExisting(string existingFileName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AddToExistingFileRadioButton.SimulateClickAsync(JoinableTaskFactory)); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AddToExistingFileComboBox.SimulateSelectItemAsync(JoinableTaskFactory, existingFileName, mustExist: false)); }); } } public string[] GetNewFileComboBoxItems() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { return JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); return dialog.GetTestAccessor().CreateNewFileComboBox.Items.Cast<string>().ToArray(); }); } } protected override GenerateTypeDialog.TestAccessor GetAccessor(GenerateTypeDialog dialog) => dialog.GetTestAccessor(); } }
// 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 System.Linq; using System.Threading; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType; using Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class GenerateTypeDialog_InProc : AbstractCodeRefactorDialog_InProc<GenerateTypeDialog, GenerateTypeDialog.TestAccessor> { private GenerateTypeDialog_InProc() { } public static GenerateTypeDialog_InProc Create() => new GenerateTypeDialog_InProc(); public override void VerifyOpen() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { // Thread.Yield is insufficient; something in the light bulb must be relying on a UI thread // message at lower priority than the Background priority used in testing. WaitForApplicationIdle(Helper.HangMitigatingTimeout); continue; } WaitForApplicationIdle(Helper.HangMitigatingTimeout); return; } } } public bool CloseWindow() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null) { return false; } } ClickCancel(); return true; } public void ClickOK() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token)); } } public void ClickCancel() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token)); } } public void SetAccessibility(string accessibility) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AccessListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, accessibility)); }); } } public void SetKind(string kind) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().KindListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, kind)); }); } } public void SetTargetProject(string projectName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().ProjectListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, projectName)); }); } } public void SetTargetFileToNewName(string newFileName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().CreateNewFileRadioButton.SimulateClickAsync(JoinableTaskFactory)); Contract.ThrowIfFalse(await dialog.GetTestAccessor().CreateNewFileComboBox.SimulateSelectItemAsync(JoinableTaskFactory, newFileName, mustExist: false)); }); } } public void SetTargetFileToExisting(string existingFileName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AddToExistingFileRadioButton.SimulateClickAsync(JoinableTaskFactory)); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AddToExistingFileComboBox.SimulateSelectItemAsync(JoinableTaskFactory, existingFileName, mustExist: false)); }); } } public string[] GetNewFileComboBoxItems() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { return JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); return dialog.GetTestAccessor().CreateNewFileComboBox.Items.Cast<string>().ToArray(); }); } } protected override GenerateTypeDialog.TestAccessor GetAccessor(GenerateTypeDialog dialog) => dialog.GetTestAccessor(); } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenDisplayClassOptimisationTests.cs
// 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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenDisplayClassOptimizationTests : CSharpTestBase { private static void VerifyTypeIL(CompilationVerifier compilation, string typeName, string expected) { // .Net Core has different assemblies for the same standard library types as .Net Framework, meaning that that the emitted output will be different to the expected if we run them .Net Core // Since we do not expect there to be any meaningful differences between output for .Net Core and .Net Framework, we will skip these tests on .Net Core if (ExecutionConditionUtil.IsDesktop) { compilation.VerifyTypeIL(typeName, expected); } } [Fact] public void WhenOptimisationsAreEnabled_MergeDisplayClasses() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { int a = 1; { int b = 2; Func<int> c = () => a + b; Console.WriteLine(c()); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3", options: TestOptions.ReleaseExe); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x207a // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance int32 '<Main>b__0' () cil managed { // Method begins at RVA 0x2082 // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 41 (0x29) .maxstack 8 .entrypoint IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: ldc.i4.1 IL_0007: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000c: dup IL_000d: ldc.i4.2 IL_000e: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0013: ldftn instance int32 Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_0019: newobj instance void class [mscorlib]System.Func`1<int32>::.ctor(object, native int) IL_001e: callvirt instance !0 class [mscorlib]System.Func`1<int32>::Invoke() IL_0023: call void [mscorlib]System.Console::WriteLine(int32) IL_0028: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void WhenOptimisationsAreDisabled_DoNotMergeDisplayClasses() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { int a = 1; { int b = 2; Func<int> c = () => a + b; Console.WriteLine(c()); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3", options: TestOptions.DebugExe); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209a // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209a // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance int32 '<Main>b__0' () cil managed { // Method begins at RVA 0x20a3 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 62 (0x3e) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class Program/'<>c__DisplayClass0_1', [2] class [mscorlib]System.Func`1<int32> ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000e: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: ldloc.0 IL_0016: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_001b: nop IL_001c: ldloc.1 IL_001d: ldc.i4.2 IL_001e: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0023: ldloc.1 IL_0024: ldftn instance int32 Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_002a: newobj instance void class [mscorlib]System.Func`1<int32>::.ctor(object, native int) IL_002f: stloc.2 IL_0030: ldloc.2 IL_0031: callvirt instance !0 class [mscorlib]System.Func`1<int32>::Invoke() IL_0036: call void [mscorlib]System.Console::WriteLine(int32) IL_003b: nop IL_003c: nop IL_003d: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForWithBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; for (var i = 0; i < strings.Count; i++) { int x = i; actions.Add(() => { Console.WriteLine(strings[i - x - 1]); }); } actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"three two one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2115 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2115 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x211d // Code size 42 (0x2a) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_001c: sub IL_001d: ldc.i4.1 IL_001e: sub IL_001f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0024: call void [mscorlib]System.Console::WriteLine(string) IL_0029: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 185 (0xb9) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class Program/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_003f: br.s IL_0081 // loop start (head: IL_0081) IL_0041: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0046: stloc.2 IL_0047: ldloc.2 IL_0048: ldloc.0 IL_0049: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_004e: ldloc.2 IL_004f: ldloc.2 IL_0050: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0055: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_005a: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_005f: ldloc.1 IL_0060: ldloc.2 IL_0061: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0067: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_006c: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0071: ldloc.0 IL_0072: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0077: stloc.3 IL_0078: ldloc.0 IL_0079: ldloc.3 IL_007a: ldc.i4.1 IL_007b: add IL_007c: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0081: ldloc.0 IL_0082: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0087: ldloc.0 IL_0088: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_008d: callvirt instance int32 class [mscorlib]System.Collections.Generic.List`1<string>::get_Count() IL_0092: blt.s IL_0041 // end loop IL_0094: ldloc.1 IL_0095: ldc.i4.0 IL_0096: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_009b: callvirt instance void [mscorlib]System.Action::Invoke() IL_00a0: ldloc.1 IL_00a1: ldc.i4.1 IL_00a2: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00a7: callvirt instance void [mscorlib]System.Action::Invoke() IL_00ac: ldloc.1 IL_00ad: ldc.i4.2 IL_00ae: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00b3: callvirt instance void [mscorlib]System.Action::Invoke() IL_00b8: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForInsideWhileCorrectDisplayClassesAreCreated() { var source = @"using System; class C { public static void Main() { int x = 0; int y = 0; while (y < 10) { for (int i = 0; i < 10; i++) { Func<int> f = () => i + x; } y++; } } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "C", @" .class private auto ansi beforefieldinit C extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a7 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 i .field public class C/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a7 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance int32 '<Main>b__0' () cil managed { // Method begins at RVA 0x20af // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<>c__DisplayClass0_1'::i IL_0006: ldarg.0 IL_0007: ldfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000c: ldfld int32 C/'<>c__DisplayClass0_0'::x IL_0011: add IL_0012: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 75 (0x4b) .maxstack 3 .locals init ( [0] class C/'<>c__DisplayClass0_0', [1] int32, [2] class C/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void C/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 C/'<>c__DisplayClass0_0'::x IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br.s IL_0045 // loop start (head: IL_0045) IL_0011: newobj instance void C/'<>c__DisplayClass0_1'::.ctor() IL_0016: stloc.2 IL_0017: ldloc.2 IL_0018: ldloc.0 IL_0019: stfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_001e: ldloc.2 IL_001f: ldc.i4.0 IL_0020: stfld int32 C/'<>c__DisplayClass0_1'::i IL_0025: br.s IL_0037 // loop start (head: IL_0037) IL_0027: ldloc.2 IL_0028: ldfld int32 C/'<>c__DisplayClass0_1'::i IL_002d: stloc.3 IL_002e: ldloc.2 IL_002f: ldloc.3 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stfld int32 C/'<>c__DisplayClass0_1'::i IL_0037: ldloc.2 IL_0038: ldfld int32 C/'<>c__DisplayClass0_1'::i IL_003d: ldc.i4.s 10 IL_003f: blt.s IL_0027 // end loop IL_0041: ldloc.1 IL_0042: ldc.i4.1 IL_0043: add IL_0044: stloc.1 IL_0045: ldloc.1 IL_0046: ldc.i4.s 10 IL_0048: blt.s IL_0011 // end loop IL_004a: ret } // end of method C::Main .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a7 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor } // end of class C"); } [Fact] public void ForInsideEmptyForCorrectDisplayClassesAreCreated() { var source = @"using System; class C { public static void Main() { int x = 0; int y = 0; for(;;) { for (int i = 0; i < 10; i++) { Func<int> f = () => i + x; } y++; break; } } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "C", @" .class private auto ansi beforefieldinit C extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 i .field public class C/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance int32 '<Main>b__0' () cil managed { // Method begins at RVA 0x20a8 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<>c__DisplayClass0_1'::i IL_0006: ldarg.0 IL_0007: ldfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000c: ldfld int32 C/'<>c__DisplayClass0_0'::x IL_0011: add IL_0012: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 68 (0x44) .maxstack 3 .locals init ( [0] class C/'<>c__DisplayClass0_0', [1] int32, [2] class C/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void C/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 C/'<>c__DisplayClass0_0'::x IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: newobj instance void C/'<>c__DisplayClass0_1'::.ctor() IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.0 IL_0017: stfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_001c: ldloc.2 IL_001d: ldc.i4.0 IL_001e: stfld int32 C/'<>c__DisplayClass0_1'::i IL_0023: br.s IL_0035 // loop start (head: IL_0035) IL_0025: ldloc.2 IL_0026: ldfld int32 C/'<>c__DisplayClass0_1'::i IL_002b: stloc.3 IL_002c: ldloc.2 IL_002d: ldloc.3 IL_002e: ldc.i4.1 IL_002f: add IL_0030: stfld int32 C/'<>c__DisplayClass0_1'::i IL_0035: ldloc.2 IL_0036: ldfld int32 C/'<>c__DisplayClass0_1'::i IL_003b: ldc.i4.s 10 IL_003d: blt.s IL_0025 // end loop IL_003f: ldloc.1 IL_0040: ldc.i4.1 IL_0041: add IL_0042: stloc.1 IL_0043: ret } // end of method C::Main .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor } // end of class C"); } [Fact] public void ForWithoutBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; for (var i = 0; i < strings.Count; i++) actions.Add(i is int x ? (Action)(() => Console.WriteLine(strings[i - x - 1])) : () => {}); actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"three two one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2115 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2115 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x211d // Code size 42 (0x2a) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_001c: sub IL_001d: ldc.i4.1 IL_001e: sub IL_001f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0024: call void [mscorlib]System.Console::WriteLine(string) IL_0029: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x2148 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2115 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x2154 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 185 (0xb9) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class Program/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_003f: br.s IL_0081 // loop start (head: IL_0081) IL_0041: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0046: stloc.2 IL_0047: ldloc.2 IL_0048: ldloc.0 IL_0049: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_004e: ldloc.1 IL_004f: ldloc.2 IL_0050: ldloc.2 IL_0051: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0056: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_005b: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_0060: ldloc.2 IL_0061: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0067: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_006c: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0071: ldloc.0 IL_0072: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0077: stloc.3 IL_0078: ldloc.0 IL_0079: ldloc.3 IL_007a: ldc.i4.1 IL_007b: add IL_007c: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0081: ldloc.0 IL_0082: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0087: ldloc.0 IL_0088: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_008d: callvirt instance int32 class [mscorlib]System.Collections.Generic.List`1<string>::get_Count() IL_0092: blt.s IL_0041 // end loop IL_0094: ldloc.1 IL_0095: ldc.i4.0 IL_0096: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_009b: callvirt instance void [mscorlib]System.Action::Invoke() IL_00a0: ldloc.1 IL_00a1: ldc.i4.1 IL_00a2: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00a7: callvirt instance void [mscorlib]System.Action::Invoke() IL_00ac: ldloc.1 IL_00ad: ldc.i4.2 IL_00ae: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00b3: callvirt instance void [mscorlib]System.Action::Invoke() IL_00b8: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForeachWithBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; using System.Linq; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; foreach (var i in Enumerable.Range(0,3)) { int x = i; actions.Add(() => { Console.WriteLine(strings[i - x]); }); } actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"one one one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2124 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 i .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2124 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x212c // Code size 35 (0x23) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_0011: ldarg.0 IL_0012: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_0017: sub IL_0018: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_001d: call void [mscorlib]System.Console::WriteLine(string) IL_0022: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 183 (0xb7) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>, [3] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldc.i4.0 IL_0039: ldc.i4.3 IL_003a: call class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> [System.Core]System.Linq.Enumerable::Range(int32, int32) IL_003f: callvirt instance class [mscorlib]System.Collections.Generic.IEnumerator`1<!0> class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>::GetEnumerator() IL_0044: stloc.2 .try { IL_0045: br.s IL_007e // loop start (head: IL_007e) IL_0047: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_004c: stloc.3 IL_004d: ldloc.3 IL_004e: ldloc.0 IL_004f: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0054: ldloc.3 IL_0055: ldloc.2 IL_0056: callvirt instance !0 class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>::get_Current() IL_005b: stfld int32 Program/'<>c__DisplayClass0_1'::i IL_0060: ldloc.3 IL_0061: ldloc.3 IL_0062: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_0067: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_006c: ldloc.1 IL_006d: ldloc.3 IL_006e: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0074: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0079: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_007e: ldloc.2 IL_007f: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() IL_0084: brtrue.s IL_0047 // end loop IL_0086: leave.s IL_0092 } // end .try finally { IL_0088: ldloc.2 IL_0089: brfalse.s IL_0091 IL_008b: ldloc.2 IL_008c: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_0091: endfinally } // end handler IL_0092: ldloc.1 IL_0093: ldc.i4.0 IL_0094: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0099: callvirt instance void [mscorlib]System.Action::Invoke() IL_009e: ldloc.1 IL_009f: ldc.i4.1 IL_00a0: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00a5: callvirt instance void [mscorlib]System.Action::Invoke() IL_00aa: ldloc.1 IL_00ab: ldc.i4.2 IL_00ac: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00b1: callvirt instance void [mscorlib]System.Action::Invoke() IL_00b6: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForeachWithoutBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; using System.Linq; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; foreach (var i in Enumerable.Range(0,3)) actions.Add(i is int x ? (Action)(() => Console.WriteLine(strings[i - x])) : () => {}); actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"one one one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2124 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 i .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2124 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x212c // Code size 35 (0x23) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_0011: ldarg.0 IL_0012: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_0017: sub IL_0018: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_001d: call void [mscorlib]System.Console::WriteLine(string) IL_0022: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x2150 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2124 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x215c // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 183 (0xb7) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>, [3] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldc.i4.0 IL_0039: ldc.i4.3 IL_003a: call class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> [System.Core]System.Linq.Enumerable::Range(int32, int32) IL_003f: callvirt instance class [mscorlib]System.Collections.Generic.IEnumerator`1<!0> class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>::GetEnumerator() IL_0044: stloc.2 .try { IL_0045: br.s IL_007e // loop start (head: IL_007e) IL_0047: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_004c: stloc.3 IL_004d: ldloc.3 IL_004e: ldloc.0 IL_004f: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0054: ldloc.3 IL_0055: ldloc.2 IL_0056: callvirt instance !0 class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>::get_Current() IL_005b: stfld int32 Program/'<>c__DisplayClass0_1'::i IL_0060: ldloc.1 IL_0061: ldloc.3 IL_0062: ldloc.3 IL_0063: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_0068: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_006d: ldloc.3 IL_006e: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0074: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0079: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_007e: ldloc.2 IL_007f: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() IL_0084: brtrue.s IL_0047 // end loop IL_0086: leave.s IL_0092 } // end .try finally { IL_0088: ldloc.2 IL_0089: brfalse.s IL_0091 IL_008b: ldloc.2 IL_008c: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_0091: endfinally } // end handler IL_0092: ldloc.1 IL_0093: ldc.i4.0 IL_0094: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0099: callvirt instance void [mscorlib]System.Action::Invoke() IL_009e: ldloc.1 IL_009f: ldc.i4.1 IL_00a0: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00a5: callvirt instance void [mscorlib]System.Action::Invoke() IL_00aa: ldloc.1 IL_00ab: ldc.i4.2 IL_00ac: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00b1: callvirt instance void [mscorlib]System.Action::Invoke() IL_00b6: ret } // end of method Program::Main } // end of class Program"); } [CompilerTrait(CompilerFeature.AsyncStreams)] [Fact] public void AwaitForeachCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; using System.Linq; public class C { public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { public int Current { get; } public System.Threading.Tasks.Task<bool> MoveNextAsync() => null; } } public class Program { public static async void M(C enumerable) { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; await foreach (var i in enumerable) actions.Add(i is int x ? (Action)(() => Console.WriteLine(strings[i - x])) : () => {}); actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 i .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<M>b__0' () cil managed { // Method begins at RVA 0x209e // Code size 35 (0x23) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_0011: ldarg.0 IL_0012: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_0017: sub IL_0018: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_001d: call void [mscorlib]System.Console::WriteLine(string) IL_0022: ret } // end of method '<>c__DisplayClass0_1'::'<M>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x20c2 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<M>b__0_1' () cil managed { // Method begins at RVA 0x20ce // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<M>b__0_1' } // end of class <>c .class nested private auto ansi sealed beforefieldinit '<M>d__0' extends [mscorlib]System.ValueType implements [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 '<>1__state' .field public valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder '<>t__builder' .field public class C enumerable .field private class Program/'<>c__DisplayClass0_0' '<>8__1' .field private class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> '<actions>5__2' .field private class C/Enumerator '<>7__wrap2' .field private valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool> '<>u__1' // Methods .method private final hidebysig newslot virtual instance void MoveNext () cil managed { .override method instance void [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine::MoveNext() // Method begins at RVA 0x20d0 // Code size 416 (0x1a0) .maxstack 4 .locals init ( [0] int32, [1] valuetype [mscorlib]System.Threading.CancellationToken, [2] class Program/'<>c__DisplayClass0_1', [3] valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool>, [4] class [mscorlib]System.Exception ) IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<M>d__0'::'<>1__state' IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse IL_00f3 IL_000d: ldarg.0 IL_000e: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0013: stfld class Program/'<>c__DisplayClass0_0' Program/'<M>d__0'::'<>8__1' IL_0018: ldarg.0 IL_0019: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_001e: stfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_0023: ldarg.0 IL_0024: ldfld class Program/'<>c__DisplayClass0_0' Program/'<M>d__0'::'<>8__1' IL_0029: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_002e: dup IL_002f: ldstr ""one"" IL_0034: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0039: dup IL_003a: ldstr ""two"" IL_003f: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0044: dup IL_0045: ldstr ""three"" IL_004a: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_004f: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0054: ldarg.0 IL_0055: ldarg.0 IL_0056: ldfld class C Program/'<M>d__0'::enumerable IL_005b: ldloca.s 1 IL_005d: initobj [mscorlib]System.Threading.CancellationToken IL_0063: ldloc.1 IL_0064: callvirt instance class C/Enumerator C::GetAsyncEnumerator(valuetype [mscorlib]System.Threading.CancellationToken) IL_0069: stfld class C/Enumerator Program/'<M>d__0'::'<>7__wrap2' IL_006e: br.s IL_00b6 IL_0070: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0075: stloc.2 IL_0076: ldloc.2 IL_0077: ldarg.0 IL_0078: ldfld class Program/'<>c__DisplayClass0_0' Program/'<M>d__0'::'<>8__1' IL_007d: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0082: ldloc.2 IL_0083: ldarg.0 IL_0084: ldfld class C/Enumerator Program/'<M>d__0'::'<>7__wrap2' IL_0089: callvirt instance int32 C/Enumerator::get_Current() IL_008e: stfld int32 Program/'<>c__DisplayClass0_1'::i IL_0093: ldarg.0 IL_0094: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_0099: ldloc.2 IL_009a: ldloc.2 IL_009b: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_00a0: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_00a5: ldloc.2 IL_00a6: ldftn instance void Program/'<>c__DisplayClass0_1'::'<M>b__0'() IL_00ac: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_00b1: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_00b6: ldarg.0 IL_00b7: ldfld class C/Enumerator Program/'<M>d__0'::'<>7__wrap2' IL_00bc: callvirt instance class [mscorlib]System.Threading.Tasks.Task`1<bool> C/Enumerator::MoveNextAsync() IL_00c1: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<!0> class [mscorlib]System.Threading.Tasks.Task`1<bool>::GetAwaiter() IL_00c6: stloc.3 IL_00c7: ldloca.s 3 IL_00c9: call instance bool valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool>::get_IsCompleted() IL_00ce: brtrue.s IL_010f IL_00d0: ldarg.0 IL_00d1: ldc.i4.0 IL_00d2: dup IL_00d3: stloc.0 IL_00d4: stfld int32 Program/'<M>d__0'::'<>1__state' IL_00d9: ldarg.0 IL_00da: ldloc.3 IL_00db: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool> Program/'<M>d__0'::'<>u__1' IL_00e0: ldarg.0 IL_00e1: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program/'<M>d__0'::'<>t__builder' IL_00e6: ldloca.s 3 IL_00e8: ldarg.0 IL_00e9: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool>, valuetype Program/'<M>d__0'>(!!0&, !!1&) IL_00ee: leave IL_019f IL_00f3: ldarg.0 IL_00f4: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool> Program/'<M>d__0'::'<>u__1' IL_00f9: stloc.3 IL_00fa: ldarg.0 IL_00fb: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool> Program/'<M>d__0'::'<>u__1' IL_0100: initobj valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool> IL_0106: ldarg.0 IL_0107: ldc.i4.m1 IL_0108: dup IL_0109: stloc.0 IL_010a: stfld int32 Program/'<M>d__0'::'<>1__state' IL_010f: ldloca.s 3 IL_0111: call instance !0 valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool>::GetResult() IL_0116: brtrue IL_0070 IL_011b: ldarg.0 IL_011c: ldnull IL_011d: stfld class C/Enumerator Program/'<M>d__0'::'<>7__wrap2' IL_0122: ldarg.0 IL_0123: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_0128: ldc.i4.0 IL_0129: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_012e: callvirt instance void [mscorlib]System.Action::Invoke() IL_0133: ldarg.0 IL_0134: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_0139: ldc.i4.1 IL_013a: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_013f: callvirt instance void [mscorlib]System.Action::Invoke() IL_0144: ldarg.0 IL_0145: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_014a: ldc.i4.2 IL_014b: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0150: callvirt instance void [mscorlib]System.Action::Invoke() IL_0155: leave.s IL_017e } // end .try catch [mscorlib]System.Exception { IL_0157: stloc.s 4 IL_0159: ldarg.0 IL_015a: ldc.i4.s -2 IL_015c: stfld int32 Program/'<M>d__0'::'<>1__state' IL_0161: ldarg.0 IL_0162: ldnull IL_0163: stfld class Program/'<>c__DisplayClass0_0' Program/'<M>d__0'::'<>8__1' IL_0168: ldarg.0 IL_0169: ldnull IL_016a: stfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_016f: ldarg.0 IL_0170: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program/'<M>d__0'::'<>t__builder' IL_0175: ldloc.s 4 IL_0177: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::SetException(class [mscorlib]System.Exception) IL_017c: leave.s IL_019f } // end handler IL_017e: ldarg.0 IL_017f: ldc.i4.s -2 IL_0181: stfld int32 Program/'<M>d__0'::'<>1__state' IL_0186: ldarg.0 IL_0187: ldnull IL_0188: stfld class Program/'<>c__DisplayClass0_0' Program/'<M>d__0'::'<>8__1' IL_018d: ldarg.0 IL_018e: ldnull IL_018f: stfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_0194: ldarg.0 IL_0195: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program/'<M>d__0'::'<>t__builder' IL_019a: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::SetResult() IL_019f: ret } // end of method '<M>d__0'::MoveNext .method private final hidebysig newslot virtual instance void SetStateMachine ( class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine stateMachine ) cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance void [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine::SetStateMachine(class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine) // Method begins at RVA 0x2298 // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program/'<M>d__0'::'<>t__builder' IL_0006: ldarg.1 IL_0007: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::SetStateMachine(class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine) IL_000c: ret } // end of method '<M>d__0'::SetStateMachine } // end of class <M>d__0 // Methods .method public hidebysig static void M ( class C enumerable ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.AsyncStateMachineAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 0f 50 72 6f 67 72 61 6d 2b 3c 4d 3e 64 5f 5f 30 00 00 ) // Method begins at RVA 0x205c // Code size 43 (0x2b) .maxstack 2 .locals init ( [0] valuetype Program/'<M>d__0' ) IL_0000: ldloca.s 0 IL_0002: call valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::Create() IL_0007: stfld valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program/'<M>d__0'::'<>t__builder' IL_000c: ldloca.s 0 IL_000e: ldarg.0 IL_000f: stfld class C Program/'<M>d__0'::enumerable IL_0014: ldloca.s 0 IL_0016: ldc.i4.m1 IL_0017: stfld int32 Program/'<M>d__0'::'<>1__state' IL_001c: ldloca.s 0 IL_001e: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program/'<M>d__0'::'<>t__builder' IL_0023: ldloca.s 0 IL_0025: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::Start<valuetype Program/'<M>d__0'>(!!0&) IL_002a: ret } // end of method Program::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void IfWithBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one""}; if (0 is int i) { var x = i; actions.Add(() => { Console.WriteLine(strings[i + x]); }); } actions[0](); } }"; var compilation = CompileAndVerify(source, expectedOutput: "one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20b8 // Code size 30 (0x1e) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_000c: ldarg.0 IL_000d: ldfld int32 Program/'<>c__DisplayClass0_0'::x IL_0012: add IL_0013: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0018: call void [mscorlib]System.Console::WriteLine(string) IL_001d: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 84 (0x54) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0029: ldloc.0 IL_002a: ldloc.0 IL_002b: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0030: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_0035: ldloc.1 IL_0036: ldloc.0 IL_0037: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_003d: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0042: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0047: ldloc.1 IL_0048: ldc.i4.0 IL_0049: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_004e: callvirt instance void [mscorlib]System.Action::Invoke() IL_0053: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void IfWithoutBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one""}; if (0 is int i) actions.Add(i is int x ? (Action)(() => Console.WriteLine(strings[i + x])) : () => {}); actions[0](); } }"; var compilation = CompileAndVerify(source, expectedOutput: "one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20b8 // Code size 30 (0x1e) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_000c: ldarg.0 IL_000d: ldfld int32 Program/'<>c__DisplayClass0_0'::x IL_0012: add IL_0013: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0018: call void [mscorlib]System.Console::WriteLine(string) IL_001d: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x20d7 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x20e3 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 84 (0x54) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0029: ldloc.1 IL_002a: ldloc.0 IL_002b: ldloc.0 IL_002c: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0031: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_0036: ldloc.0 IL_0037: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_003d: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0042: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0047: ldloc.1 IL_0048: ldc.i4.0 IL_0049: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_004e: callvirt instance void [mscorlib]System.Action::Invoke() IL_0053: ret } // end of method Program::Main } // end of class Program "); } [Fact] public void ElseWithoutBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one""}; if(true) if (!(0 is int i) || strings[0] != ""one"") throw new Exception(); else actions.Add(i is int x ? (Action)(() => Console.WriteLine(strings[i + x])) : () => {}); actions[0](); } }"; var compilation = CompileAndVerify(source, expectedOutput: "one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20ce // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20d6 // Code size 30 (0x1e) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_000c: ldarg.0 IL_000d: ldfld int32 Program/'<>c__DisplayClass0_0'::x IL_0012: add IL_0013: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0018: call void [mscorlib]System.Console::WriteLine(string) IL_001d: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x20f5 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20ce // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x2101 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 114 (0x72) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0029: ldloc.0 IL_002a: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_002f: ldc.i4.0 IL_0030: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0035: ldstr ""one"" IL_003a: call bool [mscorlib]System.String::op_Inequality(string, string) IL_003f: brfalse.s IL_0047 IL_0041: newobj instance void [mscorlib]System.Exception::.ctor() IL_0046: throw IL_0047: ldloc.1 IL_0048: ldloc.0 IL_0049: ldloc.0 IL_004a: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_004f: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_0054: ldloc.0 IL_0055: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_005b: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0060: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0065: ldloc.1 IL_0066: ldc.i4.0 IL_0067: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_006c: callvirt instance void [mscorlib]System.Action::Invoke() IL_0071: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void UsingWithBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"" }; using (var disposable = new Disposable()) { var i = 0; actions.Add(() => { Console.WriteLine(disposable.ToString()); Console.WriteLine(strings[i]); }); } actions[0](); } public class Disposable : IDisposable { public void Dispose(){} } }"; var compilation = CompileAndVerify(source, expectedOutput: @"Program+Disposable one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested public auto ansi beforefieldinit Disposable extends [mscorlib]System.Object implements [mscorlib]System.IDisposable { // Methods .method public final hidebysig newslot virtual instance void Dispose () cil managed { // Method begins at RVA 0x20d8 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Disposable::Dispose .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20da // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Disposable::.ctor } // end of class Disposable .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public class Program/Disposable disposable .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20da // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20e2 // Code size 39 (0x27) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable IL_0006: callvirt instance string [mscorlib]System.Object::ToString() IL_000b: call void [mscorlib]System.Console::WriteLine(string) IL_0010: ldarg.0 IL_0011: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_001c: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0021: call void [mscorlib]System.Console::WriteLine(string) IL_0026: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 105 (0x69) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0022: ldloc.0 IL_0023: newobj instance void Program/Disposable::.ctor() IL_0028: stfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable .try { IL_002d: ldloc.0 IL_002e: ldc.i4.0 IL_002f: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0034: ldloc.1 IL_0035: ldloc.0 IL_0036: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_003c: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0041: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0046: leave.s IL_005c } // end .try finally { IL_0048: ldloc.0 IL_0049: ldfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable IL_004e: brfalse.s IL_005b IL_0050: ldloc.0 IL_0051: ldfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable IL_0056: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_005b: endfinally } // end handler IL_005c: ldloc.1 IL_005d: ldc.i4.0 IL_005e: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0063: callvirt instance void [mscorlib]System.Action::Invoke() IL_0068: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void UsingWithoutBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"" }; using (var disposable = new Disposable()) actions.Add(0 is int i ? (Action)(() => { Console.WriteLine(disposable.ToString()); Console.WriteLine(strings[i]); }) : () => {}); actions[0](); } public class Disposable : IDisposable { public void Dispose(){} } }"; var compilation = CompileAndVerify(source, expectedOutput: @"Program+Disposable one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested public auto ansi beforefieldinit Disposable extends [mscorlib]System.Object implements [mscorlib]System.IDisposable { // Methods .method public final hidebysig newslot virtual instance void Dispose () cil managed { // Method begins at RVA 0x20d8 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Disposable::Dispose .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20da // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Disposable::.ctor } // end of class Disposable .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public class Program/Disposable disposable .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20da // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20e2 // Code size 39 (0x27) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable IL_0006: callvirt instance string [mscorlib]System.Object::ToString() IL_000b: call void [mscorlib]System.Console::WriteLine(string) IL_0010: ldarg.0 IL_0011: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_001c: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0021: call void [mscorlib]System.Console::WriteLine(string) IL_0026: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x210a // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20da // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x20d8 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 105 (0x69) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0022: ldloc.0 IL_0023: newobj instance void Program/Disposable::.ctor() IL_0028: stfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable .try { IL_002d: ldloc.1 IL_002e: ldloc.0 IL_002f: ldc.i4.0 IL_0030: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0035: ldloc.0 IL_0036: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_003c: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0041: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0046: leave.s IL_005c } // end .try finally { IL_0048: ldloc.0 IL_0049: ldfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable IL_004e: brfalse.s IL_005b IL_0050: ldloc.0 IL_0051: ldfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable IL_0056: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_005b: endfinally } // end handler IL_005c: ldloc.1 IL_005d: ldc.i4.0 IL_005e: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0063: callvirt instance void [mscorlib]System.Action::Invoke() IL_0068: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void IfInUsingInForeachInForCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; using System.Linq; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; foreach(var i in Enumerable.Range(0,1)) for (var j = 0; j < strings.Count; j++) using (var disposable = new Disposable()) if(j is int x) actions.Add(0 is int y ? (Action)(() => { Console.WriteLine(disposable.ToString()); Console.WriteLine(strings[j - x - 1 + i + y]); }) : () => { }); actions[0](); actions[1](); actions[2](); } public class Disposable : IDisposable { public void Dispose() { } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"Program+Disposable three Program+Disposable two Program+Disposable one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested public auto ansi beforefieldinit Disposable extends [mscorlib]System.Object implements [mscorlib]System.IDisposable { // Methods .method public final hidebysig newslot virtual instance void Dispose () cil managed { // Method begins at RVA 0x21b0 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Disposable::Dispose .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x21b2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Disposable::.ctor } // end of class Disposable .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x21b2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 i .field public int32 j .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x21b2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_2' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class Program/Disposable disposable .field public int32 x .field public int32 y .field public class Program/'<>c__DisplayClass0_1' 'CS$<>8__locals2' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x21b2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_2'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x21bc // Code size 82 (0x52) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldfld class Program/Disposable Program/'<>c__DisplayClass0_2'::disposable IL_0006: callvirt instance string [mscorlib]System.Object::ToString() IL_000b: call void [mscorlib]System.Console::WriteLine(string) IL_0010: ldarg.0 IL_0011: ldfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0016: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_001b: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0020: ldarg.0 IL_0021: ldfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0026: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_002b: ldarg.0 IL_002c: ldfld int32 Program/'<>c__DisplayClass0_2'::x IL_0031: sub IL_0032: ldc.i4.1 IL_0033: sub IL_0034: ldarg.0 IL_0035: ldfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_003a: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_003f: add IL_0040: ldarg.0 IL_0041: ldfld int32 Program/'<>c__DisplayClass0_2'::y IL_0046: add IL_0047: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_004c: call void [mscorlib]System.Console::WriteLine(string) IL_0051: ret } // end of method '<>c__DisplayClass0_2'::'<Main>b__0' } // end of class <>c__DisplayClass0_2 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x221a // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x21b2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x21b0 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 310 (0x136) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>, [3] class Program/'<>c__DisplayClass0_1', [4] class Program/'<>c__DisplayClass0_2', [5] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldc.i4.0 IL_0039: ldc.i4.1 IL_003a: call class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> [System.Core]System.Linq.Enumerable::Range(int32, int32) IL_003f: callvirt instance class [mscorlib]System.Collections.Generic.IEnumerator`1<!0> class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>::GetEnumerator() IL_0044: stloc.2 .try { IL_0045: br IL_00fa // loop start (head: IL_00fa) IL_004a: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_004f: stloc.3 IL_0050: ldloc.3 IL_0051: ldloc.0 IL_0052: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0057: ldloc.3 IL_0058: ldloc.2 IL_0059: callvirt instance !0 class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>::get_Current() IL_005e: stfld int32 Program/'<>c__DisplayClass0_1'::i IL_0063: ldloc.3 IL_0064: ldc.i4.0 IL_0065: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_006a: br.s IL_00df // loop start (head: IL_00df) IL_006c: newobj instance void Program/'<>c__DisplayClass0_2'::.ctor() IL_0071: stloc.s 4 IL_0073: ldloc.s 4 IL_0075: ldloc.3 IL_0076: stfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_007b: ldloc.s 4 IL_007d: newobj instance void Program/Disposable::.ctor() IL_0082: stfld class Program/Disposable Program/'<>c__DisplayClass0_2'::disposable .try { IL_0087: ldloc.s 4 IL_0089: ldloc.s 4 IL_008b: ldfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0090: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_0095: stfld int32 Program/'<>c__DisplayClass0_2'::x IL_009a: ldloc.1 IL_009b: ldloc.s 4 IL_009d: ldc.i4.0 IL_009e: stfld int32 Program/'<>c__DisplayClass0_2'::y IL_00a3: ldloc.s 4 IL_00a5: ldftn instance void Program/'<>c__DisplayClass0_2'::'<Main>b__0'() IL_00ab: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_00b0: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_00b5: leave.s IL_00cd } // end .try finally { IL_00b7: ldloc.s 4 IL_00b9: ldfld class Program/Disposable Program/'<>c__DisplayClass0_2'::disposable IL_00be: brfalse.s IL_00cc IL_00c0: ldloc.s 4 IL_00c2: ldfld class Program/Disposable Program/'<>c__DisplayClass0_2'::disposable IL_00c7: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_00cc: endfinally } // end handler IL_00cd: ldloc.3 IL_00ce: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_00d3: stloc.s 5 IL_00d5: ldloc.3 IL_00d6: ldloc.s 5 IL_00d8: ldc.i4.1 IL_00d9: add IL_00da: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_00df: ldloc.3 IL_00e0: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_00e5: ldloc.3 IL_00e6: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_00eb: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_00f0: callvirt instance int32 class [mscorlib]System.Collections.Generic.List`1<string>::get_Count() IL_00f5: blt IL_006c // end loop IL_00fa: ldloc.2 IL_00fb: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() IL_0100: brtrue IL_004a // end loop IL_0105: leave.s IL_0111 } // end .try finally { IL_0107: ldloc.2 IL_0108: brfalse.s IL_0110 IL_010a: ldloc.2 IL_010b: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_0110: endfinally } // end handler IL_0111: ldloc.1 IL_0112: ldc.i4.0 IL_0113: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0118: callvirt instance void [mscorlib]System.Action::Invoke() IL_011d: ldloc.1 IL_011e: ldc.i4.1 IL_011f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0124: callvirt instance void [mscorlib]System.Action::Invoke() IL_0129: ldloc.1 IL_012a: ldc.i4.2 IL_012b: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0130: callvirt instance void [mscorlib]System.Action::Invoke() IL_0135: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void WhileCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; int i = 0; while(i is int j && i++ < 3) actions.Add(0 is int x ? (Action)(() => Console.WriteLine(strings[j + x])) : () => { }); actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"one two three"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20f2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 j .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20f2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20fa // Code size 35 (0x23) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_0011: ldarg.0 IL_0012: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_0017: add IL_0018: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_001d: call void [mscorlib]System.Console::WriteLine(string) IL_0022: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x211e // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20f2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x212a // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 150 (0x96) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] int32, [3] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldc.i4.0 IL_0039: stloc.2 // loop start (head: IL_003a) IL_003a: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_003f: stloc.3 IL_0040: ldloc.3 IL_0041: ldloc.0 IL_0042: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0047: ldloc.3 IL_0048: ldloc.2 IL_0049: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_004e: ldloc.2 IL_004f: dup IL_0050: ldc.i4.1 IL_0051: add IL_0052: stloc.2 IL_0053: ldc.i4.3 IL_0054: bge.s IL_0071 IL_0056: ldloc.1 IL_0057: ldloc.3 IL_0058: ldc.i4.0 IL_0059: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_005e: ldloc.3 IL_005f: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0065: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_006a: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_006f: br.s IL_003a // end loop IL_0071: ldloc.1 IL_0072: ldc.i4.0 IL_0073: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0078: callvirt instance void [mscorlib]System.Action::Invoke() IL_007d: ldloc.1 IL_007e: ldc.i4.1 IL_007f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0084: callvirt instance void [mscorlib]System.Action::Invoke() IL_0089: ldloc.1 IL_008a: ldc.i4.2 IL_008b: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0090: callvirt instance void [mscorlib]System.Action::Invoke() IL_0095: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForWithVariableDeclaredInInvocationExpressionInIteratorCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; for (int i = 0; ++i < 3; actions.Add(i is int j ? (Action)(() => { Console.WriteLine(strings[i - j - 1]); }) : () => { })) ; actions[0](); actions[1](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"two one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20fa // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 j .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20fa // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2102 // Code size 42 (0x2a) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_001c: sub IL_001d: ldc.i4.1 IL_001e: sub IL_001f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0024: call void [mscorlib]System.Console::WriteLine(string) IL_0029: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x212d // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20fa // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x2139 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 158 (0x9e) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class Program/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_003f: br.s IL_0071 // loop start (head: IL_0071) IL_0041: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0046: stloc.2 IL_0047: ldloc.2 IL_0048: ldloc.0 IL_0049: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_004e: ldloc.1 IL_004f: ldloc.2 IL_0050: ldloc.2 IL_0051: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0056: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_005b: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_0060: ldloc.2 IL_0061: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0067: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_006c: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0071: ldloc.0 IL_0072: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0077: ldc.i4.1 IL_0078: add IL_0079: stloc.3 IL_007a: ldloc.0 IL_007b: ldloc.3 IL_007c: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0081: ldloc.3 IL_0082: ldc.i4.3 IL_0083: blt.s IL_0041 // end loop IL_0085: ldloc.1 IL_0086: ldc.i4.0 IL_0087: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_008c: callvirt instance void [mscorlib]System.Action::Invoke() IL_0091: ldloc.1 IL_0092: ldc.i4.1 IL_0093: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0098: callvirt instance void [mscorlib]System.Action::Invoke() IL_009d: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForWithVariableDeclaredInSimpleAssignmentExpressionInIteratorCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var strings = new List<string>() { ""one"", ""two"", ""three"" }; Action action = null; for (int i = 0; ++i < 2; action = i is int j ? (Action)(() => { Console.WriteLine(strings[i - j - 1]); }) : () => { }) ; action(); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20df // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 j .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20df // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20e7 // Code size 42 (0x2a) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_001c: sub IL_001d: ldc.i4.1 IL_001e: sub IL_001f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0024: call void [mscorlib]System.Console::WriteLine(string) IL_0029: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x2112 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20df // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x211e // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 131 (0x83) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Action, [2] class Program/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_000c: dup IL_000d: ldstr ""one"" IL_0012: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0017: dup IL_0018: ldstr ""two"" IL_001d: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0022: dup IL_0023: ldstr ""three"" IL_0028: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_002d: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0032: ldnull IL_0033: stloc.1 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_003b: br.s IL_0068 // loop start (head: IL_0068) IL_003d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0042: stloc.2 IL_0043: ldloc.2 IL_0044: ldloc.0 IL_0045: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_004a: ldloc.2 IL_004b: ldloc.2 IL_004c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0051: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0056: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_005b: ldloc.2 IL_005c: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0062: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0067: stloc.1 IL_0068: ldloc.0 IL_0069: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_006e: ldc.i4.1 IL_006f: add IL_0070: stloc.3 IL_0071: ldloc.0 IL_0072: ldloc.3 IL_0073: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0078: ldloc.3 IL_0079: ldc.i4.2 IL_007a: blt.s IL_003d // end loop IL_007c: ldloc.1 IL_007d: callvirt instance void [mscorlib]System.Action::Invoke() IL_0082: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForWithVariableDeclaredInConditionCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var strings = new List<string>() { ""one"" }; Action action = null; for (int i = 0; i is int j && null == (action = () => { Console.WriteLine(strings[i + j]); });) break; ; action(); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b5 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 j .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b5 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20bd // Code size 40 (0x28) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_001c: add IL_001d: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0022: call void [mscorlib]System.Console::WriteLine(string) IL_0027: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 89 (0x59) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Action, [2] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_000c: dup IL_000d: ldstr ""one"" IL_0012: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0017: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_001c: ldnull IL_001d: stloc.1 IL_001e: ldloc.0 IL_001f: ldc.i4.0 IL_0020: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0025: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_002a: stloc.2 IL_002b: ldloc.2 IL_002c: ldloc.0 IL_002d: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0032: ldloc.2 IL_0033: ldloc.2 IL_0034: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0039: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_003e: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_0043: ldloc.2 IL_0044: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_004a: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_004f: dup IL_0050: stloc.1 IL_0051: pop IL_0052: ldloc.1 IL_0053: callvirt instance void [mscorlib]System.Action::Invoke() IL_0058: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForWithVariableDeclaredInConditionAndNoneInInitializerCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var strings = new List<string>() { ""one"" }; Action action = null; int i = 0; for (; i is int j && null == (action = () => { Console.WriteLine(strings[i + j]); });) break; ; action(); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b5 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 j .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b5 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20bd // Code size 40 (0x28) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_001c: add IL_001d: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0022: call void [mscorlib]System.Console::WriteLine(string) IL_0027: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 89 (0x59) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Action, [2] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_000c: dup IL_000d: ldstr ""one"" IL_0012: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0017: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_001c: ldnull IL_001d: stloc.1 IL_001e: ldloc.0 IL_001f: ldc.i4.0 IL_0020: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0025: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_002a: stloc.2 IL_002b: ldloc.2 IL_002c: ldloc.0 IL_002d: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0032: ldloc.2 IL_0033: ldloc.2 IL_0034: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0039: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_003e: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_0043: ldloc.2 IL_0044: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_004a: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_004f: dup IL_0050: stloc.1 IL_0051: pop IL_0052: ldloc.1 IL_0053: callvirt instance void [mscorlib]System.Action::Invoke() IL_0058: ret } // end of method Program::Main } // end of class Program "); } [Fact] public void DoWhileCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; int i = 0; do actions.Add(i is int x ? (Action)(() => Console.WriteLine(strings[i - x - 1])) : () => { }); while (++i < 3); actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"three two one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2104 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2104 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x210c // Code size 42 (0x2a) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_001c: sub IL_001d: ldc.i4.1 IL_001e: sub IL_001f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0024: call void [mscorlib]System.Console::WriteLine(string) IL_0029: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x2137 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2104 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x2143 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 168 (0xa8) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class Program/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: stfld int32 Program/'<>c__DisplayClass0_0'::i // loop start (head: IL_003f) IL_003f: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0044: stloc.2 IL_0045: ldloc.2 IL_0046: ldloc.0 IL_0047: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_004c: ldloc.1 IL_004d: ldloc.2 IL_004e: ldloc.2 IL_004f: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0054: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0059: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_005e: ldloc.2 IL_005f: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0065: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_006a: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_006f: ldloc.0 IL_0070: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0075: ldc.i4.1 IL_0076: add IL_0077: stloc.3 IL_0078: ldloc.0 IL_0079: ldloc.3 IL_007a: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_007f: ldloc.3 IL_0080: ldc.i4.3 IL_0081: blt.s IL_003f // end loop IL_0083: ldloc.1 IL_0084: ldc.i4.0 IL_0085: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_008a: callvirt instance void [mscorlib]System.Action::Invoke() IL_008f: ldloc.1 IL_0090: ldc.i4.1 IL_0091: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0096: callvirt instance void [mscorlib]System.Action::Invoke() IL_009b: ldloc.1 IL_009c: ldc.i4.2 IL_009d: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00a2: callvirt instance void [mscorlib]System.Action::Invoke() IL_00a7: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsBackwardsGoToMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { target: ; int b = 1; Action action = () => Console.WriteLine(a + b); action(); return; goto target; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2082 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x208a // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 38 (0x26) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0014: ldloc.0 IL_0015: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_001b: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0020: callvirt instance void [mscorlib]System.Action::Invoke() IL_0025: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsForwardsGoToMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { goto target; int b = 1; Action action = () => Console.WriteLine(a + b); action(); target: ; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @""); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x206a // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2072 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 14 (0xe) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsBackwardsGoToCaseMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; switch(a) { case 1: default: int b = 1; Action action = () => Console.WriteLine(a + b); action(); break; case 0: goto case 1; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2090 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2098 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 52 (0x34) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_001b IL_0017: ldloc.1 IL_0018: ldc.i4.1 IL_0019: pop IL_001a: pop IL_001b: ldloc.0 IL_001c: ldc.i4.1 IL_001d: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0022: ldloc.0 IL_0023: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_0029: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002e: callvirt instance void [mscorlib]System.Action::Invoke() IL_0033: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsForwardsGoToCaseMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; switch(a) { case 0: goto case 1; case 1: default: int b = 1; Action action = () => Console.WriteLine(a + b); action(); break; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2090 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2098 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 52 (0x34) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_001b IL_0017: ldloc.1 IL_0018: ldc.i4.1 IL_0019: pop IL_001a: pop IL_001b: ldloc.0 IL_001c: ldc.i4.1 IL_001d: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0022: ldloc.0 IL_0023: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_0029: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002e: callvirt instance void [mscorlib]System.Action::Invoke() IL_0033: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsBackwardsGoToDefaultMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; switch(a) { default: int b = 1; Action action = () => Console.WriteLine(a + b); action(); break; case 0: goto default; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2089 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2091 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 45 (0x2d) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0013: pop IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_001b: ldloc.0 IL_001c: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_0022: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0027: callvirt instance void [mscorlib]System.Action::Invoke() IL_002c: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsForwardsGoToDefaultMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; switch(a) { case 0: int b = 1; Action action = () => Console.WriteLine(a + b); action(); goto default; default: break; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208a // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2092 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 46 (0x2e) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0013: brtrue.s IL_002d IL_0015: ldloc.0 IL_0016: ldc.i4.1 IL_0017: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_001c: ldloc.0 IL_001d: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_0023: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0028: callvirt instance void [mscorlib]System.Action::Invoke() IL_002d: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsScopeContainingBackwardsGoToMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { target: ; int b = 1; Action action = () => Console.WriteLine(a + b); action(); return; { goto target; } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2082 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x208a // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 38 (0x26) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0014: ldloc.0 IL_0015: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_001b: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0020: callvirt instance void [mscorlib]System.Action::Invoke() IL_0025: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void BackwardsGoToToPointInBetweenScopeAndParentPreventsMerging01() { var source = @"using System; public static class Program { public static void Main() { int a = 0; target: ; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); } return; goto target; } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2095 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 49 (0x31) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: dup IL_0013: ldloc.0 IL_0014: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0019: dup IL_001a: ldc.i4.1 IL_001b: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0020: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0026: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002b: callvirt instance void [mscorlib]System.Action::Invoke() IL_0030: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void BackwardsGoToToPointInBetweenScopeAndParentPreventsMerging02() { var source = @"using System; public static class Program { public static void Main() { int a = 0; target: ; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); } return; { goto target; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2095 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 49 (0x31) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: dup IL_0013: ldloc.0 IL_0014: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0019: dup IL_001a: ldc.i4.1 IL_001b: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0020: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0026: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002b: callvirt instance void [mscorlib]System.Action::Invoke() IL_0030: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void BackwardsGoToToPointInBetweenScopeAndParentPreventsMerging03() { var source = @"using System; public static class Program { public static void Main() { int a = 0; target: ; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); return; goto target; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2095 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 49 (0x31) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: dup IL_0013: ldloc.0 IL_0014: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0019: dup IL_001a: ldc.i4.1 IL_001b: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0020: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0026: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002b: callvirt instance void [mscorlib]System.Action::Invoke() IL_0030: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void BackwardsGoToToPointInBetweenScopeAndParentPreventsMerging04() { var source = @"using System; public static class Program { public static void Main() { int a = 0; target: ; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); return; { goto target; } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2095 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 49 (0x31) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: dup IL_0013: ldloc.0 IL_0014: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0019: dup IL_001a: ldc.i4.1 IL_001b: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0020: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0026: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002b: callvirt instance void [mscorlib]System.Action::Invoke() IL_0030: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void BackwardsGoToCaseToPointInBetweenScopeAndParentPreventsMerging() { var source = @"using System; public static class Program { public static void Main() { int a = 0; switch(a) { case 1: default: { int b = 1; Action action = () => Console.WriteLine(a + b); action(); break; } case 0: goto case 1; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20a3 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 63 (0x3f) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_001b IL_0017: ldloc.1 IL_0018: ldc.i4.1 IL_0019: pop IL_001a: pop IL_001b: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0020: dup IL_0021: ldloc.0 IL_0022: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0027: dup IL_0028: ldc.i4.1 IL_0029: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_002e: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0034: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0039: callvirt instance void [mscorlib]System.Action::Invoke() IL_003e: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void BackwardsGoToDefaultToPointInBetweenScopeAndParentPreventsMerging() { var source = @"using System; public static class Program { public static void Main() { int a = 0; switch(a) { default: { int b = 1; Action action = () => Console.WriteLine(a + b); action(); break; } case 0: goto default; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2094 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2094 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x209c // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 56 (0x38) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0013: pop IL_0014: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0019: dup IL_001a: ldloc.0 IL_001b: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0020: dup IL_0021: ldc.i4.1 IL_0022: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0027: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_002d: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0032: callvirt instance void [mscorlib]System.Action::Invoke() IL_0037: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable01() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); } Action _ = () => Console.WriteLine(a); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2095 // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x20a2 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__1' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 49 (0x31) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: dup IL_0013: ldloc.0 IL_0014: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0019: dup IL_001a: ldc.i4.1 IL_001b: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0020: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__1'() IL_0026: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002b: callvirt instance void [mscorlib]System.Action::Invoke() IL_0030: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable02() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; { Action action = () => Console.WriteLine(a + b); action(); } { Action _ = () => Console.WriteLine(a + b); } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2077 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x207f // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x207f // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__1' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 38 (0x26) .maxstack 8 .entrypoint IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: ldc.i4.0 IL_0007: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000c: dup IL_000d: ldc.i4.1 IL_000e: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0013: dup IL_0014: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_001a: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_001f: callvirt instance void [mscorlib]System.Action::Invoke() IL_0024: pop IL_0025: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable03() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); Action _ = () => Console.WriteLine(b); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2077 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x207f // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x2093 // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__1' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 38 (0x26) .maxstack 8 .entrypoint IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: ldc.i4.0 IL_0007: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000c: dup IL_000d: ldc.i4.1 IL_000e: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0013: dup IL_0014: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_001a: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_001f: callvirt instance void [mscorlib]System.Action::Invoke() IL_0024: pop IL_0025: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable04() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); Action _ = () => Console.WriteLine(a); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2094 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x209c // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__1' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2094 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20a9 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 56 (0x38) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: dup IL_0013: ldloc.0 IL_0014: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0019: dup IL_001a: ldc.i4.1 IL_001b: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0020: dup IL_0021: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0027: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002c: callvirt instance void [mscorlib]System.Action::Invoke() IL_0031: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0036: pop IL_0037: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable05() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; { int c = 2; { int d = 3; Action action = () => Console.WriteLine(b + d); action(); Action _ = () => Console.WriteLine(a + c); } } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"4"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b .field public int32 c // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x20aa // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::c IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__1' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 d .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20be // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::d IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 70 (0x46) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0014: ldloc.0 IL_0015: ldc.i4.2 IL_0016: stfld int32 Program/'<>c__DisplayClass0_0'::c IL_001b: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0020: dup IL_0021: ldloc.0 IL_0022: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0027: dup IL_0028: ldc.i4.3 IL_0029: stfld int32 Program/'<>c__DisplayClass0_1'::d IL_002e: dup IL_002f: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0035: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_003a: callvirt instance void [mscorlib]System.Action::Invoke() IL_003f: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0044: pop IL_0045: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable06() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; { int c = 2; Action action = () => Console.WriteLine(a + c); action(); Action x = () => Console.WriteLine(a + b + c); } Action y = () => Console.WriteLine(b); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"2"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2096 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x209e // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 c .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2096 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x20ab // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::c IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__1' .method assembly hidebysig instance void '<Main>b__2' () cil managed { // Method begins at RVA 0x20c4 // Code size 36 (0x24) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_0016: add IL_0017: ldarg.0 IL_0018: ldfld int32 Program/'<>c__DisplayClass0_1'::c IL_001d: add IL_001e: call void [mscorlib]System.Console::WriteLine(int32) IL_0023: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__2' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 58 (0x3a) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0014: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0019: dup IL_001a: ldloc.0 IL_001b: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0020: dup IL_0021: ldc.i4.2 IL_0022: stfld int32 Program/'<>c__DisplayClass0_1'::c IL_0027: dup IL_0028: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__1'() IL_002e: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0033: callvirt instance void [mscorlib]System.Action::Invoke() IL_0038: pop IL_0039: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable07() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; { int c = 2; Action action = () => Console.WriteLine(b + c); action(); } Action y = () => Console.WriteLine(a + b); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2094 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x209c // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 c .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2094 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x20b0 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::c IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__1' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 56 (0x38) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0014: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0019: dup IL_001a: ldloc.0 IL_001b: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0020: dup IL_0021: ldc.i4.2 IL_0022: stfld int32 Program/'<>c__DisplayClass0_1'::c IL_0027: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__1'() IL_002d: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0032: callvirt instance void [mscorlib]System.Action::Invoke() IL_0037: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable08() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; { int c = 2; Action action = () => Console.WriteLine(b + c); action(); } Action y = () => Console.WriteLine(a); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2082 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x208a // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public int32 c // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2082 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x2097 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_1'::c IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__1' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 49 (0x31) .maxstack 8 .entrypoint IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: ldc.i4.0 IL_0007: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000c: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0011: dup IL_0012: ldc.i4.1 IL_0013: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0018: dup IL_0019: ldc.i4.2 IL_001a: stfld int32 Program/'<>c__DisplayClass0_1'::c IL_001f: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__1'() IL_0025: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002a: callvirt instance void [mscorlib]System.Action::Invoke() IL_002f: pop IL_0030: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void DoNotMergeEnvironmentsInsideLocalFunctionToOutside() { var source = @"using System; using System.Collections.Generic; public class Program { public static void Main() { var actions = new List<Action>(); int a = 1; void M() { int b = 0; actions.Add(() => b += a); actions.Add(() => Console.WriteLine(b)); } M(); M(); actions[0](); actions[2](); actions[1](); actions[3](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1 1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> actions .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20c3 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>g__M|0' () cil managed { // Method begins at RVA 0x20cc // Code size 67 (0x43) .maxstack 3 .locals init ( [0] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000d: ldloc.0 IL_000e: ldc.i4.0 IL_000f: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0014: ldarg.0 IL_0015: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_001a: ldloc.0 IL_001b: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__1'() IL_0021: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0026: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_002b: ldarg.0 IL_002c: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0031: ldloc.0 IL_0032: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__2'() IL_0038: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_003d: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0042: ret } // end of method '<>c__DisplayClass0_0'::'<Main>g__M|0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20c3 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x211b // Code size 25 (0x19) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0007: ldarg.0 IL_0008: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000d: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0012: add IL_0013: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0018: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__1' .method assembly hidebysig instance void '<Main>b__2' () cil managed { // Method begins at RVA 0x2135 // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__2' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 103 (0x67) .maxstack 3 .entrypoint IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0010: dup IL_0011: ldc.i4.1 IL_0012: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_0017: dup IL_0018: callvirt instance void Program/'<>c__DisplayClass0_0'::'<Main>g__M|0'() IL_001d: dup IL_001e: callvirt instance void Program/'<>c__DisplayClass0_0'::'<Main>g__M|0'() IL_0023: dup IL_0024: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0029: ldc.i4.0 IL_002a: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_002f: callvirt instance void [mscorlib]System.Action::Invoke() IL_0034: dup IL_0035: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_003a: ldc.i4.2 IL_003b: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0040: callvirt instance void [mscorlib]System.Action::Invoke() IL_0045: dup IL_0046: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_004b: ldc.i4.1 IL_004c: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0051: callvirt instance void [mscorlib]System.Action::Invoke() IL_0056: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_005b: ldc.i4.3 IL_005c: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0061: callvirt instance void [mscorlib]System.Action::Invoke() IL_0066: ret } // end of method Program::Main .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20c3 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void DoNotMergeEnvironmentsInsideLambdaToOutside() { var source = @"using System; using System.Collections.Generic; public class Program { public static void Main() { var actions = new List<Action>(); int a = 1; Action M = () => { int b = 0; actions.Add(() => b += a); actions.Add(() => Console.WriteLine(b)); }; M(); M(); actions[0](); actions[2](); actions[1](); actions[3](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1 1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> actions .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20ce // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20d8 // Code size 67 (0x43) .maxstack 3 .locals init ( [0] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000d: ldloc.0 IL_000e: ldc.i4.0 IL_000f: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0014: ldarg.0 IL_0015: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_001a: ldloc.0 IL_001b: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__1'() IL_0021: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0026: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_002b: ldarg.0 IL_002c: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0031: ldloc.0 IL_0032: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__2'() IL_0038: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_003d: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0042: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20ce // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x2127 // Code size 25 (0x19) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0007: ldarg.0 IL_0008: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000d: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0012: add IL_0013: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0018: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__1' .method assembly hidebysig instance void '<Main>b__2' () cil managed { // Method begins at RVA 0x2141 // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__2' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 114 (0x72) .maxstack 3 .entrypoint IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0010: dup IL_0011: ldc.i4.1 IL_0012: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_0017: dup IL_0018: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_001e: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0023: dup IL_0024: callvirt instance void [mscorlib]System.Action::Invoke() IL_0029: callvirt instance void [mscorlib]System.Action::Invoke() IL_002e: dup IL_002f: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0034: ldc.i4.0 IL_0035: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_003a: callvirt instance void [mscorlib]System.Action::Invoke() IL_003f: dup IL_0040: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0045: ldc.i4.2 IL_0046: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_004b: callvirt instance void [mscorlib]System.Action::Invoke() IL_0050: dup IL_0051: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0056: ldc.i4.1 IL_0057: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_005c: callvirt instance void [mscorlib]System.Action::Invoke() IL_0061: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0066: ldc.i4.3 IL_0067: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_006c: callvirt instance void [mscorlib]System.Action::Invoke() IL_0071: ret } // end of method Program::Main .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20ce // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void LocalMethod01() { var source = @"using System; public class Program { public static void Main() { M()(); } public static Action M() { int a = 1; { int b = 2; void M1() { Console.WriteLine(a + b); } { int c = 3; void M2() { M1(); Console.WriteLine(c); } return M2; } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3 3"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_0'::.ctor .method assembly hidebysig instance void '<M>g__M1|0' () cil managed { // Method begins at RVA 0x20a3 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass1_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass1_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass1_0'::'<M>g__M1|0' } // end of class <>c__DisplayClass1_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 c .field public class Program/'<>c__DisplayClass1_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_1'::.ctor .method assembly hidebysig instance void '<M>g__M2|1' () cil managed { // Method begins at RVA 0x20b7 // Code size 23 (0x17) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass1_0' Program/'<>c__DisplayClass1_1'::'CS$<>8__locals1' IL_0006: callvirt instance void Program/'<>c__DisplayClass1_0'::'<M>g__M1|0'() IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass1_1'::c IL_0011: call void [mscorlib]System.Console::WriteLine(int32) IL_0016: ret } // end of method '<>c__DisplayClass1_1'::'<M>g__M2|1' } // end of class <>c__DisplayClass1_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: call class [mscorlib]System.Action Program::M() IL_0005: callvirt instance void [mscorlib]System.Action::Invoke() IL_000a: ret } // end of method Program::Main .method public hidebysig static class [mscorlib]System.Action M () cil managed { // Method begins at RVA 0x205c // Code size 51 (0x33) .maxstack 3 .locals init ( [0] class Program/'<>c__DisplayClass1_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass1_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: stfld int32 Program/'<>c__DisplayClass1_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.2 IL_000f: stfld int32 Program/'<>c__DisplayClass1_0'::b IL_0014: newobj instance void Program/'<>c__DisplayClass1_1'::.ctor() IL_0019: dup IL_001a: ldloc.0 IL_001b: stfld class Program/'<>c__DisplayClass1_0' Program/'<>c__DisplayClass1_1'::'CS$<>8__locals1' IL_0020: dup IL_0021: ldc.i4.3 IL_0022: stfld int32 Program/'<>c__DisplayClass1_1'::c IL_0027: ldftn instance void Program/'<>c__DisplayClass1_1'::'<M>g__M2|1'() IL_002d: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0032: ret } // end of method Program::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void LocalMethod02() { var source = @"using System; public class Program { public static void Main() { M()(); } public static Action M() { int a = 1; { target: int b = 2; void M1() { Console.WriteLine(a + b); } { int c = 3; void M2() { M1(); Console.WriteLine(c); } return M2; goto target; } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3 3"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_0'::.ctor .method assembly hidebysig instance void '<M>g__M1|0' () cil managed { // Method begins at RVA 0x20a3 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass1_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass1_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass1_0'::'<M>g__M1|0' } // end of class <>c__DisplayClass1_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 c .field public class Program/'<>c__DisplayClass1_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_1'::.ctor .method assembly hidebysig instance void '<M>g__M2|1' () cil managed { // Method begins at RVA 0x20b7 // Code size 23 (0x17) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass1_0' Program/'<>c__DisplayClass1_1'::'CS$<>8__locals1' IL_0006: callvirt instance void Program/'<>c__DisplayClass1_0'::'<M>g__M1|0'() IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass1_1'::c IL_0011: call void [mscorlib]System.Console::WriteLine(int32) IL_0016: ret } // end of method '<>c__DisplayClass1_1'::'<M>g__M2|1' } // end of class <>c__DisplayClass1_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: call class [mscorlib]System.Action Program::M() IL_0005: callvirt instance void [mscorlib]System.Action::Invoke() IL_000a: ret } // end of method Program::Main .method public hidebysig static class [mscorlib]System.Action M () cil managed { // Method begins at RVA 0x205c // Code size 51 (0x33) .maxstack 3 .locals init ( [0] class Program/'<>c__DisplayClass1_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass1_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: stfld int32 Program/'<>c__DisplayClass1_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.2 IL_000f: stfld int32 Program/'<>c__DisplayClass1_0'::b IL_0014: newobj instance void Program/'<>c__DisplayClass1_1'::.ctor() IL_0019: dup IL_001a: ldloc.0 IL_001b: stfld class Program/'<>c__DisplayClass1_0' Program/'<>c__DisplayClass1_1'::'CS$<>8__locals1' IL_0020: dup IL_0021: ldc.i4.3 IL_0022: stfld int32 Program/'<>c__DisplayClass1_1'::c IL_0027: ldftn instance void Program/'<>c__DisplayClass1_1'::'<M>g__M2|1'() IL_002d: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0032: ret } // end of method Program::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void LocalMethod03() { var source = @"using System; public class Program { public static void Main() { M()(); } public static Action M() { int a = 1; target: { int b = 2; void M1() { Console.WriteLine(a + b); } { int c = 3; void M2() { M1(); Console.WriteLine(c); } return M2; goto target; } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3 3"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a8 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_0'::.ctor } // end of class <>c__DisplayClass1_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass1_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a8 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_1'::.ctor .method assembly hidebysig instance void '<M>g__M1|0' () cil managed { // Method begins at RVA 0x20b0 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass1_0' Program/'<>c__DisplayClass1_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass1_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass1_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass1_1'::'<M>g__M1|0' } // end of class <>c__DisplayClass1_1 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_2' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 c .field public class Program/'<>c__DisplayClass1_1' 'CS$<>8__locals2' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a8 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_2'::.ctor .method assembly hidebysig instance void '<M>g__M2|1' () cil managed { // Method begins at RVA 0x20c9 // Code size 23 (0x17) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass1_1' Program/'<>c__DisplayClass1_2'::'CS$<>8__locals2' IL_0006: callvirt instance void Program/'<>c__DisplayClass1_1'::'<M>g__M1|0'() IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass1_2'::c IL_0011: call void [mscorlib]System.Console::WriteLine(int32) IL_0016: ret } // end of method '<>c__DisplayClass1_2'::'<M>g__M2|1' } // end of class <>c__DisplayClass1_2 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: call class [mscorlib]System.Action Program::M() IL_0005: callvirt instance void [mscorlib]System.Action::Invoke() IL_000a: ret } // end of method Program::Main .method public hidebysig static class [mscorlib]System.Action M () cil managed { // Method begins at RVA 0x205c // Code size 64 (0x40) .maxstack 3 .locals init ( [0] class Program/'<>c__DisplayClass1_0', [1] class Program/'<>c__DisplayClass1_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass1_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: stfld int32 Program/'<>c__DisplayClass1_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass1_1'::.ctor() IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: ldloc.0 IL_0015: stfld class Program/'<>c__DisplayClass1_0' Program/'<>c__DisplayClass1_1'::'CS$<>8__locals1' IL_001a: ldloc.1 IL_001b: ldc.i4.2 IL_001c: stfld int32 Program/'<>c__DisplayClass1_1'::b IL_0021: newobj instance void Program/'<>c__DisplayClass1_2'::.ctor() IL_0026: dup IL_0027: ldloc.1 IL_0028: stfld class Program/'<>c__DisplayClass1_1' Program/'<>c__DisplayClass1_2'::'CS$<>8__locals2' IL_002d: dup IL_002e: ldc.i4.3 IL_002f: stfld int32 Program/'<>c__DisplayClass1_2'::c IL_0034: ldftn instance void Program/'<>c__DisplayClass1_2'::'<M>g__M2|1'() IL_003a: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_003f: ret } // end of method Program::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a8 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void LocalMethod04() { var source = @"using System; public class Program { public void M() { int x = 0; { int y = 0; void M() => y++; { Action a = () => x++; } } } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2072 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<M>b__1' () cil managed { // Method begins at RVA 0x209c // Code size 17 (0x11) .maxstack 3 .locals init ( [0] int32 ) IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::x IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: add IL_000b: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_0010: ret } // end of method '<>c__DisplayClass0_0'::'<M>b__1' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 y } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig instance void M () cil managed { // Method begins at RVA 0x2050 // Code size 22 (0x16) .maxstack 3 .locals init ( [0] valuetype Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: ldc.i4.0 IL_0007: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_000c: ldloca.s 0 IL_000e: ldc.i4.0 IL_000f: stfld int32 Program/'<>c__DisplayClass0_1'::y IL_0014: pop IL_0015: ret } // end of method Program::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2072 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor .method assembly hidebysig static void '<M>g__M|0_0' ( valuetype Program/'<>c__DisplayClass0_1'& '' ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x207c // Code size 17 (0x11) .maxstack 3 .locals init ( [0] int32 ) IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_1'::y IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: add IL_000b: stfld int32 Program/'<>c__DisplayClass0_1'::y IL_0010: ret } // end of method Program::'<M>g__M|0_0' } // end of class Program"); } [Fact] public void LocalMethod05() { var source = @"using System; public class Program { public Func<int> M() { int x = 0; { int y = 0; int M() => y++; { Func<int> a = () => x++; { int M1() => M() + a(); return M1; } } } } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance int32 '<M>b__1' () cil managed { // Method begins at RVA 0x20a8 // Code size 18 (0x12) .maxstack 3 .locals init ( [0] int32 ) IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::x IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: add IL_000b: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_0010: ldloc.0 IL_0011: ret } // end of method '<>c__DisplayClass0_0'::'<M>b__1' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 y // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance int32 '<M>g__M|0' () cil managed { // Method begins at RVA 0x20c8 // Code size 18 (0x12) .maxstack 3 .locals init ( [0] int32 ) IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_1'::y IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: add IL_000b: stfld int32 Program/'<>c__DisplayClass0_1'::y IL_0010: ldloc.0 IL_0011: ret } // end of method '<>c__DisplayClass0_1'::'<M>g__M|0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_2' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Func`1<int32> a .field public class Program/'<>c__DisplayClass0_1' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_2'::.ctor .method assembly hidebysig instance int32 '<M>g__M1|2' () cil managed { // Method begins at RVA 0x20e6 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals1' IL_0006: callvirt instance int32 Program/'<>c__DisplayClass0_1'::'<M>g__M|0'() IL_000b: ldarg.0 IL_000c: ldfld class [mscorlib]System.Func`1<int32> Program/'<>c__DisplayClass0_2'::a IL_0011: callvirt instance !0 class [mscorlib]System.Func`1<int32>::Invoke() IL_0016: add IL_0017: ret } // end of method '<>c__DisplayClass0_2'::'<M>g__M1|2' } // end of class <>c__DisplayClass0_2 // Methods .method public hidebysig instance class [mscorlib]System.Func`1<int32> M () cil managed { // Method begins at RVA 0x2050 // Code size 68 (0x44) .maxstack 4 .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: ldc.i4.0 IL_0015: stfld int32 Program/'<>c__DisplayClass0_1'::y IL_001a: newobj instance void Program/'<>c__DisplayClass0_2'::.ctor() IL_001f: dup IL_0020: ldloc.1 IL_0021: stfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals1' IL_0026: dup IL_0027: ldloc.0 IL_0028: ldftn instance int32 Program/'<>c__DisplayClass0_0'::'<M>b__1'() IL_002e: newobj instance void class [mscorlib]System.Func`1<int32>::.ctor(object, native int) IL_0033: stfld class [mscorlib]System.Func`1<int32> Program/'<>c__DisplayClass0_2'::a IL_0038: ldftn instance int32 Program/'<>c__DisplayClass0_2'::'<M>g__M1|2'() IL_003e: newobj instance void class [mscorlib]System.Func`1<int32>::.ctor(object, native int) IL_0043: ret } // end of method Program::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void YieldReturnCorrectDisplayClasseAreCreated() { var source = @"using System; using System.Collections.Generic; public class C { public IEnumerable<int> M() { int a = 1; yield return 1; while(true) { yield return 2; int b = 2; yield return 3; { yield return 4; int c = 3; target: yield return 5; { yield return 6; int d = 4; goto target; yield return 7; Action e = () => Console.WriteLine(a + b + c + d); } } } } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "C", @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2059 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public int32 c .field public class C/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2059 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_2' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 d .field public class C/'<>c__DisplayClass0_1' 'CS$<>8__locals2' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2059 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_2'::.ctor .method assembly hidebysig instance void '<M>b__0' () cil managed { // Method begins at RVA 0x2061 // Code size 53 (0x35) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0006: ldfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000b: ldfld int32 C/'<>c__DisplayClass0_0'::a IL_0010: ldarg.0 IL_0011: ldfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0016: ldfld int32 C/'<>c__DisplayClass0_1'::b IL_001b: add IL_001c: ldarg.0 IL_001d: ldfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0022: ldfld int32 C/'<>c__DisplayClass0_1'::c IL_0027: add IL_0028: ldarg.0 IL_0029: ldfld int32 C/'<>c__DisplayClass0_2'::d IL_002e: add IL_002f: call void [mscorlib]System.Console::WriteLine(int32) IL_0034: ret } // end of method '<>c__DisplayClass0_2'::'<M>b__0' } // end of class <>c__DisplayClass0_2 .class nested private auto ansi sealed beforefieldinit '<M>d__0' extends [mscorlib]System.Object implements class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>, [mscorlib]System.Collections.IEnumerable, class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>, [mscorlib]System.IDisposable, [mscorlib]System.Collections.IEnumerator { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field private int32 '<>1__state' .field private int32 '<>2__current' .field private int32 '<>l__initialThreadId' .field private class C/'<>c__DisplayClass0_0' '<>8__1' .field private class C/'<>c__DisplayClass0_1' '<>8__2' .field private class C/'<>c__DisplayClass0_2' '<>8__3' // Methods .method public hidebysig specialname rtspecialname instance void .ctor ( int32 '<>1__state' ) cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2097 // Code size 25 (0x19) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 C/'<M>d__0'::'<>1__state' IL_000d: ldarg.0 IL_000e: call int32 [mscorlib]System.Environment::get_CurrentManagedThreadId() IL_0013: stfld int32 C/'<M>d__0'::'<>l__initialThreadId' IL_0018: ret } // end of method '<M>d__0'::.ctor .method private final hidebysig newslot virtual instance void System.IDisposable.Dispose () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance void [mscorlib]System.IDisposable::Dispose() // Method begins at RVA 0x20b1 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<M>d__0'::System.IDisposable.Dispose .method private final hidebysig newslot virtual instance bool MoveNext () cil managed { .override method instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() // Method begins at RVA 0x20b4 // Code size 342 (0x156) .maxstack 2 .locals init ( [0] int32 ) IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<M>d__0'::'<>1__state' IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: switch (IL_002f, IL_005d, IL_0090, IL_00b3, IL_00ca, IL_00ed, IL_0120, IL_0135) IL_002d: ldc.i4.0 IL_002e: ret IL_002f: ldarg.0 IL_0030: ldc.i4.m1 IL_0031: stfld int32 C/'<M>d__0'::'<>1__state' IL_0036: ldarg.0 IL_0037: newobj instance void C/'<>c__DisplayClass0_0'::.ctor() IL_003c: stfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_0041: ldarg.0 IL_0042: ldfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_0047: ldc.i4.1 IL_0048: stfld int32 C/'<>c__DisplayClass0_0'::a IL_004d: ldarg.0 IL_004e: ldc.i4.1 IL_004f: stfld int32 C/'<M>d__0'::'<>2__current' IL_0054: ldarg.0 IL_0055: ldc.i4.1 IL_0056: stfld int32 C/'<M>d__0'::'<>1__state' IL_005b: ldc.i4.1 IL_005c: ret IL_005d: ldarg.0 IL_005e: ldc.i4.m1 IL_005f: stfld int32 C/'<M>d__0'::'<>1__state' IL_0064: ldarg.0 IL_0065: newobj instance void C/'<>c__DisplayClass0_1'::.ctor() IL_006a: stfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_006f: ldarg.0 IL_0070: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_0075: ldarg.0 IL_0076: ldfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_007b: stfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0080: ldarg.0 IL_0081: ldc.i4.2 IL_0082: stfld int32 C/'<M>d__0'::'<>2__current' IL_0087: ldarg.0 IL_0088: ldc.i4.2 IL_0089: stfld int32 C/'<M>d__0'::'<>1__state' IL_008e: ldc.i4.1 IL_008f: ret IL_0090: ldarg.0 IL_0091: ldc.i4.m1 IL_0092: stfld int32 C/'<M>d__0'::'<>1__state' IL_0097: ldarg.0 IL_0098: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_009d: ldc.i4.2 IL_009e: stfld int32 C/'<>c__DisplayClass0_1'::b IL_00a3: ldarg.0 IL_00a4: ldc.i4.3 IL_00a5: stfld int32 C/'<M>d__0'::'<>2__current' IL_00aa: ldarg.0 IL_00ab: ldc.i4.3 IL_00ac: stfld int32 C/'<M>d__0'::'<>1__state' IL_00b1: ldc.i4.1 IL_00b2: ret IL_00b3: ldarg.0 IL_00b4: ldc.i4.m1 IL_00b5: stfld int32 C/'<M>d__0'::'<>1__state' IL_00ba: ldarg.0 IL_00bb: ldc.i4.4 IL_00bc: stfld int32 C/'<M>d__0'::'<>2__current' IL_00c1: ldarg.0 IL_00c2: ldc.i4.4 IL_00c3: stfld int32 C/'<M>d__0'::'<>1__state' IL_00c8: ldc.i4.1 IL_00c9: ret IL_00ca: ldarg.0 IL_00cb: ldc.i4.m1 IL_00cc: stfld int32 C/'<M>d__0'::'<>1__state' IL_00d1: ldarg.0 IL_00d2: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_00d7: ldc.i4.3 IL_00d8: stfld int32 C/'<>c__DisplayClass0_1'::c IL_00dd: ldarg.0 IL_00de: ldc.i4.5 IL_00df: stfld int32 C/'<M>d__0'::'<>2__current' IL_00e4: ldarg.0 IL_00e5: ldc.i4.5 IL_00e6: stfld int32 C/'<M>d__0'::'<>1__state' IL_00eb: ldc.i4.1 IL_00ec: ret IL_00ed: ldarg.0 IL_00ee: ldc.i4.m1 IL_00ef: stfld int32 C/'<M>d__0'::'<>1__state' IL_00f4: ldarg.0 IL_00f5: newobj instance void C/'<>c__DisplayClass0_2'::.ctor() IL_00fa: stfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_00ff: ldarg.0 IL_0100: ldfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_0105: ldarg.0 IL_0106: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_010b: stfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0110: ldarg.0 IL_0111: ldc.i4.6 IL_0112: stfld int32 C/'<M>d__0'::'<>2__current' IL_0117: ldarg.0 IL_0118: ldc.i4.6 IL_0119: stfld int32 C/'<M>d__0'::'<>1__state' IL_011e: ldc.i4.1 IL_011f: ret IL_0120: ldarg.0 IL_0121: ldc.i4.m1 IL_0122: stfld int32 C/'<M>d__0'::'<>1__state' IL_0127: ldarg.0 IL_0128: ldfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_012d: ldc.i4.4 IL_012e: stfld int32 C/'<>c__DisplayClass0_2'::d IL_0133: br.s IL_00dd IL_0135: ldarg.0 IL_0136: ldc.i4.m1 IL_0137: stfld int32 C/'<M>d__0'::'<>1__state' IL_013c: ldarg.0 IL_013d: ldfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_0142: pop IL_0143: ldarg.0 IL_0144: ldnull IL_0145: stfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_014a: ldarg.0 IL_014b: ldnull IL_014c: stfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_0151: br IL_0064 } // end of method '<M>d__0'::MoveNext .method private final hidebysig specialname newslot virtual instance int32 'System.Collections.Generic.IEnumerator<System.Int32>.get_Current' () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance !0 class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>::get_Current() // Method begins at RVA 0x2216 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<M>d__0'::'<>2__current' IL_0006: ret } // end of method '<M>d__0'::'System.Collections.Generic.IEnumerator<System.Int32>.get_Current' .method private final hidebysig newslot virtual instance void System.Collections.IEnumerator.Reset () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance void [mscorlib]System.Collections.IEnumerator::Reset() // Method begins at RVA 0x221e // Code size 6 (0x6) .maxstack 8 IL_0000: newobj instance void [mscorlib]System.NotSupportedException::.ctor() IL_0005: throw } // end of method '<M>d__0'::System.Collections.IEnumerator.Reset .method private final hidebysig specialname newslot virtual instance object System.Collections.IEnumerator.get_Current () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance object [mscorlib]System.Collections.IEnumerator::get_Current() // Method begins at RVA 0x2225 // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<M>d__0'::'<>2__current' IL_0006: box [mscorlib]System.Int32 IL_000b: ret } // end of method '<M>d__0'::System.Collections.IEnumerator.get_Current .method private final hidebysig newslot virtual instance class [mscorlib]System.Collections.Generic.IEnumerator`1<int32> 'System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator' () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance class [mscorlib]System.Collections.Generic.IEnumerator`1<!0> class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>::GetEnumerator() // Method begins at RVA 0x2234 // Code size 43 (0x2b) .maxstack 2 .locals init ( [0] class C/'<M>d__0' ) IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<M>d__0'::'<>1__state' IL_0006: ldc.i4.s -2 IL_0008: bne.un.s IL_0022 IL_000a: ldarg.0 IL_000b: ldfld int32 C/'<M>d__0'::'<>l__initialThreadId' IL_0010: call int32 [mscorlib]System.Environment::get_CurrentManagedThreadId() IL_0015: bne.un.s IL_0022 IL_0017: ldarg.0 IL_0018: ldc.i4.0 IL_0019: stfld int32 C/'<M>d__0'::'<>1__state' IL_001e: ldarg.0 IL_001f: stloc.0 IL_0020: br.s IL_0029 IL_0022: ldc.i4.0 IL_0023: newobj instance void C/'<M>d__0'::.ctor(int32) IL_0028: stloc.0 IL_0029: ldloc.0 IL_002a: ret } // end of method '<M>d__0'::'System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator' .method private final hidebysig newslot virtual instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Collections.IEnumerable::GetEnumerator() // Method begins at RVA 0x226b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance class [mscorlib]System.Collections.Generic.IEnumerator`1<int32> C/'<M>d__0'::'System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator'() IL_0006: ret } // end of method '<M>d__0'::System.Collections.IEnumerable.GetEnumerator // Properties .property instance int32 'System.Collections.Generic.IEnumerator<System.Int32>.Current'() { .get instance int32 C/'<M>d__0'::'System.Collections.Generic.IEnumerator<System.Int32>.get_Current'() } .property instance object System.Collections.IEnumerator.Current() { .get instance object C/'<M>d__0'::System.Collections.IEnumerator.get_Current() } } // end of class <M>d__0 // Methods .method public hidebysig instance class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> M () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.IteratorStateMachineAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 09 43 2b 3c 4d 3e 64 5f 5f 30 00 00 ) // Method begins at RVA 0x2050 // Code size 8 (0x8) .maxstack 8 IL_0000: ldc.i4.s -2 IL_0002: newobj instance void C/'<M>d__0'::.ctor(int32) IL_0007: ret } // end of method C::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2059 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor } // end of class C"); } [Fact] public void AsyncAwaitCorrectDisplayClasseAreCreated() { var source = @"using System; using System.Threading.Tasks; public class C { public async Task M() { int a = 1; await Task.Delay(0); while(true) { await Task.Delay(0); int b = 2; await Task.Delay(0); { await Task.Delay(0); int c = 3; target: await Task.Delay(0); { await Task.Delay(0); int d = 4; goto target; await Task.Delay(0); Action e = () => Console.WriteLine(a + b + c + d); } } } } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "C", @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public int32 c .field public class C/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_2' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 d .field public class C/'<>c__DisplayClass0_1' 'CS$<>8__locals2' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_2'::.ctor .method assembly hidebysig instance void '<M>b__0' () cil managed { // Method begins at RVA 0x2093 // Code size 53 (0x35) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0006: ldfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000b: ldfld int32 C/'<>c__DisplayClass0_0'::a IL_0010: ldarg.0 IL_0011: ldfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0016: ldfld int32 C/'<>c__DisplayClass0_1'::b IL_001b: add IL_001c: ldarg.0 IL_001d: ldfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0022: ldfld int32 C/'<>c__DisplayClass0_1'::c IL_0027: add IL_0028: ldarg.0 IL_0029: ldfld int32 C/'<>c__DisplayClass0_2'::d IL_002e: add IL_002f: call void [mscorlib]System.Console::WriteLine(int32) IL_0034: ret } // end of method '<>c__DisplayClass0_2'::'<M>b__0' } // end of class <>c__DisplayClass0_2 .class nested private auto ansi sealed beforefieldinit '<M>d__0' extends [mscorlib]System.ValueType implements [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 '<>1__state' .field public valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder '<>t__builder' .field private class C/'<>c__DisplayClass0_0' '<>8__1' .field private class C/'<>c__DisplayClass0_1' '<>8__2' .field private class C/'<>c__DisplayClass0_2' '<>8__3' .field private valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter '<>u__1' // Methods .method private final hidebysig newslot virtual instance void MoveNext () cil managed { .override method instance void [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine::MoveNext() // Method begins at RVA 0x20cc // Code size 792 (0x318) .maxstack 3 .locals init ( [0] int32, [1] valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, [2] class [mscorlib]System.Exception ) IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<M>d__0'::'<>1__state' IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: switch (IL_0078, IL_00ef, IL_0156, IL_01b1, IL_0218, IL_028f, IL_02c3) IL_0029: ldarg.0 IL_002a: newobj instance void C/'<>c__DisplayClass0_0'::.ctor() IL_002f: stfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_0034: ldarg.0 IL_0035: ldfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_003a: ldc.i4.1 IL_003b: stfld int32 C/'<>c__DisplayClass0_0'::a IL_0040: ldc.i4.0 IL_0041: call class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Threading.Tasks.Task::Delay(int32) IL_0046: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter [mscorlib]System.Threading.Tasks.Task::GetAwaiter() IL_004b: stloc.1 IL_004c: ldloca.s 1 IL_004e: call instance bool [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::get_IsCompleted() IL_0053: brtrue.s IL_0094 IL_0055: ldarg.0 IL_0056: ldc.i4.0 IL_0057: dup IL_0058: stloc.0 IL_0059: stfld int32 C/'<M>d__0'::'<>1__state' IL_005e: ldarg.0 IL_005f: ldloc.1 IL_0060: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0065: ldarg.0 IL_0066: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_006b: ldloca.s 1 IL_006d: ldarg.0 IL_006e: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, valuetype C/'<M>d__0'>(!!0&, !!1&) IL_0073: leave IL_0317 IL_0078: ldarg.0 IL_0079: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_007e: stloc.1 IL_007f: ldarg.0 IL_0080: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0085: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_008b: ldarg.0 IL_008c: ldc.i4.m1 IL_008d: dup IL_008e: stloc.0 IL_008f: stfld int32 C/'<M>d__0'::'<>1__state' IL_0094: ldloca.s 1 IL_0096: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_009b: ldarg.0 IL_009c: newobj instance void C/'<>c__DisplayClass0_1'::.ctor() IL_00a1: stfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_00a6: ldarg.0 IL_00a7: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_00ac: ldarg.0 IL_00ad: ldfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_00b2: stfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_00b7: ldc.i4.0 IL_00b8: call class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Threading.Tasks.Task::Delay(int32) IL_00bd: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter [mscorlib]System.Threading.Tasks.Task::GetAwaiter() IL_00c2: stloc.1 IL_00c3: ldloca.s 1 IL_00c5: call instance bool [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::get_IsCompleted() IL_00ca: brtrue.s IL_010b IL_00cc: ldarg.0 IL_00cd: ldc.i4.1 IL_00ce: dup IL_00cf: stloc.0 IL_00d0: stfld int32 C/'<M>d__0'::'<>1__state' IL_00d5: ldarg.0 IL_00d6: ldloc.1 IL_00d7: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_00dc: ldarg.0 IL_00dd: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_00e2: ldloca.s 1 IL_00e4: ldarg.0 IL_00e5: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, valuetype C/'<M>d__0'>(!!0&, !!1&) IL_00ea: leave IL_0317 IL_00ef: ldarg.0 IL_00f0: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_00f5: stloc.1 IL_00f6: ldarg.0 IL_00f7: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_00fc: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_0102: ldarg.0 IL_0103: ldc.i4.m1 IL_0104: dup IL_0105: stloc.0 IL_0106: stfld int32 C/'<M>d__0'::'<>1__state' IL_010b: ldloca.s 1 IL_010d: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_0112: ldarg.0 IL_0113: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_0118: ldc.i4.2 IL_0119: stfld int32 C/'<>c__DisplayClass0_1'::b IL_011e: ldc.i4.0 IL_011f: call class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Threading.Tasks.Task::Delay(int32) IL_0124: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter [mscorlib]System.Threading.Tasks.Task::GetAwaiter() IL_0129: stloc.1 IL_012a: ldloca.s 1 IL_012c: call instance bool [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::get_IsCompleted() IL_0131: brtrue.s IL_0172 IL_0133: ldarg.0 IL_0134: ldc.i4.2 IL_0135: dup IL_0136: stloc.0 IL_0137: stfld int32 C/'<M>d__0'::'<>1__state' IL_013c: ldarg.0 IL_013d: ldloc.1 IL_013e: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0143: ldarg.0 IL_0144: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_0149: ldloca.s 1 IL_014b: ldarg.0 IL_014c: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, valuetype C/'<M>d__0'>(!!0&, !!1&) IL_0151: leave IL_0317 IL_0156: ldarg.0 IL_0157: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_015c: stloc.1 IL_015d: ldarg.0 IL_015e: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0163: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_0169: ldarg.0 IL_016a: ldc.i4.m1 IL_016b: dup IL_016c: stloc.0 IL_016d: stfld int32 C/'<M>d__0'::'<>1__state' IL_0172: ldloca.s 1 IL_0174: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_0179: ldc.i4.0 IL_017a: call class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Threading.Tasks.Task::Delay(int32) IL_017f: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter [mscorlib]System.Threading.Tasks.Task::GetAwaiter() IL_0184: stloc.1 IL_0185: ldloca.s 1 IL_0187: call instance bool [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::get_IsCompleted() IL_018c: brtrue.s IL_01cd IL_018e: ldarg.0 IL_018f: ldc.i4.3 IL_0190: dup IL_0191: stloc.0 IL_0192: stfld int32 C/'<M>d__0'::'<>1__state' IL_0197: ldarg.0 IL_0198: ldloc.1 IL_0199: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_019e: ldarg.0 IL_019f: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_01a4: ldloca.s 1 IL_01a6: ldarg.0 IL_01a7: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, valuetype C/'<M>d__0'>(!!0&, !!1&) IL_01ac: leave IL_0317 IL_01b1: ldarg.0 IL_01b2: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_01b7: stloc.1 IL_01b8: ldarg.0 IL_01b9: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_01be: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_01c4: ldarg.0 IL_01c5: ldc.i4.m1 IL_01c6: dup IL_01c7: stloc.0 IL_01c8: stfld int32 C/'<M>d__0'::'<>1__state' IL_01cd: ldloca.s 1 IL_01cf: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_01d4: ldarg.0 IL_01d5: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_01da: ldc.i4.3 IL_01db: stfld int32 C/'<>c__DisplayClass0_1'::c IL_01e0: ldc.i4.0 IL_01e1: call class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Threading.Tasks.Task::Delay(int32) IL_01e6: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter [mscorlib]System.Threading.Tasks.Task::GetAwaiter() IL_01eb: stloc.1 IL_01ec: ldloca.s 1 IL_01ee: call instance bool [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::get_IsCompleted() IL_01f3: brtrue.s IL_0234 IL_01f5: ldarg.0 IL_01f6: ldc.i4.4 IL_01f7: dup IL_01f8: stloc.0 IL_01f9: stfld int32 C/'<M>d__0'::'<>1__state' IL_01fe: ldarg.0 IL_01ff: ldloc.1 IL_0200: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0205: ldarg.0 IL_0206: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_020b: ldloca.s 1 IL_020d: ldarg.0 IL_020e: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, valuetype C/'<M>d__0'>(!!0&, !!1&) IL_0213: leave IL_0317 IL_0218: ldarg.0 IL_0219: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_021e: stloc.1 IL_021f: ldarg.0 IL_0220: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0225: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_022b: ldarg.0 IL_022c: ldc.i4.m1 IL_022d: dup IL_022e: stloc.0 IL_022f: stfld int32 C/'<M>d__0'::'<>1__state' IL_0234: ldloca.s 1 IL_0236: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_023b: ldarg.0 IL_023c: newobj instance void C/'<>c__DisplayClass0_2'::.ctor() IL_0241: stfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_0246: ldarg.0 IL_0247: ldfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_024c: ldarg.0 IL_024d: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_0252: stfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0257: ldc.i4.0 IL_0258: call class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Threading.Tasks.Task::Delay(int32) IL_025d: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter [mscorlib]System.Threading.Tasks.Task::GetAwaiter() IL_0262: stloc.1 IL_0263: ldloca.s 1 IL_0265: call instance bool [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::get_IsCompleted() IL_026a: brtrue.s IL_02ab IL_026c: ldarg.0 IL_026d: ldc.i4.5 IL_026e: dup IL_026f: stloc.0 IL_0270: stfld int32 C/'<M>d__0'::'<>1__state' IL_0275: ldarg.0 IL_0276: ldloc.1 IL_0277: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_027c: ldarg.0 IL_027d: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_0282: ldloca.s 1 IL_0284: ldarg.0 IL_0285: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, valuetype C/'<M>d__0'>(!!0&, !!1&) IL_028a: leave IL_0317 IL_028f: ldarg.0 IL_0290: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0295: stloc.1 IL_0296: ldarg.0 IL_0297: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_029c: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_02a2: ldarg.0 IL_02a3: ldc.i4.m1 IL_02a4: dup IL_02a5: stloc.0 IL_02a6: stfld int32 C/'<M>d__0'::'<>1__state' IL_02ab: ldloca.s 1 IL_02ad: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_02b2: ldarg.0 IL_02b3: ldfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_02b8: ldc.i4.4 IL_02b9: stfld int32 C/'<>c__DisplayClass0_2'::d IL_02be: br IL_01e0 IL_02c3: ldarg.0 IL_02c4: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_02c9: stloc.1 IL_02ca: ldarg.0 IL_02cb: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_02d0: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_02d6: ldarg.0 IL_02d7: ldc.i4.m1 IL_02d8: dup IL_02d9: stloc.0 IL_02da: stfld int32 C/'<M>d__0'::'<>1__state' IL_02df: ldloca.s 1 IL_02e1: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_02e6: ldarg.0 IL_02e7: ldnull IL_02e8: stfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_02ed: ldarg.0 IL_02ee: ldnull IL_02ef: stfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_02f4: br IL_009b } // end .try catch [mscorlib]System.Exception { IL_02f9: stloc.2 IL_02fa: ldarg.0 IL_02fb: ldc.i4.s -2 IL_02fd: stfld int32 C/'<M>d__0'::'<>1__state' IL_0302: ldarg.0 IL_0303: ldnull IL_0304: stfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_0309: ldarg.0 IL_030a: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_030f: ldloc.2 IL_0310: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetException(class [mscorlib]System.Exception) IL_0315: leave.s IL_0317 } // end handler IL_0317: ret } // end of method '<M>d__0'::MoveNext .method private final hidebysig newslot virtual instance void SetStateMachine ( class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine stateMachine ) cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance void [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine::SetStateMachine(class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine) // Method begins at RVA 0x240c // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_0006: ldarg.1 IL_0007: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetStateMachine(class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine) IL_000c: ret } // end of method '<M>d__0'::SetStateMachine } // end of class <M>d__0 // Methods .method public hidebysig instance class [mscorlib]System.Threading.Tasks.Task M () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.AsyncStateMachineAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 09 43 2b 3c 4d 3e 64 5f 5f 30 00 00 ) // Method begins at RVA 0x2050 // Code size 47 (0x2f) .maxstack 2 .locals init ( [0] valuetype C/'<M>d__0' ) IL_0000: ldloca.s 0 IL_0002: call valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::Create() IL_0007: stfld valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_000c: ldloca.s 0 IL_000e: ldc.i4.m1 IL_000f: stfld int32 C/'<M>d__0'::'<>1__state' IL_0014: ldloca.s 0 IL_0016: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_001b: ldloca.s 0 IL_001d: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::Start<valuetype C/'<M>d__0'>(!!0&) IL_0022: ldloca.s 0 IL_0024: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_0029: call instance class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::get_Task() IL_002e: ret } // end of method C::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor } // end of class C"); } } }
// 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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenDisplayClassOptimizationTests : CSharpTestBase { private static void VerifyTypeIL(CompilationVerifier compilation, string typeName, string expected) { // .Net Core has different assemblies for the same standard library types as .Net Framework, meaning that that the emitted output will be different to the expected if we run them .Net Core // Since we do not expect there to be any meaningful differences between output for .Net Core and .Net Framework, we will skip these tests on .Net Core if (ExecutionConditionUtil.IsDesktop) { compilation.VerifyTypeIL(typeName, expected); } } [Fact] public void WhenOptimisationsAreEnabled_MergeDisplayClasses() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { int a = 1; { int b = 2; Func<int> c = () => a + b; Console.WriteLine(c()); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3", options: TestOptions.ReleaseExe); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x207a // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance int32 '<Main>b__0' () cil managed { // Method begins at RVA 0x2082 // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 41 (0x29) .maxstack 8 .entrypoint IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: ldc.i4.1 IL_0007: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000c: dup IL_000d: ldc.i4.2 IL_000e: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0013: ldftn instance int32 Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_0019: newobj instance void class [mscorlib]System.Func`1<int32>::.ctor(object, native int) IL_001e: callvirt instance !0 class [mscorlib]System.Func`1<int32>::Invoke() IL_0023: call void [mscorlib]System.Console::WriteLine(int32) IL_0028: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void WhenOptimisationsAreDisabled_DoNotMergeDisplayClasses() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { int a = 1; { int b = 2; Func<int> c = () => a + b; Console.WriteLine(c()); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3", options: TestOptions.DebugExe); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209a // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209a // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance int32 '<Main>b__0' () cil managed { // Method begins at RVA 0x20a3 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 62 (0x3e) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class Program/'<>c__DisplayClass0_1', [2] class [mscorlib]System.Func`1<int32> ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000e: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: ldloc.0 IL_0016: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_001b: nop IL_001c: ldloc.1 IL_001d: ldc.i4.2 IL_001e: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0023: ldloc.1 IL_0024: ldftn instance int32 Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_002a: newobj instance void class [mscorlib]System.Func`1<int32>::.ctor(object, native int) IL_002f: stloc.2 IL_0030: ldloc.2 IL_0031: callvirt instance !0 class [mscorlib]System.Func`1<int32>::Invoke() IL_0036: call void [mscorlib]System.Console::WriteLine(int32) IL_003b: nop IL_003c: nop IL_003d: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForWithBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; for (var i = 0; i < strings.Count; i++) { int x = i; actions.Add(() => { Console.WriteLine(strings[i - x - 1]); }); } actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"three two one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2115 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2115 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x211d // Code size 42 (0x2a) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_001c: sub IL_001d: ldc.i4.1 IL_001e: sub IL_001f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0024: call void [mscorlib]System.Console::WriteLine(string) IL_0029: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 185 (0xb9) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class Program/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_003f: br.s IL_0081 // loop start (head: IL_0081) IL_0041: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0046: stloc.2 IL_0047: ldloc.2 IL_0048: ldloc.0 IL_0049: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_004e: ldloc.2 IL_004f: ldloc.2 IL_0050: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0055: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_005a: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_005f: ldloc.1 IL_0060: ldloc.2 IL_0061: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0067: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_006c: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0071: ldloc.0 IL_0072: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0077: stloc.3 IL_0078: ldloc.0 IL_0079: ldloc.3 IL_007a: ldc.i4.1 IL_007b: add IL_007c: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0081: ldloc.0 IL_0082: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0087: ldloc.0 IL_0088: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_008d: callvirt instance int32 class [mscorlib]System.Collections.Generic.List`1<string>::get_Count() IL_0092: blt.s IL_0041 // end loop IL_0094: ldloc.1 IL_0095: ldc.i4.0 IL_0096: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_009b: callvirt instance void [mscorlib]System.Action::Invoke() IL_00a0: ldloc.1 IL_00a1: ldc.i4.1 IL_00a2: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00a7: callvirt instance void [mscorlib]System.Action::Invoke() IL_00ac: ldloc.1 IL_00ad: ldc.i4.2 IL_00ae: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00b3: callvirt instance void [mscorlib]System.Action::Invoke() IL_00b8: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForInsideWhileCorrectDisplayClassesAreCreated() { var source = @"using System; class C { public static void Main() { int x = 0; int y = 0; while (y < 10) { for (int i = 0; i < 10; i++) { Func<int> f = () => i + x; } y++; } } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "C", @" .class private auto ansi beforefieldinit C extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a7 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 i .field public class C/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a7 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance int32 '<Main>b__0' () cil managed { // Method begins at RVA 0x20af // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<>c__DisplayClass0_1'::i IL_0006: ldarg.0 IL_0007: ldfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000c: ldfld int32 C/'<>c__DisplayClass0_0'::x IL_0011: add IL_0012: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 75 (0x4b) .maxstack 3 .locals init ( [0] class C/'<>c__DisplayClass0_0', [1] int32, [2] class C/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void C/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 C/'<>c__DisplayClass0_0'::x IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br.s IL_0045 // loop start (head: IL_0045) IL_0011: newobj instance void C/'<>c__DisplayClass0_1'::.ctor() IL_0016: stloc.2 IL_0017: ldloc.2 IL_0018: ldloc.0 IL_0019: stfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_001e: ldloc.2 IL_001f: ldc.i4.0 IL_0020: stfld int32 C/'<>c__DisplayClass0_1'::i IL_0025: br.s IL_0037 // loop start (head: IL_0037) IL_0027: ldloc.2 IL_0028: ldfld int32 C/'<>c__DisplayClass0_1'::i IL_002d: stloc.3 IL_002e: ldloc.2 IL_002f: ldloc.3 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stfld int32 C/'<>c__DisplayClass0_1'::i IL_0037: ldloc.2 IL_0038: ldfld int32 C/'<>c__DisplayClass0_1'::i IL_003d: ldc.i4.s 10 IL_003f: blt.s IL_0027 // end loop IL_0041: ldloc.1 IL_0042: ldc.i4.1 IL_0043: add IL_0044: stloc.1 IL_0045: ldloc.1 IL_0046: ldc.i4.s 10 IL_0048: blt.s IL_0011 // end loop IL_004a: ret } // end of method C::Main .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a7 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor } // end of class C"); } [Fact] public void ForInsideEmptyForCorrectDisplayClassesAreCreated() { var source = @"using System; class C { public static void Main() { int x = 0; int y = 0; for(;;) { for (int i = 0; i < 10; i++) { Func<int> f = () => i + x; } y++; break; } } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "C", @" .class private auto ansi beforefieldinit C extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 i .field public class C/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance int32 '<Main>b__0' () cil managed { // Method begins at RVA 0x20a8 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<>c__DisplayClass0_1'::i IL_0006: ldarg.0 IL_0007: ldfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000c: ldfld int32 C/'<>c__DisplayClass0_0'::x IL_0011: add IL_0012: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 68 (0x44) .maxstack 3 .locals init ( [0] class C/'<>c__DisplayClass0_0', [1] int32, [2] class C/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void C/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 C/'<>c__DisplayClass0_0'::x IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: newobj instance void C/'<>c__DisplayClass0_1'::.ctor() IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.0 IL_0017: stfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_001c: ldloc.2 IL_001d: ldc.i4.0 IL_001e: stfld int32 C/'<>c__DisplayClass0_1'::i IL_0023: br.s IL_0035 // loop start (head: IL_0035) IL_0025: ldloc.2 IL_0026: ldfld int32 C/'<>c__DisplayClass0_1'::i IL_002b: stloc.3 IL_002c: ldloc.2 IL_002d: ldloc.3 IL_002e: ldc.i4.1 IL_002f: add IL_0030: stfld int32 C/'<>c__DisplayClass0_1'::i IL_0035: ldloc.2 IL_0036: ldfld int32 C/'<>c__DisplayClass0_1'::i IL_003b: ldc.i4.s 10 IL_003d: blt.s IL_0025 // end loop IL_003f: ldloc.1 IL_0040: ldc.i4.1 IL_0041: add IL_0042: stloc.1 IL_0043: ret } // end of method C::Main .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor } // end of class C"); } [Fact] public void ForWithoutBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; for (var i = 0; i < strings.Count; i++) actions.Add(i is int x ? (Action)(() => Console.WriteLine(strings[i - x - 1])) : () => {}); actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"three two one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2115 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2115 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x211d // Code size 42 (0x2a) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_001c: sub IL_001d: ldc.i4.1 IL_001e: sub IL_001f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0024: call void [mscorlib]System.Console::WriteLine(string) IL_0029: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x2148 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2115 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x2154 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 185 (0xb9) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class Program/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_003f: br.s IL_0081 // loop start (head: IL_0081) IL_0041: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0046: stloc.2 IL_0047: ldloc.2 IL_0048: ldloc.0 IL_0049: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_004e: ldloc.1 IL_004f: ldloc.2 IL_0050: ldloc.2 IL_0051: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0056: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_005b: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_0060: ldloc.2 IL_0061: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0067: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_006c: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0071: ldloc.0 IL_0072: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0077: stloc.3 IL_0078: ldloc.0 IL_0079: ldloc.3 IL_007a: ldc.i4.1 IL_007b: add IL_007c: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0081: ldloc.0 IL_0082: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0087: ldloc.0 IL_0088: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_008d: callvirt instance int32 class [mscorlib]System.Collections.Generic.List`1<string>::get_Count() IL_0092: blt.s IL_0041 // end loop IL_0094: ldloc.1 IL_0095: ldc.i4.0 IL_0096: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_009b: callvirt instance void [mscorlib]System.Action::Invoke() IL_00a0: ldloc.1 IL_00a1: ldc.i4.1 IL_00a2: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00a7: callvirt instance void [mscorlib]System.Action::Invoke() IL_00ac: ldloc.1 IL_00ad: ldc.i4.2 IL_00ae: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00b3: callvirt instance void [mscorlib]System.Action::Invoke() IL_00b8: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForeachWithBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; using System.Linq; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; foreach (var i in Enumerable.Range(0,3)) { int x = i; actions.Add(() => { Console.WriteLine(strings[i - x]); }); } actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"one one one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2124 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 i .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2124 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x212c // Code size 35 (0x23) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_0011: ldarg.0 IL_0012: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_0017: sub IL_0018: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_001d: call void [mscorlib]System.Console::WriteLine(string) IL_0022: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 183 (0xb7) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>, [3] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldc.i4.0 IL_0039: ldc.i4.3 IL_003a: call class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> [System.Core]System.Linq.Enumerable::Range(int32, int32) IL_003f: callvirt instance class [mscorlib]System.Collections.Generic.IEnumerator`1<!0> class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>::GetEnumerator() IL_0044: stloc.2 .try { IL_0045: br.s IL_007e // loop start (head: IL_007e) IL_0047: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_004c: stloc.3 IL_004d: ldloc.3 IL_004e: ldloc.0 IL_004f: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0054: ldloc.3 IL_0055: ldloc.2 IL_0056: callvirt instance !0 class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>::get_Current() IL_005b: stfld int32 Program/'<>c__DisplayClass0_1'::i IL_0060: ldloc.3 IL_0061: ldloc.3 IL_0062: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_0067: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_006c: ldloc.1 IL_006d: ldloc.3 IL_006e: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0074: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0079: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_007e: ldloc.2 IL_007f: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() IL_0084: brtrue.s IL_0047 // end loop IL_0086: leave.s IL_0092 } // end .try finally { IL_0088: ldloc.2 IL_0089: brfalse.s IL_0091 IL_008b: ldloc.2 IL_008c: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_0091: endfinally } // end handler IL_0092: ldloc.1 IL_0093: ldc.i4.0 IL_0094: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0099: callvirt instance void [mscorlib]System.Action::Invoke() IL_009e: ldloc.1 IL_009f: ldc.i4.1 IL_00a0: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00a5: callvirt instance void [mscorlib]System.Action::Invoke() IL_00aa: ldloc.1 IL_00ab: ldc.i4.2 IL_00ac: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00b1: callvirt instance void [mscorlib]System.Action::Invoke() IL_00b6: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForeachWithoutBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; using System.Linq; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; foreach (var i in Enumerable.Range(0,3)) actions.Add(i is int x ? (Action)(() => Console.WriteLine(strings[i - x])) : () => {}); actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"one one one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2124 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 i .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2124 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x212c // Code size 35 (0x23) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_0011: ldarg.0 IL_0012: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_0017: sub IL_0018: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_001d: call void [mscorlib]System.Console::WriteLine(string) IL_0022: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x2150 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2124 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x215c // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 183 (0xb7) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>, [3] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldc.i4.0 IL_0039: ldc.i4.3 IL_003a: call class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> [System.Core]System.Linq.Enumerable::Range(int32, int32) IL_003f: callvirt instance class [mscorlib]System.Collections.Generic.IEnumerator`1<!0> class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>::GetEnumerator() IL_0044: stloc.2 .try { IL_0045: br.s IL_007e // loop start (head: IL_007e) IL_0047: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_004c: stloc.3 IL_004d: ldloc.3 IL_004e: ldloc.0 IL_004f: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0054: ldloc.3 IL_0055: ldloc.2 IL_0056: callvirt instance !0 class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>::get_Current() IL_005b: stfld int32 Program/'<>c__DisplayClass0_1'::i IL_0060: ldloc.1 IL_0061: ldloc.3 IL_0062: ldloc.3 IL_0063: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_0068: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_006d: ldloc.3 IL_006e: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0074: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0079: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_007e: ldloc.2 IL_007f: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() IL_0084: brtrue.s IL_0047 // end loop IL_0086: leave.s IL_0092 } // end .try finally { IL_0088: ldloc.2 IL_0089: brfalse.s IL_0091 IL_008b: ldloc.2 IL_008c: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_0091: endfinally } // end handler IL_0092: ldloc.1 IL_0093: ldc.i4.0 IL_0094: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0099: callvirt instance void [mscorlib]System.Action::Invoke() IL_009e: ldloc.1 IL_009f: ldc.i4.1 IL_00a0: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00a5: callvirt instance void [mscorlib]System.Action::Invoke() IL_00aa: ldloc.1 IL_00ab: ldc.i4.2 IL_00ac: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00b1: callvirt instance void [mscorlib]System.Action::Invoke() IL_00b6: ret } // end of method Program::Main } // end of class Program"); } [CompilerTrait(CompilerFeature.AsyncStreams)] [Fact] public void AwaitForeachCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; using System.Linq; public class C { public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { public int Current { get; } public System.Threading.Tasks.Task<bool> MoveNextAsync() => null; } } public class Program { public static async void M(C enumerable) { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; await foreach (var i in enumerable) actions.Add(i is int x ? (Action)(() => Console.WriteLine(strings[i - x])) : () => {}); actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 i .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<M>b__0' () cil managed { // Method begins at RVA 0x209e // Code size 35 (0x23) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_0011: ldarg.0 IL_0012: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_0017: sub IL_0018: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_001d: call void [mscorlib]System.Console::WriteLine(string) IL_0022: ret } // end of method '<>c__DisplayClass0_1'::'<M>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x20c2 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<M>b__0_1' () cil managed { // Method begins at RVA 0x20ce // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<M>b__0_1' } // end of class <>c .class nested private auto ansi sealed beforefieldinit '<M>d__0' extends [mscorlib]System.ValueType implements [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 '<>1__state' .field public valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder '<>t__builder' .field public class C enumerable .field private class Program/'<>c__DisplayClass0_0' '<>8__1' .field private class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> '<actions>5__2' .field private class C/Enumerator '<>7__wrap2' .field private valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool> '<>u__1' // Methods .method private final hidebysig newslot virtual instance void MoveNext () cil managed { .override method instance void [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine::MoveNext() // Method begins at RVA 0x20d0 // Code size 416 (0x1a0) .maxstack 4 .locals init ( [0] int32, [1] valuetype [mscorlib]System.Threading.CancellationToken, [2] class Program/'<>c__DisplayClass0_1', [3] valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool>, [4] class [mscorlib]System.Exception ) IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<M>d__0'::'<>1__state' IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse IL_00f3 IL_000d: ldarg.0 IL_000e: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0013: stfld class Program/'<>c__DisplayClass0_0' Program/'<M>d__0'::'<>8__1' IL_0018: ldarg.0 IL_0019: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_001e: stfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_0023: ldarg.0 IL_0024: ldfld class Program/'<>c__DisplayClass0_0' Program/'<M>d__0'::'<>8__1' IL_0029: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_002e: dup IL_002f: ldstr ""one"" IL_0034: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0039: dup IL_003a: ldstr ""two"" IL_003f: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0044: dup IL_0045: ldstr ""three"" IL_004a: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_004f: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0054: ldarg.0 IL_0055: ldarg.0 IL_0056: ldfld class C Program/'<M>d__0'::enumerable IL_005b: ldloca.s 1 IL_005d: initobj [mscorlib]System.Threading.CancellationToken IL_0063: ldloc.1 IL_0064: callvirt instance class C/Enumerator C::GetAsyncEnumerator(valuetype [mscorlib]System.Threading.CancellationToken) IL_0069: stfld class C/Enumerator Program/'<M>d__0'::'<>7__wrap2' IL_006e: br.s IL_00b6 IL_0070: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0075: stloc.2 IL_0076: ldloc.2 IL_0077: ldarg.0 IL_0078: ldfld class Program/'<>c__DisplayClass0_0' Program/'<M>d__0'::'<>8__1' IL_007d: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0082: ldloc.2 IL_0083: ldarg.0 IL_0084: ldfld class C/Enumerator Program/'<M>d__0'::'<>7__wrap2' IL_0089: callvirt instance int32 C/Enumerator::get_Current() IL_008e: stfld int32 Program/'<>c__DisplayClass0_1'::i IL_0093: ldarg.0 IL_0094: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_0099: ldloc.2 IL_009a: ldloc.2 IL_009b: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_00a0: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_00a5: ldloc.2 IL_00a6: ldftn instance void Program/'<>c__DisplayClass0_1'::'<M>b__0'() IL_00ac: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_00b1: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_00b6: ldarg.0 IL_00b7: ldfld class C/Enumerator Program/'<M>d__0'::'<>7__wrap2' IL_00bc: callvirt instance class [mscorlib]System.Threading.Tasks.Task`1<bool> C/Enumerator::MoveNextAsync() IL_00c1: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<!0> class [mscorlib]System.Threading.Tasks.Task`1<bool>::GetAwaiter() IL_00c6: stloc.3 IL_00c7: ldloca.s 3 IL_00c9: call instance bool valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool>::get_IsCompleted() IL_00ce: brtrue.s IL_010f IL_00d0: ldarg.0 IL_00d1: ldc.i4.0 IL_00d2: dup IL_00d3: stloc.0 IL_00d4: stfld int32 Program/'<M>d__0'::'<>1__state' IL_00d9: ldarg.0 IL_00da: ldloc.3 IL_00db: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool> Program/'<M>d__0'::'<>u__1' IL_00e0: ldarg.0 IL_00e1: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program/'<M>d__0'::'<>t__builder' IL_00e6: ldloca.s 3 IL_00e8: ldarg.0 IL_00e9: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool>, valuetype Program/'<M>d__0'>(!!0&, !!1&) IL_00ee: leave IL_019f IL_00f3: ldarg.0 IL_00f4: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool> Program/'<M>d__0'::'<>u__1' IL_00f9: stloc.3 IL_00fa: ldarg.0 IL_00fb: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool> Program/'<M>d__0'::'<>u__1' IL_0100: initobj valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool> IL_0106: ldarg.0 IL_0107: ldc.i4.m1 IL_0108: dup IL_0109: stloc.0 IL_010a: stfld int32 Program/'<M>d__0'::'<>1__state' IL_010f: ldloca.s 3 IL_0111: call instance !0 valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter`1<bool>::GetResult() IL_0116: brtrue IL_0070 IL_011b: ldarg.0 IL_011c: ldnull IL_011d: stfld class C/Enumerator Program/'<M>d__0'::'<>7__wrap2' IL_0122: ldarg.0 IL_0123: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_0128: ldc.i4.0 IL_0129: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_012e: callvirt instance void [mscorlib]System.Action::Invoke() IL_0133: ldarg.0 IL_0134: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_0139: ldc.i4.1 IL_013a: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_013f: callvirt instance void [mscorlib]System.Action::Invoke() IL_0144: ldarg.0 IL_0145: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_014a: ldc.i4.2 IL_014b: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0150: callvirt instance void [mscorlib]System.Action::Invoke() IL_0155: leave.s IL_017e } // end .try catch [mscorlib]System.Exception { IL_0157: stloc.s 4 IL_0159: ldarg.0 IL_015a: ldc.i4.s -2 IL_015c: stfld int32 Program/'<M>d__0'::'<>1__state' IL_0161: ldarg.0 IL_0162: ldnull IL_0163: stfld class Program/'<>c__DisplayClass0_0' Program/'<M>d__0'::'<>8__1' IL_0168: ldarg.0 IL_0169: ldnull IL_016a: stfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_016f: ldarg.0 IL_0170: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program/'<M>d__0'::'<>t__builder' IL_0175: ldloc.s 4 IL_0177: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::SetException(class [mscorlib]System.Exception) IL_017c: leave.s IL_019f } // end handler IL_017e: ldarg.0 IL_017f: ldc.i4.s -2 IL_0181: stfld int32 Program/'<M>d__0'::'<>1__state' IL_0186: ldarg.0 IL_0187: ldnull IL_0188: stfld class Program/'<>c__DisplayClass0_0' Program/'<M>d__0'::'<>8__1' IL_018d: ldarg.0 IL_018e: ldnull IL_018f: stfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<M>d__0'::'<actions>5__2' IL_0194: ldarg.0 IL_0195: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program/'<M>d__0'::'<>t__builder' IL_019a: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::SetResult() IL_019f: ret } // end of method '<M>d__0'::MoveNext .method private final hidebysig newslot virtual instance void SetStateMachine ( class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine stateMachine ) cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance void [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine::SetStateMachine(class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine) // Method begins at RVA 0x2298 // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program/'<M>d__0'::'<>t__builder' IL_0006: ldarg.1 IL_0007: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::SetStateMachine(class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine) IL_000c: ret } // end of method '<M>d__0'::SetStateMachine } // end of class <M>d__0 // Methods .method public hidebysig static void M ( class C enumerable ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.AsyncStateMachineAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 0f 50 72 6f 67 72 61 6d 2b 3c 4d 3e 64 5f 5f 30 00 00 ) // Method begins at RVA 0x205c // Code size 43 (0x2b) .maxstack 2 .locals init ( [0] valuetype Program/'<M>d__0' ) IL_0000: ldloca.s 0 IL_0002: call valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::Create() IL_0007: stfld valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program/'<M>d__0'::'<>t__builder' IL_000c: ldloca.s 0 IL_000e: ldarg.0 IL_000f: stfld class C Program/'<M>d__0'::enumerable IL_0014: ldloca.s 0 IL_0016: ldc.i4.m1 IL_0017: stfld int32 Program/'<M>d__0'::'<>1__state' IL_001c: ldloca.s 0 IL_001e: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program/'<M>d__0'::'<>t__builder' IL_0023: ldloca.s 0 IL_0025: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncVoidMethodBuilder::Start<valuetype Program/'<M>d__0'>(!!0&) IL_002a: ret } // end of method Program::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void IfWithBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one""}; if (0 is int i) { var x = i; actions.Add(() => { Console.WriteLine(strings[i + x]); }); } actions[0](); } }"; var compilation = CompileAndVerify(source, expectedOutput: "one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20b8 // Code size 30 (0x1e) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_000c: ldarg.0 IL_000d: ldfld int32 Program/'<>c__DisplayClass0_0'::x IL_0012: add IL_0013: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0018: call void [mscorlib]System.Console::WriteLine(string) IL_001d: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 84 (0x54) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0029: ldloc.0 IL_002a: ldloc.0 IL_002b: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0030: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_0035: ldloc.1 IL_0036: ldloc.0 IL_0037: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_003d: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0042: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0047: ldloc.1 IL_0048: ldc.i4.0 IL_0049: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_004e: callvirt instance void [mscorlib]System.Action::Invoke() IL_0053: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void IfWithoutBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one""}; if (0 is int i) actions.Add(i is int x ? (Action)(() => Console.WriteLine(strings[i + x])) : () => {}); actions[0](); } }"; var compilation = CompileAndVerify(source, expectedOutput: "one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20b8 // Code size 30 (0x1e) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_000c: ldarg.0 IL_000d: ldfld int32 Program/'<>c__DisplayClass0_0'::x IL_0012: add IL_0013: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0018: call void [mscorlib]System.Console::WriteLine(string) IL_001d: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x20d7 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x20e3 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 84 (0x54) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0029: ldloc.1 IL_002a: ldloc.0 IL_002b: ldloc.0 IL_002c: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0031: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_0036: ldloc.0 IL_0037: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_003d: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0042: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0047: ldloc.1 IL_0048: ldc.i4.0 IL_0049: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_004e: callvirt instance void [mscorlib]System.Action::Invoke() IL_0053: ret } // end of method Program::Main } // end of class Program "); } [Fact] public void ElseWithoutBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one""}; if(true) if (!(0 is int i) || strings[0] != ""one"") throw new Exception(); else actions.Add(i is int x ? (Action)(() => Console.WriteLine(strings[i + x])) : () => {}); actions[0](); } }"; var compilation = CompileAndVerify(source, expectedOutput: "one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20ce // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20d6 // Code size 30 (0x1e) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_000c: ldarg.0 IL_000d: ldfld int32 Program/'<>c__DisplayClass0_0'::x IL_0012: add IL_0013: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0018: call void [mscorlib]System.Console::WriteLine(string) IL_001d: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x20f5 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20ce // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x2101 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 114 (0x72) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0029: ldloc.0 IL_002a: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_002f: ldc.i4.0 IL_0030: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0035: ldstr ""one"" IL_003a: call bool [mscorlib]System.String::op_Inequality(string, string) IL_003f: brfalse.s IL_0047 IL_0041: newobj instance void [mscorlib]System.Exception::.ctor() IL_0046: throw IL_0047: ldloc.1 IL_0048: ldloc.0 IL_0049: ldloc.0 IL_004a: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_004f: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_0054: ldloc.0 IL_0055: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_005b: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0060: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0065: ldloc.1 IL_0066: ldc.i4.0 IL_0067: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_006c: callvirt instance void [mscorlib]System.Action::Invoke() IL_0071: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void UsingWithBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"" }; using (var disposable = new Disposable()) { var i = 0; actions.Add(() => { Console.WriteLine(disposable.ToString()); Console.WriteLine(strings[i]); }); } actions[0](); } public class Disposable : IDisposable { public void Dispose(){} } }"; var compilation = CompileAndVerify(source, expectedOutput: @"Program+Disposable one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested public auto ansi beforefieldinit Disposable extends [mscorlib]System.Object implements [mscorlib]System.IDisposable { // Methods .method public final hidebysig newslot virtual instance void Dispose () cil managed { // Method begins at RVA 0x20d8 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Disposable::Dispose .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20da // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Disposable::.ctor } // end of class Disposable .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public class Program/Disposable disposable .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20da // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20e2 // Code size 39 (0x27) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable IL_0006: callvirt instance string [mscorlib]System.Object::ToString() IL_000b: call void [mscorlib]System.Console::WriteLine(string) IL_0010: ldarg.0 IL_0011: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_001c: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0021: call void [mscorlib]System.Console::WriteLine(string) IL_0026: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 105 (0x69) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0022: ldloc.0 IL_0023: newobj instance void Program/Disposable::.ctor() IL_0028: stfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable .try { IL_002d: ldloc.0 IL_002e: ldc.i4.0 IL_002f: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0034: ldloc.1 IL_0035: ldloc.0 IL_0036: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_003c: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0041: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0046: leave.s IL_005c } // end .try finally { IL_0048: ldloc.0 IL_0049: ldfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable IL_004e: brfalse.s IL_005b IL_0050: ldloc.0 IL_0051: ldfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable IL_0056: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_005b: endfinally } // end handler IL_005c: ldloc.1 IL_005d: ldc.i4.0 IL_005e: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0063: callvirt instance void [mscorlib]System.Action::Invoke() IL_0068: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void UsingWithoutBlockCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"" }; using (var disposable = new Disposable()) actions.Add(0 is int i ? (Action)(() => { Console.WriteLine(disposable.ToString()); Console.WriteLine(strings[i]); }) : () => {}); actions[0](); } public class Disposable : IDisposable { public void Dispose(){} } }"; var compilation = CompileAndVerify(source, expectedOutput: @"Program+Disposable one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested public auto ansi beforefieldinit Disposable extends [mscorlib]System.Object implements [mscorlib]System.IDisposable { // Methods .method public final hidebysig newslot virtual instance void Dispose () cil managed { // Method begins at RVA 0x20d8 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Disposable::Dispose .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20da // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Disposable::.ctor } // end of class Disposable .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public class Program/Disposable disposable .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20da // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20e2 // Code size 39 (0x27) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable IL_0006: callvirt instance string [mscorlib]System.Object::ToString() IL_000b: call void [mscorlib]System.Console::WriteLine(string) IL_0010: ldarg.0 IL_0011: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_001c: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0021: call void [mscorlib]System.Console::WriteLine(string) IL_0026: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x210a // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20da // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x20d8 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 105 (0x69) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0022: ldloc.0 IL_0023: newobj instance void Program/Disposable::.ctor() IL_0028: stfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable .try { IL_002d: ldloc.1 IL_002e: ldloc.0 IL_002f: ldc.i4.0 IL_0030: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0035: ldloc.0 IL_0036: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_003c: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0041: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0046: leave.s IL_005c } // end .try finally { IL_0048: ldloc.0 IL_0049: ldfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable IL_004e: brfalse.s IL_005b IL_0050: ldloc.0 IL_0051: ldfld class Program/Disposable Program/'<>c__DisplayClass0_0'::disposable IL_0056: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_005b: endfinally } // end handler IL_005c: ldloc.1 IL_005d: ldc.i4.0 IL_005e: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0063: callvirt instance void [mscorlib]System.Action::Invoke() IL_0068: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void IfInUsingInForeachInForCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; using System.Linq; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; foreach(var i in Enumerable.Range(0,1)) for (var j = 0; j < strings.Count; j++) using (var disposable = new Disposable()) if(j is int x) actions.Add(0 is int y ? (Action)(() => { Console.WriteLine(disposable.ToString()); Console.WriteLine(strings[j - x - 1 + i + y]); }) : () => { }); actions[0](); actions[1](); actions[2](); } public class Disposable : IDisposable { public void Dispose() { } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"Program+Disposable three Program+Disposable two Program+Disposable one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested public auto ansi beforefieldinit Disposable extends [mscorlib]System.Object implements [mscorlib]System.IDisposable { // Methods .method public final hidebysig newslot virtual instance void Dispose () cil managed { // Method begins at RVA 0x21b0 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method Disposable::Dispose .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x21b2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Disposable::.ctor } // end of class Disposable .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x21b2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 i .field public int32 j .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x21b2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_2' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class Program/Disposable disposable .field public int32 x .field public int32 y .field public class Program/'<>c__DisplayClass0_1' 'CS$<>8__locals2' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x21b2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_2'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x21bc // Code size 82 (0x52) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldfld class Program/Disposable Program/'<>c__DisplayClass0_2'::disposable IL_0006: callvirt instance string [mscorlib]System.Object::ToString() IL_000b: call void [mscorlib]System.Console::WriteLine(string) IL_0010: ldarg.0 IL_0011: ldfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0016: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_001b: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0020: ldarg.0 IL_0021: ldfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0026: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_002b: ldarg.0 IL_002c: ldfld int32 Program/'<>c__DisplayClass0_2'::x IL_0031: sub IL_0032: ldc.i4.1 IL_0033: sub IL_0034: ldarg.0 IL_0035: ldfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_003a: ldfld int32 Program/'<>c__DisplayClass0_1'::i IL_003f: add IL_0040: ldarg.0 IL_0041: ldfld int32 Program/'<>c__DisplayClass0_2'::y IL_0046: add IL_0047: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_004c: call void [mscorlib]System.Console::WriteLine(string) IL_0051: ret } // end of method '<>c__DisplayClass0_2'::'<Main>b__0' } // end of class <>c__DisplayClass0_2 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x221a // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x21b2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x21b0 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 310 (0x136) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>, [3] class Program/'<>c__DisplayClass0_1', [4] class Program/'<>c__DisplayClass0_2', [5] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldc.i4.0 IL_0039: ldc.i4.1 IL_003a: call class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> [System.Core]System.Linq.Enumerable::Range(int32, int32) IL_003f: callvirt instance class [mscorlib]System.Collections.Generic.IEnumerator`1<!0> class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>::GetEnumerator() IL_0044: stloc.2 .try { IL_0045: br IL_00fa // loop start (head: IL_00fa) IL_004a: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_004f: stloc.3 IL_0050: ldloc.3 IL_0051: ldloc.0 IL_0052: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0057: ldloc.3 IL_0058: ldloc.2 IL_0059: callvirt instance !0 class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>::get_Current() IL_005e: stfld int32 Program/'<>c__DisplayClass0_1'::i IL_0063: ldloc.3 IL_0064: ldc.i4.0 IL_0065: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_006a: br.s IL_00df // loop start (head: IL_00df) IL_006c: newobj instance void Program/'<>c__DisplayClass0_2'::.ctor() IL_0071: stloc.s 4 IL_0073: ldloc.s 4 IL_0075: ldloc.3 IL_0076: stfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_007b: ldloc.s 4 IL_007d: newobj instance void Program/Disposable::.ctor() IL_0082: stfld class Program/Disposable Program/'<>c__DisplayClass0_2'::disposable .try { IL_0087: ldloc.s 4 IL_0089: ldloc.s 4 IL_008b: ldfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0090: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_0095: stfld int32 Program/'<>c__DisplayClass0_2'::x IL_009a: ldloc.1 IL_009b: ldloc.s 4 IL_009d: ldc.i4.0 IL_009e: stfld int32 Program/'<>c__DisplayClass0_2'::y IL_00a3: ldloc.s 4 IL_00a5: ldftn instance void Program/'<>c__DisplayClass0_2'::'<Main>b__0'() IL_00ab: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_00b0: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_00b5: leave.s IL_00cd } // end .try finally { IL_00b7: ldloc.s 4 IL_00b9: ldfld class Program/Disposable Program/'<>c__DisplayClass0_2'::disposable IL_00be: brfalse.s IL_00cc IL_00c0: ldloc.s 4 IL_00c2: ldfld class Program/Disposable Program/'<>c__DisplayClass0_2'::disposable IL_00c7: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_00cc: endfinally } // end handler IL_00cd: ldloc.3 IL_00ce: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_00d3: stloc.s 5 IL_00d5: ldloc.3 IL_00d6: ldloc.s 5 IL_00d8: ldc.i4.1 IL_00d9: add IL_00da: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_00df: ldloc.3 IL_00e0: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_00e5: ldloc.3 IL_00e6: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_00eb: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_00f0: callvirt instance int32 class [mscorlib]System.Collections.Generic.List`1<string>::get_Count() IL_00f5: blt IL_006c // end loop IL_00fa: ldloc.2 IL_00fb: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() IL_0100: brtrue IL_004a // end loop IL_0105: leave.s IL_0111 } // end .try finally { IL_0107: ldloc.2 IL_0108: brfalse.s IL_0110 IL_010a: ldloc.2 IL_010b: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_0110: endfinally } // end handler IL_0111: ldloc.1 IL_0112: ldc.i4.0 IL_0113: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0118: callvirt instance void [mscorlib]System.Action::Invoke() IL_011d: ldloc.1 IL_011e: ldc.i4.1 IL_011f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0124: callvirt instance void [mscorlib]System.Action::Invoke() IL_0129: ldloc.1 IL_012a: ldc.i4.2 IL_012b: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0130: callvirt instance void [mscorlib]System.Action::Invoke() IL_0135: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void WhileCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; int i = 0; while(i is int j && i++ < 3) actions.Add(0 is int x ? (Action)(() => Console.WriteLine(strings[j + x])) : () => { }); actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"one two three"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20f2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 j .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20f2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20fa // Code size 35 (0x23) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_0011: ldarg.0 IL_0012: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_0017: add IL_0018: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_001d: call void [mscorlib]System.Console::WriteLine(string) IL_0022: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x211e // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20f2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x212a // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 150 (0x96) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] int32, [3] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldc.i4.0 IL_0039: stloc.2 // loop start (head: IL_003a) IL_003a: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_003f: stloc.3 IL_0040: ldloc.3 IL_0041: ldloc.0 IL_0042: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0047: ldloc.3 IL_0048: ldloc.2 IL_0049: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_004e: ldloc.2 IL_004f: dup IL_0050: ldc.i4.1 IL_0051: add IL_0052: stloc.2 IL_0053: ldc.i4.3 IL_0054: bge.s IL_0071 IL_0056: ldloc.1 IL_0057: ldloc.3 IL_0058: ldc.i4.0 IL_0059: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_005e: ldloc.3 IL_005f: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0065: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_006a: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_006f: br.s IL_003a // end loop IL_0071: ldloc.1 IL_0072: ldc.i4.0 IL_0073: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0078: callvirt instance void [mscorlib]System.Action::Invoke() IL_007d: ldloc.1 IL_007e: ldc.i4.1 IL_007f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0084: callvirt instance void [mscorlib]System.Action::Invoke() IL_0089: ldloc.1 IL_008a: ldc.i4.2 IL_008b: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0090: callvirt instance void [mscorlib]System.Action::Invoke() IL_0095: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForWithVariableDeclaredInInvocationExpressionInIteratorCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; for (int i = 0; ++i < 3; actions.Add(i is int j ? (Action)(() => { Console.WriteLine(strings[i - j - 1]); }) : () => { })) ; actions[0](); actions[1](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"two one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20fa // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 j .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20fa // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2102 // Code size 42 (0x2a) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_001c: sub IL_001d: ldc.i4.1 IL_001e: sub IL_001f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0024: call void [mscorlib]System.Console::WriteLine(string) IL_0029: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x212d // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20fa // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x2139 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 158 (0x9e) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class Program/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_003f: br.s IL_0071 // loop start (head: IL_0071) IL_0041: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0046: stloc.2 IL_0047: ldloc.2 IL_0048: ldloc.0 IL_0049: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_004e: ldloc.1 IL_004f: ldloc.2 IL_0050: ldloc.2 IL_0051: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0056: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_005b: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_0060: ldloc.2 IL_0061: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0067: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_006c: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0071: ldloc.0 IL_0072: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0077: ldc.i4.1 IL_0078: add IL_0079: stloc.3 IL_007a: ldloc.0 IL_007b: ldloc.3 IL_007c: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0081: ldloc.3 IL_0082: ldc.i4.3 IL_0083: blt.s IL_0041 // end loop IL_0085: ldloc.1 IL_0086: ldc.i4.0 IL_0087: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_008c: callvirt instance void [mscorlib]System.Action::Invoke() IL_0091: ldloc.1 IL_0092: ldc.i4.1 IL_0093: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0098: callvirt instance void [mscorlib]System.Action::Invoke() IL_009d: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForWithVariableDeclaredInSimpleAssignmentExpressionInIteratorCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var strings = new List<string>() { ""one"", ""two"", ""three"" }; Action action = null; for (int i = 0; ++i < 2; action = i is int j ? (Action)(() => { Console.WriteLine(strings[i - j - 1]); }) : () => { }) ; action(); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20df // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 j .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20df // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20e7 // Code size 42 (0x2a) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_001c: sub IL_001d: ldc.i4.1 IL_001e: sub IL_001f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0024: call void [mscorlib]System.Console::WriteLine(string) IL_0029: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x2112 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20df // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x211e // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 131 (0x83) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Action, [2] class Program/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_000c: dup IL_000d: ldstr ""one"" IL_0012: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0017: dup IL_0018: ldstr ""two"" IL_001d: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0022: dup IL_0023: ldstr ""three"" IL_0028: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_002d: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0032: ldnull IL_0033: stloc.1 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_003b: br.s IL_0068 // loop start (head: IL_0068) IL_003d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0042: stloc.2 IL_0043: ldloc.2 IL_0044: ldloc.0 IL_0045: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_004a: ldloc.2 IL_004b: ldloc.2 IL_004c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0051: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0056: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_005b: ldloc.2 IL_005c: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0062: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0067: stloc.1 IL_0068: ldloc.0 IL_0069: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_006e: ldc.i4.1 IL_006f: add IL_0070: stloc.3 IL_0071: ldloc.0 IL_0072: ldloc.3 IL_0073: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0078: ldloc.3 IL_0079: ldc.i4.2 IL_007a: blt.s IL_003d // end loop IL_007c: ldloc.1 IL_007d: callvirt instance void [mscorlib]System.Action::Invoke() IL_0082: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForWithVariableDeclaredInConditionCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var strings = new List<string>() { ""one"" }; Action action = null; for (int i = 0; i is int j && null == (action = () => { Console.WriteLine(strings[i + j]); });) break; ; action(); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b5 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 j .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b5 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20bd // Code size 40 (0x28) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_001c: add IL_001d: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0022: call void [mscorlib]System.Console::WriteLine(string) IL_0027: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 89 (0x59) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Action, [2] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_000c: dup IL_000d: ldstr ""one"" IL_0012: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0017: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_001c: ldnull IL_001d: stloc.1 IL_001e: ldloc.0 IL_001f: ldc.i4.0 IL_0020: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0025: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_002a: stloc.2 IL_002b: ldloc.2 IL_002c: ldloc.0 IL_002d: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0032: ldloc.2 IL_0033: ldloc.2 IL_0034: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0039: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_003e: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_0043: ldloc.2 IL_0044: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_004a: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_004f: dup IL_0050: stloc.1 IL_0051: pop IL_0052: ldloc.1 IL_0053: callvirt instance void [mscorlib]System.Action::Invoke() IL_0058: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ForWithVariableDeclaredInConditionAndNoneInInitializerCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var strings = new List<string>() { ""one"" }; Action action = null; int i = 0; for (; i is int j && null == (action = () => { Console.WriteLine(strings[i + j]); });) break; ; action(); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b5 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 j .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20b5 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20bd // Code size 40 (0x28) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::j IL_001c: add IL_001d: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0022: call void [mscorlib]System.Console::WriteLine(string) IL_0027: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 89 (0x59) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Action, [2] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_000c: dup IL_000d: ldstr ""one"" IL_0012: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0017: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_001c: ldnull IL_001d: stloc.1 IL_001e: ldloc.0 IL_001f: ldc.i4.0 IL_0020: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_0025: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_002a: stloc.2 IL_002b: ldloc.2 IL_002c: ldloc.0 IL_002d: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0032: ldloc.2 IL_0033: ldloc.2 IL_0034: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0039: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_003e: stfld int32 Program/'<>c__DisplayClass0_1'::j IL_0043: ldloc.2 IL_0044: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_004a: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_004f: dup IL_0050: stloc.1 IL_0051: pop IL_0052: ldloc.1 IL_0053: callvirt instance void [mscorlib]System.Action::Invoke() IL_0058: ret } // end of method Program::Main } // end of class Program "); } [Fact] public void DoWhileCorrectDisplayClassesAreCreated() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var actions = new List<Action>(); var strings = new List<string>() { ""one"", ""two"", ""three"" }; int i = 0; do actions.Add(i is int x ? (Action)(() => Console.WriteLine(strings[i - x - 1])) : () => { }); while (++i < 3); actions[0](); actions[1](); actions[2](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"three two one"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<string> strings .field public int32 i // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2104 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2104 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x210c // Code size 42 (0x2a) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0016: ldarg.0 IL_0017: ldfld int32 Program/'<>c__DisplayClass0_1'::x IL_001c: sub IL_001d: ldc.i4.1 IL_001e: sub IL_001f: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<string>::get_Item(int32) IL_0024: call void [mscorlib]System.Console::WriteLine(string) IL_0029: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed serializable beforefieldinit '<>c' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static initonly class Program/'<>c' '<>9' .field public static class [mscorlib]System.Action '<>9__0_1' // Methods .method private hidebysig specialname rtspecialname static void .cctor () cil managed { // Method begins at RVA 0x2137 // Code size 11 (0xb) .maxstack 8 IL_0000: newobj instance void Program/'<>c'::.ctor() IL_0005: stsfld class Program/'<>c' Program/'<>c'::'<>9' IL_000a: ret } // end of method '<>c'::.cctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2104 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c'::.ctor .method assembly hidebysig instance void '<Main>b__0_1' () cil managed { // Method begins at RVA 0x2143 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<>c'::'<Main>b__0_1' } // end of class <>c // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 168 (0xa8) .maxstack 4 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>, [2] class Program/'<>c__DisplayClass0_1', [3] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0012: dup IL_0013: ldstr ""one"" IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_001d: dup IL_001e: ldstr ""two"" IL_0023: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0028: dup IL_0029: ldstr ""three"" IL_002e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0) IL_0033: stfld class [mscorlib]System.Collections.Generic.List`1<string> Program/'<>c__DisplayClass0_0'::strings IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: stfld int32 Program/'<>c__DisplayClass0_0'::i // loop start (head: IL_003f) IL_003f: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0044: stloc.2 IL_0045: ldloc.2 IL_0046: ldloc.0 IL_0047: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_004c: ldloc.1 IL_004d: ldloc.2 IL_004e: ldloc.2 IL_004f: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0054: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0059: stfld int32 Program/'<>c__DisplayClass0_1'::x IL_005e: ldloc.2 IL_005f: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0065: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_006a: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_006f: ldloc.0 IL_0070: ldfld int32 Program/'<>c__DisplayClass0_0'::i IL_0075: ldc.i4.1 IL_0076: add IL_0077: stloc.3 IL_0078: ldloc.0 IL_0079: ldloc.3 IL_007a: stfld int32 Program/'<>c__DisplayClass0_0'::i IL_007f: ldloc.3 IL_0080: ldc.i4.3 IL_0081: blt.s IL_003f // end loop IL_0083: ldloc.1 IL_0084: ldc.i4.0 IL_0085: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_008a: callvirt instance void [mscorlib]System.Action::Invoke() IL_008f: ldloc.1 IL_0090: ldc.i4.1 IL_0091: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0096: callvirt instance void [mscorlib]System.Action::Invoke() IL_009b: ldloc.1 IL_009c: ldc.i4.2 IL_009d: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_00a2: callvirt instance void [mscorlib]System.Action::Invoke() IL_00a7: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsBackwardsGoToMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { target: ; int b = 1; Action action = () => Console.WriteLine(a + b); action(); return; goto target; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2082 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x208a // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 38 (0x26) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0014: ldloc.0 IL_0015: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_001b: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0020: callvirt instance void [mscorlib]System.Action::Invoke() IL_0025: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsForwardsGoToMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { goto target; int b = 1; Action action = () => Console.WriteLine(a + b); action(); target: ; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @""); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x206a // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2072 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 14 (0xe) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsBackwardsGoToCaseMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; switch(a) { case 1: default: int b = 1; Action action = () => Console.WriteLine(a + b); action(); break; case 0: goto case 1; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2090 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2098 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 52 (0x34) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_001b IL_0017: ldloc.1 IL_0018: ldc.i4.1 IL_0019: pop IL_001a: pop IL_001b: ldloc.0 IL_001c: ldc.i4.1 IL_001d: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0022: ldloc.0 IL_0023: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_0029: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002e: callvirt instance void [mscorlib]System.Action::Invoke() IL_0033: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsForwardsGoToCaseMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; switch(a) { case 0: goto case 1; case 1: default: int b = 1; Action action = () => Console.WriteLine(a + b); action(); break; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2090 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2098 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 52 (0x34) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_001b IL_0017: ldloc.1 IL_0018: ldc.i4.1 IL_0019: pop IL_001a: pop IL_001b: ldloc.0 IL_001c: ldc.i4.1 IL_001d: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0022: ldloc.0 IL_0023: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_0029: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002e: callvirt instance void [mscorlib]System.Action::Invoke() IL_0033: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsBackwardsGoToDefaultMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; switch(a) { default: int b = 1; Action action = () => Console.WriteLine(a + b); action(); break; case 0: goto default; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2089 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2091 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 45 (0x2d) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0013: pop IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_001b: ldloc.0 IL_001c: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_0022: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0027: callvirt instance void [mscorlib]System.Action::Invoke() IL_002c: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsForwardsGoToDefaultMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; switch(a) { case 0: int b = 1; Action action = () => Console.WriteLine(a + b); action(); goto default; default: break; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208a // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2092 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 46 (0x2e) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0013: brtrue.s IL_002d IL_0015: ldloc.0 IL_0016: ldc.i4.1 IL_0017: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_001c: ldloc.0 IL_001d: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_0023: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0028: callvirt instance void [mscorlib]System.Action::Invoke() IL_002d: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void ScopeContainsScopeContainingBackwardsGoToMergeDisplayClasses() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { target: ; int b = 1; Action action = () => Console.WriteLine(a + b); action(); return; { goto target; } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2082 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x208a // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 38 (0x26) .maxstack 2 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0014: ldloc.0 IL_0015: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_001b: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0020: callvirt instance void [mscorlib]System.Action::Invoke() IL_0025: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void BackwardsGoToToPointInBetweenScopeAndParentPreventsMerging01() { var source = @"using System; public static class Program { public static void Main() { int a = 0; target: ; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); } return; goto target; } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2095 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 49 (0x31) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: dup IL_0013: ldloc.0 IL_0014: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0019: dup IL_001a: ldc.i4.1 IL_001b: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0020: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0026: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002b: callvirt instance void [mscorlib]System.Action::Invoke() IL_0030: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void BackwardsGoToToPointInBetweenScopeAndParentPreventsMerging02() { var source = @"using System; public static class Program { public static void Main() { int a = 0; target: ; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); } return; { goto target; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2095 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 49 (0x31) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: dup IL_0013: ldloc.0 IL_0014: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0019: dup IL_001a: ldc.i4.1 IL_001b: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0020: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0026: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002b: callvirt instance void [mscorlib]System.Action::Invoke() IL_0030: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void BackwardsGoToToPointInBetweenScopeAndParentPreventsMerging03() { var source = @"using System; public static class Program { public static void Main() { int a = 0; target: ; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); return; goto target; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2095 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 49 (0x31) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: dup IL_0013: ldloc.0 IL_0014: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0019: dup IL_001a: ldc.i4.1 IL_001b: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0020: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0026: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002b: callvirt instance void [mscorlib]System.Action::Invoke() IL_0030: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void BackwardsGoToToPointInBetweenScopeAndParentPreventsMerging04() { var source = @"using System; public static class Program { public static void Main() { int a = 0; target: ; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); return; { goto target; } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2095 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 49 (0x31) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: dup IL_0013: ldloc.0 IL_0014: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0019: dup IL_001a: ldc.i4.1 IL_001b: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0020: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0026: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002b: callvirt instance void [mscorlib]System.Action::Invoke() IL_0030: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void BackwardsGoToCaseToPointInBetweenScopeAndParentPreventsMerging() { var source = @"using System; public static class Program { public static void Main() { int a = 0; switch(a) { case 1: default: { int b = 1; Action action = () => Console.WriteLine(a + b); action(); break; } case 0: goto case 1; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20a3 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 63 (0x3f) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] int32 ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_001b IL_0017: ldloc.1 IL_0018: ldc.i4.1 IL_0019: pop IL_001a: pop IL_001b: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0020: dup IL_0021: ldloc.0 IL_0022: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0027: dup IL_0028: ldc.i4.1 IL_0029: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_002e: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0034: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0039: callvirt instance void [mscorlib]System.Action::Invoke() IL_003e: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void BackwardsGoToDefaultToPointInBetweenScopeAndParentPreventsMerging() { var source = @"using System; public static class Program { public static void Main() { int a = 0; switch(a) { default: { int b = 1; Action action = () => Console.WriteLine(a + b); action(); break; } case 0: goto default; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2094 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2094 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x209c // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 56 (0x38) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0013: pop IL_0014: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0019: dup IL_001a: ldloc.0 IL_001b: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0020: dup IL_0021: ldc.i4.1 IL_0022: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0027: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_002d: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0032: callvirt instance void [mscorlib]System.Action::Invoke() IL_0037: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable01() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); } Action _ = () => Console.WriteLine(a); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x2095 // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208d // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x20a2 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__1' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 49 (0x31) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: dup IL_0013: ldloc.0 IL_0014: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0019: dup IL_001a: ldc.i4.1 IL_001b: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0020: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__1'() IL_0026: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002b: callvirt instance void [mscorlib]System.Action::Invoke() IL_0030: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable02() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; { Action action = () => Console.WriteLine(a + b); action(); } { Action _ = () => Console.WriteLine(a + b); } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2077 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x207f // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x207f // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__1' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 38 (0x26) .maxstack 8 .entrypoint IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: ldc.i4.0 IL_0007: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000c: dup IL_000d: ldc.i4.1 IL_000e: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0013: dup IL_0014: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_001a: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_001f: callvirt instance void [mscorlib]System.Action::Invoke() IL_0024: pop IL_0025: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable03() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); Action _ = () => Console.WriteLine(b); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2077 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x207f // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x2093 // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__1' } // end of class <>c__DisplayClass0_0 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 38 (0x26) .maxstack 8 .entrypoint IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: ldc.i4.0 IL_0007: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000c: dup IL_000d: ldc.i4.1 IL_000e: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0013: dup IL_0014: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_001a: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_001f: callvirt instance void [mscorlib]System.Action::Invoke() IL_0024: pop IL_0025: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable04() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; Action action = () => Console.WriteLine(a + b); action(); Action _ = () => Console.WriteLine(a); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2094 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x209c // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__1' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2094 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20a9 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 56 (0x38) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: dup IL_0013: ldloc.0 IL_0014: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0019: dup IL_001a: ldc.i4.1 IL_001b: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0020: dup IL_0021: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0027: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002c: callvirt instance void [mscorlib]System.Action::Invoke() IL_0031: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0036: pop IL_0037: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable05() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; { int c = 2; { int d = 3; Action action = () => Console.WriteLine(b + d); action(); Action _ = () => Console.WriteLine(a + c); } } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"4"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b .field public int32 c // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x20aa // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::c IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__1' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 d .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a2 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20be // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::d IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__0' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 70 (0x46) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0014: ldloc.0 IL_0015: ldc.i4.2 IL_0016: stfld int32 Program/'<>c__DisplayClass0_0'::c IL_001b: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0020: dup IL_0021: ldloc.0 IL_0022: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0027: dup IL_0028: ldc.i4.3 IL_0029: stfld int32 Program/'<>c__DisplayClass0_1'::d IL_002e: dup IL_002f: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__0'() IL_0035: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_003a: callvirt instance void [mscorlib]System.Action::Invoke() IL_003f: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0044: pop IL_0045: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable06() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; { int c = 2; Action action = () => Console.WriteLine(a + c); action(); Action x = () => Console.WriteLine(a + b + c); } Action y = () => Console.WriteLine(b); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"2"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2096 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x209e // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 c .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2096 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x20ab // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::c IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__1' .method assembly hidebysig instance void '<Main>b__2' () cil managed { // Method begins at RVA 0x20c4 // Code size 36 (0x24) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_000b: ldarg.0 IL_000c: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0011: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_0016: add IL_0017: ldarg.0 IL_0018: ldfld int32 Program/'<>c__DisplayClass0_1'::c IL_001d: add IL_001e: call void [mscorlib]System.Console::WriteLine(int32) IL_0023: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__2' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 58 (0x3a) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0014: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0019: dup IL_001a: ldloc.0 IL_001b: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0020: dup IL_0021: ldc.i4.2 IL_0022: stfld int32 Program/'<>c__DisplayClass0_1'::c IL_0027: dup IL_0028: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__1'() IL_002e: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0033: callvirt instance void [mscorlib]System.Action::Invoke() IL_0038: pop IL_0039: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable07() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; { int c = 2; Action action = () => Console.WriteLine(b + c); action(); } Action y = () => Console.WriteLine(a + b); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2094 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x209c // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 c .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2094 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x20b0 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass0_0'::b IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass0_1'::c IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__1' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 56 (0x38) .maxstack 3 .entrypoint .locals init ( [0] class Program/'<>c__DisplayClass0_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: stfld int32 Program/'<>c__DisplayClass0_0'::b IL_0014: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0019: dup IL_001a: ldloc.0 IL_001b: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0020: dup IL_0021: ldc.i4.2 IL_0022: stfld int32 Program/'<>c__DisplayClass0_1'::c IL_0027: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__1'() IL_002d: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0032: callvirt instance void [mscorlib]System.Action::Invoke() IL_0037: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void OptimizationDoesNotIncreaseClosuresReferencingVariable08() { var source = @"using System; public static class Program { public static void Main() { int a = 0; { int b = 1; { int c = 2; Action action = () => Console.WriteLine(b + c); action(); } Action y = () => Console.WriteLine(a); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi abstract sealed beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2082 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x208a // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public int32 c // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2082 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x2097 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass0_1'::c IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__1' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 49 (0x31) .maxstack 8 .entrypoint IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: ldc.i4.0 IL_0007: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_000c: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0011: dup IL_0012: ldc.i4.1 IL_0013: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0018: dup IL_0019: ldc.i4.2 IL_001a: stfld int32 Program/'<>c__DisplayClass0_1'::c IL_001f: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__1'() IL_0025: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002a: callvirt instance void [mscorlib]System.Action::Invoke() IL_002f: pop IL_0030: ret } // end of method Program::Main } // end of class Program"); } [Fact] public void DoNotMergeEnvironmentsInsideLocalFunctionToOutside() { var source = @"using System; using System.Collections.Generic; public class Program { public static void Main() { var actions = new List<Action>(); int a = 1; void M() { int b = 0; actions.Add(() => b += a); actions.Add(() => Console.WriteLine(b)); } M(); M(); actions[0](); actions[2](); actions[1](); actions[3](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1 1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> actions .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20c3 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>g__M|0' () cil managed { // Method begins at RVA 0x20cc // Code size 67 (0x43) .maxstack 3 .locals init ( [0] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000d: ldloc.0 IL_000e: ldc.i4.0 IL_000f: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0014: ldarg.0 IL_0015: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_001a: ldloc.0 IL_001b: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__1'() IL_0021: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0026: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_002b: ldarg.0 IL_002c: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0031: ldloc.0 IL_0032: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__2'() IL_0038: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_003d: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0042: ret } // end of method '<>c__DisplayClass0_0'::'<Main>g__M|0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20c3 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x211b // Code size 25 (0x19) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0007: ldarg.0 IL_0008: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000d: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0012: add IL_0013: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0018: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__1' .method assembly hidebysig instance void '<Main>b__2' () cil managed { // Method begins at RVA 0x2135 // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__2' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 103 (0x67) .maxstack 3 .entrypoint IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0010: dup IL_0011: ldc.i4.1 IL_0012: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_0017: dup IL_0018: callvirt instance void Program/'<>c__DisplayClass0_0'::'<Main>g__M|0'() IL_001d: dup IL_001e: callvirt instance void Program/'<>c__DisplayClass0_0'::'<Main>g__M|0'() IL_0023: dup IL_0024: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0029: ldc.i4.0 IL_002a: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_002f: callvirt instance void [mscorlib]System.Action::Invoke() IL_0034: dup IL_0035: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_003a: ldc.i4.2 IL_003b: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0040: callvirt instance void [mscorlib]System.Action::Invoke() IL_0045: dup IL_0046: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_004b: ldc.i4.1 IL_004c: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0051: callvirt instance void [mscorlib]System.Action::Invoke() IL_0056: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_005b: ldc.i4.3 IL_005c: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_0061: callvirt instance void [mscorlib]System.Action::Invoke() IL_0066: ret } // end of method Program::Main .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20c3 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void DoNotMergeEnvironmentsInsideLambdaToOutside() { var source = @"using System; using System.Collections.Generic; public class Program { public static void Main() { var actions = new List<Action>(); int a = 1; Action M = () => { int b = 0; actions.Add(() => b += a); actions.Add(() => Console.WriteLine(b)); }; M(); M(); actions[0](); actions[2](); actions[1](); actions[3](); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"1 1"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> actions .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20ce // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<Main>b__0' () cil managed { // Method begins at RVA 0x20d8 // Code size 67 (0x43) .maxstack 3 .locals init ( [0] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000d: ldloc.0 IL_000e: ldc.i4.0 IL_000f: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0014: ldarg.0 IL_0015: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_001a: ldloc.0 IL_001b: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__1'() IL_0021: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0026: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_002b: ldarg.0 IL_002c: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0031: ldloc.0 IL_0032: ldftn instance void Program/'<>c__DisplayClass0_1'::'<Main>b__2'() IL_0038: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_003d: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::Add(!0) IL_0042: ret } // end of method '<>c__DisplayClass0_0'::'<Main>b__0' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20ce // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance void '<Main>b__1' () cil managed { // Method begins at RVA 0x2127 // Code size 25 (0x19) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0007: ldarg.0 IL_0008: ldfld class Program/'<>c__DisplayClass0_0' Program/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000d: ldfld int32 Program/'<>c__DisplayClass0_0'::a IL_0012: add IL_0013: stfld int32 Program/'<>c__DisplayClass0_1'::b IL_0018: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__1' .method assembly hidebysig instance void '<Main>b__2' () cil managed { // Method begins at RVA 0x2141 // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_1'::b IL_0006: call void [mscorlib]System.Console::WriteLine(int32) IL_000b: ret } // end of method '<>c__DisplayClass0_1'::'<Main>b__2' } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 114 (0x72) .maxstack 3 .entrypoint IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::.ctor() IL_000b: stfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0010: dup IL_0011: ldc.i4.1 IL_0012: stfld int32 Program/'<>c__DisplayClass0_0'::a IL_0017: dup IL_0018: ldftn instance void Program/'<>c__DisplayClass0_0'::'<Main>b__0'() IL_001e: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0023: dup IL_0024: callvirt instance void [mscorlib]System.Action::Invoke() IL_0029: callvirt instance void [mscorlib]System.Action::Invoke() IL_002e: dup IL_002f: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0034: ldc.i4.0 IL_0035: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_003a: callvirt instance void [mscorlib]System.Action::Invoke() IL_003f: dup IL_0040: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0045: ldc.i4.2 IL_0046: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_004b: callvirt instance void [mscorlib]System.Action::Invoke() IL_0050: dup IL_0051: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0056: ldc.i4.1 IL_0057: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_005c: callvirt instance void [mscorlib]System.Action::Invoke() IL_0061: ldfld class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action> Program/'<>c__DisplayClass0_0'::actions IL_0066: ldc.i4.3 IL_0067: callvirt instance !0 class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>::get_Item(int32) IL_006c: callvirt instance void [mscorlib]System.Action::Invoke() IL_0071: ret } // end of method Program::Main .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20ce // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void LocalMethod01() { var source = @"using System; public class Program { public static void Main() { M()(); } public static Action M() { int a = 1; { int b = 2; void M1() { Console.WriteLine(a + b); } { int c = 3; void M2() { M1(); Console.WriteLine(c); } return M2; } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3 3"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_0'::.ctor .method assembly hidebysig instance void '<M>g__M1|0' () cil managed { // Method begins at RVA 0x20a3 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass1_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass1_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass1_0'::'<M>g__M1|0' } // end of class <>c__DisplayClass1_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 c .field public class Program/'<>c__DisplayClass1_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_1'::.ctor .method assembly hidebysig instance void '<M>g__M2|1' () cil managed { // Method begins at RVA 0x20b7 // Code size 23 (0x17) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass1_0' Program/'<>c__DisplayClass1_1'::'CS$<>8__locals1' IL_0006: callvirt instance void Program/'<>c__DisplayClass1_0'::'<M>g__M1|0'() IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass1_1'::c IL_0011: call void [mscorlib]System.Console::WriteLine(int32) IL_0016: ret } // end of method '<>c__DisplayClass1_1'::'<M>g__M2|1' } // end of class <>c__DisplayClass1_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: call class [mscorlib]System.Action Program::M() IL_0005: callvirt instance void [mscorlib]System.Action::Invoke() IL_000a: ret } // end of method Program::Main .method public hidebysig static class [mscorlib]System.Action M () cil managed { // Method begins at RVA 0x205c // Code size 51 (0x33) .maxstack 3 .locals init ( [0] class Program/'<>c__DisplayClass1_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass1_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: stfld int32 Program/'<>c__DisplayClass1_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.2 IL_000f: stfld int32 Program/'<>c__DisplayClass1_0'::b IL_0014: newobj instance void Program/'<>c__DisplayClass1_1'::.ctor() IL_0019: dup IL_001a: ldloc.0 IL_001b: stfld class Program/'<>c__DisplayClass1_0' Program/'<>c__DisplayClass1_1'::'CS$<>8__locals1' IL_0020: dup IL_0021: ldc.i4.3 IL_0022: stfld int32 Program/'<>c__DisplayClass1_1'::c IL_0027: ldftn instance void Program/'<>c__DisplayClass1_1'::'<M>g__M2|1'() IL_002d: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0032: ret } // end of method Program::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void LocalMethod02() { var source = @"using System; public class Program { public static void Main() { M()(); } public static Action M() { int a = 1; { target: int b = 2; void M1() { Console.WriteLine(a + b); } { int c = 3; void M2() { M1(); Console.WriteLine(c); } return M2; goto target; } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3 3"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a .field public int32 b // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_0'::.ctor .method assembly hidebysig instance void '<M>g__M1|0' () cil managed { // Method begins at RVA 0x20a3 // Code size 19 (0x13) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass1_0'::a IL_0006: ldarg.0 IL_0007: ldfld int32 Program/'<>c__DisplayClass1_0'::b IL_000c: add IL_000d: call void [mscorlib]System.Console::WriteLine(int32) IL_0012: ret } // end of method '<>c__DisplayClass1_0'::'<M>g__M1|0' } // end of class <>c__DisplayClass1_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 c .field public class Program/'<>c__DisplayClass1_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_1'::.ctor .method assembly hidebysig instance void '<M>g__M2|1' () cil managed { // Method begins at RVA 0x20b7 // Code size 23 (0x17) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass1_0' Program/'<>c__DisplayClass1_1'::'CS$<>8__locals1' IL_0006: callvirt instance void Program/'<>c__DisplayClass1_0'::'<M>g__M1|0'() IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass1_1'::c IL_0011: call void [mscorlib]System.Console::WriteLine(int32) IL_0016: ret } // end of method '<>c__DisplayClass1_1'::'<M>g__M2|1' } // end of class <>c__DisplayClass1_1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: call class [mscorlib]System.Action Program::M() IL_0005: callvirt instance void [mscorlib]System.Action::Invoke() IL_000a: ret } // end of method Program::Main .method public hidebysig static class [mscorlib]System.Action M () cil managed { // Method begins at RVA 0x205c // Code size 51 (0x33) .maxstack 3 .locals init ( [0] class Program/'<>c__DisplayClass1_0' ) IL_0000: newobj instance void Program/'<>c__DisplayClass1_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: stfld int32 Program/'<>c__DisplayClass1_0'::a IL_000d: ldloc.0 IL_000e: ldc.i4.2 IL_000f: stfld int32 Program/'<>c__DisplayClass1_0'::b IL_0014: newobj instance void Program/'<>c__DisplayClass1_1'::.ctor() IL_0019: dup IL_001a: ldloc.0 IL_001b: stfld class Program/'<>c__DisplayClass1_0' Program/'<>c__DisplayClass1_1'::'CS$<>8__locals1' IL_0020: dup IL_0021: ldc.i4.3 IL_0022: stfld int32 Program/'<>c__DisplayClass1_1'::c IL_0027: ldftn instance void Program/'<>c__DisplayClass1_1'::'<M>g__M2|1'() IL_002d: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0032: ret } // end of method Program::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x209b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void LocalMethod03() { var source = @"using System; public class Program { public static void Main() { M()(); } public static Action M() { int a = 1; target: { int b = 2; void M1() { Console.WriteLine(a + b); } { int c = 3; void M2() { M1(); Console.WriteLine(c); } return M2; goto target; } } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"3 3"); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a8 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_0'::.ctor } // end of class <>c__DisplayClass1_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public class Program/'<>c__DisplayClass1_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a8 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_1'::.ctor .method assembly hidebysig instance void '<M>g__M1|0' () cil managed { // Method begins at RVA 0x20b0 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass1_0' Program/'<>c__DisplayClass1_1'::'CS$<>8__locals1' IL_0006: ldfld int32 Program/'<>c__DisplayClass1_0'::a IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass1_1'::b IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method '<>c__DisplayClass1_1'::'<M>g__M1|0' } // end of class <>c__DisplayClass1_1 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass1_2' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 c .field public class Program/'<>c__DisplayClass1_1' 'CS$<>8__locals2' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a8 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass1_2'::.ctor .method assembly hidebysig instance void '<M>g__M2|1' () cil managed { // Method begins at RVA 0x20c9 // Code size 23 (0x17) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass1_1' Program/'<>c__DisplayClass1_2'::'CS$<>8__locals2' IL_0006: callvirt instance void Program/'<>c__DisplayClass1_1'::'<M>g__M1|0'() IL_000b: ldarg.0 IL_000c: ldfld int32 Program/'<>c__DisplayClass1_2'::c IL_0011: call void [mscorlib]System.Console::WriteLine(int32) IL_0016: ret } // end of method '<>c__DisplayClass1_2'::'<M>g__M2|1' } // end of class <>c__DisplayClass1_2 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: call class [mscorlib]System.Action Program::M() IL_0005: callvirt instance void [mscorlib]System.Action::Invoke() IL_000a: ret } // end of method Program::Main .method public hidebysig static class [mscorlib]System.Action M () cil managed { // Method begins at RVA 0x205c // Code size 64 (0x40) .maxstack 3 .locals init ( [0] class Program/'<>c__DisplayClass1_0', [1] class Program/'<>c__DisplayClass1_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass1_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: stfld int32 Program/'<>c__DisplayClass1_0'::a IL_000d: newobj instance void Program/'<>c__DisplayClass1_1'::.ctor() IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: ldloc.0 IL_0015: stfld class Program/'<>c__DisplayClass1_0' Program/'<>c__DisplayClass1_1'::'CS$<>8__locals1' IL_001a: ldloc.1 IL_001b: ldc.i4.2 IL_001c: stfld int32 Program/'<>c__DisplayClass1_1'::b IL_0021: newobj instance void Program/'<>c__DisplayClass1_2'::.ctor() IL_0026: dup IL_0027: ldloc.1 IL_0028: stfld class Program/'<>c__DisplayClass1_1' Program/'<>c__DisplayClass1_2'::'CS$<>8__locals2' IL_002d: dup IL_002e: ldc.i4.3 IL_002f: stfld int32 Program/'<>c__DisplayClass1_2'::c IL_0034: ldftn instance void Program/'<>c__DisplayClass1_2'::'<M>g__M2|1'() IL_003a: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_003f: ret } // end of method Program::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a8 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void LocalMethod04() { var source = @"using System; public class Program { public void M() { int x = 0; { int y = 0; void M() => y++; { Action a = () => x++; } } } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2072 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance void '<M>b__1' () cil managed { // Method begins at RVA 0x209c // Code size 17 (0x11) .maxstack 3 .locals init ( [0] int32 ) IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::x IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: add IL_000b: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_0010: ret } // end of method '<>c__DisplayClass0_0'::'<M>b__1' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 y } // end of class <>c__DisplayClass0_1 // Methods .method public hidebysig instance void M () cil managed { // Method begins at RVA 0x2050 // Code size 22 (0x16) .maxstack 3 .locals init ( [0] valuetype Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: dup IL_0006: ldc.i4.0 IL_0007: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_000c: ldloca.s 0 IL_000e: ldc.i4.0 IL_000f: stfld int32 Program/'<>c__DisplayClass0_1'::y IL_0014: pop IL_0015: ret } // end of method Program::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2072 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor .method assembly hidebysig static void '<M>g__M|0_0' ( valuetype Program/'<>c__DisplayClass0_1'& '' ) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x207c // Code size 17 (0x11) .maxstack 3 .locals init ( [0] int32 ) IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_1'::y IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: add IL_000b: stfld int32 Program/'<>c__DisplayClass0_1'::y IL_0010: ret } // end of method Program::'<M>g__M|0_0' } // end of class Program"); } [Fact] public void LocalMethod05() { var source = @"using System; public class Program { public Func<int> M() { int x = 0; { int y = 0; int M() => y++; { Func<int> a = () => x++; { int M1() => M() + a(); return M1; } } } } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "Program", @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 x // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance int32 '<M>b__1' () cil managed { // Method begins at RVA 0x20a8 // Code size 18 (0x12) .maxstack 3 .locals init ( [0] int32 ) IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_0'::x IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: add IL_000b: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_0010: ldloc.0 IL_0011: ret } // end of method '<>c__DisplayClass0_0'::'<M>b__1' } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 y // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor .method assembly hidebysig instance int32 '<M>g__M|0' () cil managed { // Method begins at RVA 0x20c8 // Code size 18 (0x12) .maxstack 3 .locals init ( [0] int32 ) IL_0000: ldarg.0 IL_0001: ldfld int32 Program/'<>c__DisplayClass0_1'::y IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: add IL_000b: stfld int32 Program/'<>c__DisplayClass0_1'::y IL_0010: ldloc.0 IL_0011: ret } // end of method '<>c__DisplayClass0_1'::'<M>g__M|0' } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_2' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public class [mscorlib]System.Func`1<int32> a .field public class Program/'<>c__DisplayClass0_1' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_2'::.ctor .method assembly hidebysig instance int32 '<M>g__M1|2' () cil managed { // Method begins at RVA 0x20e6 // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals1' IL_0006: callvirt instance int32 Program/'<>c__DisplayClass0_1'::'<M>g__M|0'() IL_000b: ldarg.0 IL_000c: ldfld class [mscorlib]System.Func`1<int32> Program/'<>c__DisplayClass0_2'::a IL_0011: callvirt instance !0 class [mscorlib]System.Func`1<int32>::Invoke() IL_0016: add IL_0017: ret } // end of method '<>c__DisplayClass0_2'::'<M>g__M1|2' } // end of class <>c__DisplayClass0_2 // Methods .method public hidebysig instance class [mscorlib]System.Func`1<int32> M () cil managed { // Method begins at RVA 0x2050 // Code size 68 (0x44) .maxstack 4 .locals init ( [0] class Program/'<>c__DisplayClass0_0', [1] class Program/'<>c__DisplayClass0_1' ) IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor() IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::x IL_000d: newobj instance void Program/'<>c__DisplayClass0_1'::.ctor() IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: ldc.i4.0 IL_0015: stfld int32 Program/'<>c__DisplayClass0_1'::y IL_001a: newobj instance void Program/'<>c__DisplayClass0_2'::.ctor() IL_001f: dup IL_0020: ldloc.1 IL_0021: stfld class Program/'<>c__DisplayClass0_1' Program/'<>c__DisplayClass0_2'::'CS$<>8__locals1' IL_0026: dup IL_0027: ldloc.0 IL_0028: ldftn instance int32 Program/'<>c__DisplayClass0_0'::'<M>b__1'() IL_002e: newobj instance void class [mscorlib]System.Func`1<int32>::.ctor(object, native int) IL_0033: stfld class [mscorlib]System.Func`1<int32> Program/'<>c__DisplayClass0_2'::a IL_0038: ldftn instance int32 Program/'<>c__DisplayClass0_2'::'<M>g__M1|2'() IL_003e: newobj instance void class [mscorlib]System.Func`1<int32>::.ctor(object, native int) IL_0043: ret } // end of method Program::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a0 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class Program"); } [Fact] public void YieldReturnCorrectDisplayClasseAreCreated() { var source = @"using System; using System.Collections.Generic; public class C { public IEnumerable<int> M() { int a = 1; yield return 1; while(true) { yield return 2; int b = 2; yield return 3; { yield return 4; int c = 3; target: yield return 5; { yield return 6; int d = 4; goto target; yield return 7; Action e = () => Console.WriteLine(a + b + c + d); } } } } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "C", @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2059 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public int32 c .field public class C/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2059 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_2' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 d .field public class C/'<>c__DisplayClass0_1' 'CS$<>8__locals2' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2059 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_2'::.ctor .method assembly hidebysig instance void '<M>b__0' () cil managed { // Method begins at RVA 0x2061 // Code size 53 (0x35) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0006: ldfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000b: ldfld int32 C/'<>c__DisplayClass0_0'::a IL_0010: ldarg.0 IL_0011: ldfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0016: ldfld int32 C/'<>c__DisplayClass0_1'::b IL_001b: add IL_001c: ldarg.0 IL_001d: ldfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0022: ldfld int32 C/'<>c__DisplayClass0_1'::c IL_0027: add IL_0028: ldarg.0 IL_0029: ldfld int32 C/'<>c__DisplayClass0_2'::d IL_002e: add IL_002f: call void [mscorlib]System.Console::WriteLine(int32) IL_0034: ret } // end of method '<>c__DisplayClass0_2'::'<M>b__0' } // end of class <>c__DisplayClass0_2 .class nested private auto ansi sealed beforefieldinit '<M>d__0' extends [mscorlib]System.Object implements class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>, [mscorlib]System.Collections.IEnumerable, class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>, [mscorlib]System.IDisposable, [mscorlib]System.Collections.IEnumerator { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field private int32 '<>1__state' .field private int32 '<>2__current' .field private int32 '<>l__initialThreadId' .field private class C/'<>c__DisplayClass0_0' '<>8__1' .field private class C/'<>c__DisplayClass0_1' '<>8__2' .field private class C/'<>c__DisplayClass0_2' '<>8__3' // Methods .method public hidebysig specialname rtspecialname instance void .ctor ( int32 '<>1__state' ) cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2097 // Code size 25 (0x19) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld int32 C/'<M>d__0'::'<>1__state' IL_000d: ldarg.0 IL_000e: call int32 [mscorlib]System.Environment::get_CurrentManagedThreadId() IL_0013: stfld int32 C/'<M>d__0'::'<>l__initialThreadId' IL_0018: ret } // end of method '<M>d__0'::.ctor .method private final hidebysig newslot virtual instance void System.IDisposable.Dispose () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance void [mscorlib]System.IDisposable::Dispose() // Method begins at RVA 0x20b1 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method '<M>d__0'::System.IDisposable.Dispose .method private final hidebysig newslot virtual instance bool MoveNext () cil managed { .override method instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() // Method begins at RVA 0x20b4 // Code size 342 (0x156) .maxstack 2 .locals init ( [0] int32 ) IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<M>d__0'::'<>1__state' IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: switch (IL_002f, IL_005d, IL_0090, IL_00b3, IL_00ca, IL_00ed, IL_0120, IL_0135) IL_002d: ldc.i4.0 IL_002e: ret IL_002f: ldarg.0 IL_0030: ldc.i4.m1 IL_0031: stfld int32 C/'<M>d__0'::'<>1__state' IL_0036: ldarg.0 IL_0037: newobj instance void C/'<>c__DisplayClass0_0'::.ctor() IL_003c: stfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_0041: ldarg.0 IL_0042: ldfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_0047: ldc.i4.1 IL_0048: stfld int32 C/'<>c__DisplayClass0_0'::a IL_004d: ldarg.0 IL_004e: ldc.i4.1 IL_004f: stfld int32 C/'<M>d__0'::'<>2__current' IL_0054: ldarg.0 IL_0055: ldc.i4.1 IL_0056: stfld int32 C/'<M>d__0'::'<>1__state' IL_005b: ldc.i4.1 IL_005c: ret IL_005d: ldarg.0 IL_005e: ldc.i4.m1 IL_005f: stfld int32 C/'<M>d__0'::'<>1__state' IL_0064: ldarg.0 IL_0065: newobj instance void C/'<>c__DisplayClass0_1'::.ctor() IL_006a: stfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_006f: ldarg.0 IL_0070: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_0075: ldarg.0 IL_0076: ldfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_007b: stfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_0080: ldarg.0 IL_0081: ldc.i4.2 IL_0082: stfld int32 C/'<M>d__0'::'<>2__current' IL_0087: ldarg.0 IL_0088: ldc.i4.2 IL_0089: stfld int32 C/'<M>d__0'::'<>1__state' IL_008e: ldc.i4.1 IL_008f: ret IL_0090: ldarg.0 IL_0091: ldc.i4.m1 IL_0092: stfld int32 C/'<M>d__0'::'<>1__state' IL_0097: ldarg.0 IL_0098: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_009d: ldc.i4.2 IL_009e: stfld int32 C/'<>c__DisplayClass0_1'::b IL_00a3: ldarg.0 IL_00a4: ldc.i4.3 IL_00a5: stfld int32 C/'<M>d__0'::'<>2__current' IL_00aa: ldarg.0 IL_00ab: ldc.i4.3 IL_00ac: stfld int32 C/'<M>d__0'::'<>1__state' IL_00b1: ldc.i4.1 IL_00b2: ret IL_00b3: ldarg.0 IL_00b4: ldc.i4.m1 IL_00b5: stfld int32 C/'<M>d__0'::'<>1__state' IL_00ba: ldarg.0 IL_00bb: ldc.i4.4 IL_00bc: stfld int32 C/'<M>d__0'::'<>2__current' IL_00c1: ldarg.0 IL_00c2: ldc.i4.4 IL_00c3: stfld int32 C/'<M>d__0'::'<>1__state' IL_00c8: ldc.i4.1 IL_00c9: ret IL_00ca: ldarg.0 IL_00cb: ldc.i4.m1 IL_00cc: stfld int32 C/'<M>d__0'::'<>1__state' IL_00d1: ldarg.0 IL_00d2: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_00d7: ldc.i4.3 IL_00d8: stfld int32 C/'<>c__DisplayClass0_1'::c IL_00dd: ldarg.0 IL_00de: ldc.i4.5 IL_00df: stfld int32 C/'<M>d__0'::'<>2__current' IL_00e4: ldarg.0 IL_00e5: ldc.i4.5 IL_00e6: stfld int32 C/'<M>d__0'::'<>1__state' IL_00eb: ldc.i4.1 IL_00ec: ret IL_00ed: ldarg.0 IL_00ee: ldc.i4.m1 IL_00ef: stfld int32 C/'<M>d__0'::'<>1__state' IL_00f4: ldarg.0 IL_00f5: newobj instance void C/'<>c__DisplayClass0_2'::.ctor() IL_00fa: stfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_00ff: ldarg.0 IL_0100: ldfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_0105: ldarg.0 IL_0106: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_010b: stfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0110: ldarg.0 IL_0111: ldc.i4.6 IL_0112: stfld int32 C/'<M>d__0'::'<>2__current' IL_0117: ldarg.0 IL_0118: ldc.i4.6 IL_0119: stfld int32 C/'<M>d__0'::'<>1__state' IL_011e: ldc.i4.1 IL_011f: ret IL_0120: ldarg.0 IL_0121: ldc.i4.m1 IL_0122: stfld int32 C/'<M>d__0'::'<>1__state' IL_0127: ldarg.0 IL_0128: ldfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_012d: ldc.i4.4 IL_012e: stfld int32 C/'<>c__DisplayClass0_2'::d IL_0133: br.s IL_00dd IL_0135: ldarg.0 IL_0136: ldc.i4.m1 IL_0137: stfld int32 C/'<M>d__0'::'<>1__state' IL_013c: ldarg.0 IL_013d: ldfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_0142: pop IL_0143: ldarg.0 IL_0144: ldnull IL_0145: stfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_014a: ldarg.0 IL_014b: ldnull IL_014c: stfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_0151: br IL_0064 } // end of method '<M>d__0'::MoveNext .method private final hidebysig specialname newslot virtual instance int32 'System.Collections.Generic.IEnumerator<System.Int32>.get_Current' () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance !0 class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>::get_Current() // Method begins at RVA 0x2216 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<M>d__0'::'<>2__current' IL_0006: ret } // end of method '<M>d__0'::'System.Collections.Generic.IEnumerator<System.Int32>.get_Current' .method private final hidebysig newslot virtual instance void System.Collections.IEnumerator.Reset () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance void [mscorlib]System.Collections.IEnumerator::Reset() // Method begins at RVA 0x221e // Code size 6 (0x6) .maxstack 8 IL_0000: newobj instance void [mscorlib]System.NotSupportedException::.ctor() IL_0005: throw } // end of method '<M>d__0'::System.Collections.IEnumerator.Reset .method private final hidebysig specialname newslot virtual instance object System.Collections.IEnumerator.get_Current () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance object [mscorlib]System.Collections.IEnumerator::get_Current() // Method begins at RVA 0x2225 // Code size 12 (0xc) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<M>d__0'::'<>2__current' IL_0006: box [mscorlib]System.Int32 IL_000b: ret } // end of method '<M>d__0'::System.Collections.IEnumerator.get_Current .method private final hidebysig newslot virtual instance class [mscorlib]System.Collections.Generic.IEnumerator`1<int32> 'System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator' () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance class [mscorlib]System.Collections.Generic.IEnumerator`1<!0> class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>::GetEnumerator() // Method begins at RVA 0x2234 // Code size 43 (0x2b) .maxstack 2 .locals init ( [0] class C/'<M>d__0' ) IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<M>d__0'::'<>1__state' IL_0006: ldc.i4.s -2 IL_0008: bne.un.s IL_0022 IL_000a: ldarg.0 IL_000b: ldfld int32 C/'<M>d__0'::'<>l__initialThreadId' IL_0010: call int32 [mscorlib]System.Environment::get_CurrentManagedThreadId() IL_0015: bne.un.s IL_0022 IL_0017: ldarg.0 IL_0018: ldc.i4.0 IL_0019: stfld int32 C/'<M>d__0'::'<>1__state' IL_001e: ldarg.0 IL_001f: stloc.0 IL_0020: br.s IL_0029 IL_0022: ldc.i4.0 IL_0023: newobj instance void C/'<M>d__0'::.ctor(int32) IL_0028: stloc.0 IL_0029: ldloc.0 IL_002a: ret } // end of method '<M>d__0'::'System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator' .method private final hidebysig newslot virtual instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Collections.IEnumerable::GetEnumerator() // Method begins at RVA 0x226b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance class [mscorlib]System.Collections.Generic.IEnumerator`1<int32> C/'<M>d__0'::'System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator'() IL_0006: ret } // end of method '<M>d__0'::System.Collections.IEnumerable.GetEnumerator // Properties .property instance int32 'System.Collections.Generic.IEnumerator<System.Int32>.Current'() { .get instance int32 C/'<M>d__0'::'System.Collections.Generic.IEnumerator<System.Int32>.get_Current'() } .property instance object System.Collections.IEnumerator.Current() { .get instance object C/'<M>d__0'::System.Collections.IEnumerator.get_Current() } } // end of class <M>d__0 // Methods .method public hidebysig instance class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> M () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.IteratorStateMachineAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 09 43 2b 3c 4d 3e 64 5f 5f 30 00 00 ) // Method begins at RVA 0x2050 // Code size 8 (0x8) .maxstack 8 IL_0000: ldc.i4.s -2 IL_0002: newobj instance void C/'<M>d__0'::.ctor(int32) IL_0007: ret } // end of method C::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2059 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor } // end of class C"); } [Fact] public void AsyncAwaitCorrectDisplayClasseAreCreated() { var source = @"using System; using System.Threading.Tasks; public class C { public async Task M() { int a = 1; await Task.Delay(0); while(true) { await Task.Delay(0); int b = 2; await Task.Delay(0); { await Task.Delay(0); int c = 3; target: await Task.Delay(0); { await Task.Delay(0); int d = 4; goto target; await Task.Delay(0); Action e = () => Console.WriteLine(a + b + c + d); } } } } }"; var compilation = CompileAndVerify(source); VerifyTypeIL(compilation, "C", @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 a // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_0'::.ctor } // end of class <>c__DisplayClass0_0 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_1' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 b .field public int32 c .field public class C/'<>c__DisplayClass0_0' 'CS$<>8__locals1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_1'::.ctor } // end of class <>c__DisplayClass0_1 .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_2' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 d .field public class C/'<>c__DisplayClass0_1' 'CS$<>8__locals2' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method '<>c__DisplayClass0_2'::.ctor .method assembly hidebysig instance void '<M>b__0' () cil managed { // Method begins at RVA 0x2093 // Code size 53 (0x35) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0006: ldfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_000b: ldfld int32 C/'<>c__DisplayClass0_0'::a IL_0010: ldarg.0 IL_0011: ldfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0016: ldfld int32 C/'<>c__DisplayClass0_1'::b IL_001b: add IL_001c: ldarg.0 IL_001d: ldfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0022: ldfld int32 C/'<>c__DisplayClass0_1'::c IL_0027: add IL_0028: ldarg.0 IL_0029: ldfld int32 C/'<>c__DisplayClass0_2'::d IL_002e: add IL_002f: call void [mscorlib]System.Console::WriteLine(int32) IL_0034: ret } // end of method '<>c__DisplayClass0_2'::'<M>b__0' } // end of class <>c__DisplayClass0_2 .class nested private auto ansi sealed beforefieldinit '<M>d__0' extends [mscorlib]System.ValueType implements [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 '<>1__state' .field public valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder '<>t__builder' .field private class C/'<>c__DisplayClass0_0' '<>8__1' .field private class C/'<>c__DisplayClass0_1' '<>8__2' .field private class C/'<>c__DisplayClass0_2' '<>8__3' .field private valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter '<>u__1' // Methods .method private final hidebysig newslot virtual instance void MoveNext () cil managed { .override method instance void [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine::MoveNext() // Method begins at RVA 0x20cc // Code size 792 (0x318) .maxstack 3 .locals init ( [0] int32, [1] valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, [2] class [mscorlib]System.Exception ) IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<M>d__0'::'<>1__state' IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: switch (IL_0078, IL_00ef, IL_0156, IL_01b1, IL_0218, IL_028f, IL_02c3) IL_0029: ldarg.0 IL_002a: newobj instance void C/'<>c__DisplayClass0_0'::.ctor() IL_002f: stfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_0034: ldarg.0 IL_0035: ldfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_003a: ldc.i4.1 IL_003b: stfld int32 C/'<>c__DisplayClass0_0'::a IL_0040: ldc.i4.0 IL_0041: call class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Threading.Tasks.Task::Delay(int32) IL_0046: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter [mscorlib]System.Threading.Tasks.Task::GetAwaiter() IL_004b: stloc.1 IL_004c: ldloca.s 1 IL_004e: call instance bool [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::get_IsCompleted() IL_0053: brtrue.s IL_0094 IL_0055: ldarg.0 IL_0056: ldc.i4.0 IL_0057: dup IL_0058: stloc.0 IL_0059: stfld int32 C/'<M>d__0'::'<>1__state' IL_005e: ldarg.0 IL_005f: ldloc.1 IL_0060: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0065: ldarg.0 IL_0066: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_006b: ldloca.s 1 IL_006d: ldarg.0 IL_006e: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, valuetype C/'<M>d__0'>(!!0&, !!1&) IL_0073: leave IL_0317 IL_0078: ldarg.0 IL_0079: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_007e: stloc.1 IL_007f: ldarg.0 IL_0080: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0085: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_008b: ldarg.0 IL_008c: ldc.i4.m1 IL_008d: dup IL_008e: stloc.0 IL_008f: stfld int32 C/'<M>d__0'::'<>1__state' IL_0094: ldloca.s 1 IL_0096: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_009b: ldarg.0 IL_009c: newobj instance void C/'<>c__DisplayClass0_1'::.ctor() IL_00a1: stfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_00a6: ldarg.0 IL_00a7: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_00ac: ldarg.0 IL_00ad: ldfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_00b2: stfld class C/'<>c__DisplayClass0_0' C/'<>c__DisplayClass0_1'::'CS$<>8__locals1' IL_00b7: ldc.i4.0 IL_00b8: call class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Threading.Tasks.Task::Delay(int32) IL_00bd: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter [mscorlib]System.Threading.Tasks.Task::GetAwaiter() IL_00c2: stloc.1 IL_00c3: ldloca.s 1 IL_00c5: call instance bool [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::get_IsCompleted() IL_00ca: brtrue.s IL_010b IL_00cc: ldarg.0 IL_00cd: ldc.i4.1 IL_00ce: dup IL_00cf: stloc.0 IL_00d0: stfld int32 C/'<M>d__0'::'<>1__state' IL_00d5: ldarg.0 IL_00d6: ldloc.1 IL_00d7: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_00dc: ldarg.0 IL_00dd: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_00e2: ldloca.s 1 IL_00e4: ldarg.0 IL_00e5: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, valuetype C/'<M>d__0'>(!!0&, !!1&) IL_00ea: leave IL_0317 IL_00ef: ldarg.0 IL_00f0: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_00f5: stloc.1 IL_00f6: ldarg.0 IL_00f7: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_00fc: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_0102: ldarg.0 IL_0103: ldc.i4.m1 IL_0104: dup IL_0105: stloc.0 IL_0106: stfld int32 C/'<M>d__0'::'<>1__state' IL_010b: ldloca.s 1 IL_010d: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_0112: ldarg.0 IL_0113: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_0118: ldc.i4.2 IL_0119: stfld int32 C/'<>c__DisplayClass0_1'::b IL_011e: ldc.i4.0 IL_011f: call class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Threading.Tasks.Task::Delay(int32) IL_0124: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter [mscorlib]System.Threading.Tasks.Task::GetAwaiter() IL_0129: stloc.1 IL_012a: ldloca.s 1 IL_012c: call instance bool [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::get_IsCompleted() IL_0131: brtrue.s IL_0172 IL_0133: ldarg.0 IL_0134: ldc.i4.2 IL_0135: dup IL_0136: stloc.0 IL_0137: stfld int32 C/'<M>d__0'::'<>1__state' IL_013c: ldarg.0 IL_013d: ldloc.1 IL_013e: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0143: ldarg.0 IL_0144: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_0149: ldloca.s 1 IL_014b: ldarg.0 IL_014c: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, valuetype C/'<M>d__0'>(!!0&, !!1&) IL_0151: leave IL_0317 IL_0156: ldarg.0 IL_0157: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_015c: stloc.1 IL_015d: ldarg.0 IL_015e: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0163: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_0169: ldarg.0 IL_016a: ldc.i4.m1 IL_016b: dup IL_016c: stloc.0 IL_016d: stfld int32 C/'<M>d__0'::'<>1__state' IL_0172: ldloca.s 1 IL_0174: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_0179: ldc.i4.0 IL_017a: call class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Threading.Tasks.Task::Delay(int32) IL_017f: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter [mscorlib]System.Threading.Tasks.Task::GetAwaiter() IL_0184: stloc.1 IL_0185: ldloca.s 1 IL_0187: call instance bool [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::get_IsCompleted() IL_018c: brtrue.s IL_01cd IL_018e: ldarg.0 IL_018f: ldc.i4.3 IL_0190: dup IL_0191: stloc.0 IL_0192: stfld int32 C/'<M>d__0'::'<>1__state' IL_0197: ldarg.0 IL_0198: ldloc.1 IL_0199: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_019e: ldarg.0 IL_019f: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_01a4: ldloca.s 1 IL_01a6: ldarg.0 IL_01a7: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, valuetype C/'<M>d__0'>(!!0&, !!1&) IL_01ac: leave IL_0317 IL_01b1: ldarg.0 IL_01b2: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_01b7: stloc.1 IL_01b8: ldarg.0 IL_01b9: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_01be: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_01c4: ldarg.0 IL_01c5: ldc.i4.m1 IL_01c6: dup IL_01c7: stloc.0 IL_01c8: stfld int32 C/'<M>d__0'::'<>1__state' IL_01cd: ldloca.s 1 IL_01cf: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_01d4: ldarg.0 IL_01d5: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_01da: ldc.i4.3 IL_01db: stfld int32 C/'<>c__DisplayClass0_1'::c IL_01e0: ldc.i4.0 IL_01e1: call class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Threading.Tasks.Task::Delay(int32) IL_01e6: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter [mscorlib]System.Threading.Tasks.Task::GetAwaiter() IL_01eb: stloc.1 IL_01ec: ldloca.s 1 IL_01ee: call instance bool [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::get_IsCompleted() IL_01f3: brtrue.s IL_0234 IL_01f5: ldarg.0 IL_01f6: ldc.i4.4 IL_01f7: dup IL_01f8: stloc.0 IL_01f9: stfld int32 C/'<M>d__0'::'<>1__state' IL_01fe: ldarg.0 IL_01ff: ldloc.1 IL_0200: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0205: ldarg.0 IL_0206: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_020b: ldloca.s 1 IL_020d: ldarg.0 IL_020e: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, valuetype C/'<M>d__0'>(!!0&, !!1&) IL_0213: leave IL_0317 IL_0218: ldarg.0 IL_0219: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_021e: stloc.1 IL_021f: ldarg.0 IL_0220: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0225: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_022b: ldarg.0 IL_022c: ldc.i4.m1 IL_022d: dup IL_022e: stloc.0 IL_022f: stfld int32 C/'<M>d__0'::'<>1__state' IL_0234: ldloca.s 1 IL_0236: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_023b: ldarg.0 IL_023c: newobj instance void C/'<>c__DisplayClass0_2'::.ctor() IL_0241: stfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_0246: ldarg.0 IL_0247: ldfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_024c: ldarg.0 IL_024d: ldfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_0252: stfld class C/'<>c__DisplayClass0_1' C/'<>c__DisplayClass0_2'::'CS$<>8__locals2' IL_0257: ldc.i4.0 IL_0258: call class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Threading.Tasks.Task::Delay(int32) IL_025d: callvirt instance valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter [mscorlib]System.Threading.Tasks.Task::GetAwaiter() IL_0262: stloc.1 IL_0263: ldloca.s 1 IL_0265: call instance bool [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::get_IsCompleted() IL_026a: brtrue.s IL_02ab IL_026c: ldarg.0 IL_026d: ldc.i4.5 IL_026e: dup IL_026f: stloc.0 IL_0270: stfld int32 C/'<M>d__0'::'<>1__state' IL_0275: ldarg.0 IL_0276: ldloc.1 IL_0277: stfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_027c: ldarg.0 IL_027d: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_0282: ldloca.s 1 IL_0284: ldarg.0 IL_0285: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::AwaitUnsafeOnCompleted<valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter, valuetype C/'<M>d__0'>(!!0&, !!1&) IL_028a: leave IL_0317 IL_028f: ldarg.0 IL_0290: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_0295: stloc.1 IL_0296: ldarg.0 IL_0297: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_029c: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_02a2: ldarg.0 IL_02a3: ldc.i4.m1 IL_02a4: dup IL_02a5: stloc.0 IL_02a6: stfld int32 C/'<M>d__0'::'<>1__state' IL_02ab: ldloca.s 1 IL_02ad: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_02b2: ldarg.0 IL_02b3: ldfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_02b8: ldc.i4.4 IL_02b9: stfld int32 C/'<>c__DisplayClass0_2'::d IL_02be: br IL_01e0 IL_02c3: ldarg.0 IL_02c4: ldfld valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_02c9: stloc.1 IL_02ca: ldarg.0 IL_02cb: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.TaskAwaiter C/'<M>d__0'::'<>u__1' IL_02d0: initobj [mscorlib]System.Runtime.CompilerServices.TaskAwaiter IL_02d6: ldarg.0 IL_02d7: ldc.i4.m1 IL_02d8: dup IL_02d9: stloc.0 IL_02da: stfld int32 C/'<M>d__0'::'<>1__state' IL_02df: ldloca.s 1 IL_02e1: call instance void [mscorlib]System.Runtime.CompilerServices.TaskAwaiter::GetResult() IL_02e6: ldarg.0 IL_02e7: ldnull IL_02e8: stfld class C/'<>c__DisplayClass0_2' C/'<M>d__0'::'<>8__3' IL_02ed: ldarg.0 IL_02ee: ldnull IL_02ef: stfld class C/'<>c__DisplayClass0_1' C/'<M>d__0'::'<>8__2' IL_02f4: br IL_009b } // end .try catch [mscorlib]System.Exception { IL_02f9: stloc.2 IL_02fa: ldarg.0 IL_02fb: ldc.i4.s -2 IL_02fd: stfld int32 C/'<M>d__0'::'<>1__state' IL_0302: ldarg.0 IL_0303: ldnull IL_0304: stfld class C/'<>c__DisplayClass0_0' C/'<M>d__0'::'<>8__1' IL_0309: ldarg.0 IL_030a: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_030f: ldloc.2 IL_0310: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetException(class [mscorlib]System.Exception) IL_0315: leave.s IL_0317 } // end handler IL_0317: ret } // end of method '<M>d__0'::MoveNext .method private final hidebysig newslot virtual instance void SetStateMachine ( class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine stateMachine ) cil managed { .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) .override method instance void [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine::SetStateMachine(class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine) // Method begins at RVA 0x240c // Code size 13 (0xd) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_0006: ldarg.1 IL_0007: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetStateMachine(class [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine) IL_000c: ret } // end of method '<M>d__0'::SetStateMachine } // end of class <M>d__0 // Methods .method public hidebysig instance class [mscorlib]System.Threading.Tasks.Task M () cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.AsyncStateMachineAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 09 43 2b 3c 4d 3e 64 5f 5f 30 00 00 ) // Method begins at RVA 0x2050 // Code size 47 (0x2f) .maxstack 2 .locals init ( [0] valuetype C/'<M>d__0' ) IL_0000: ldloca.s 0 IL_0002: call valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::Create() IL_0007: stfld valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_000c: ldloca.s 0 IL_000e: ldc.i4.m1 IL_000f: stfld int32 C/'<M>d__0'::'<>1__state' IL_0014: ldloca.s 0 IL_0016: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_001b: ldloca.s 0 IL_001d: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::Start<valuetype C/'<M>d__0'>(!!0&) IL_0022: ldloca.s 0 IL_0024: ldflda valuetype [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder C/'<M>d__0'::'<>t__builder' IL_0029: call instance class [mscorlib]System.Threading.Tasks.Task [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::get_Task() IL_002e: ret } // end of method C::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x208b // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor } // end of class C"); } } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest2/Recommendations/StackAllocKeywordRecommenderTests.cs
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class StackAllocKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { // e.g. this is a valid statement // stackalloc[] { 1, 2, 3 }.IndexOf(1); await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptySpaceAfterAssignment() { await VerifyKeywordAsync(AddInsideMethod( @"var v = $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeEmptySpace() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { var v = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeEmptySpace_AfterNonPointer() { // There can be an implicit conversion to int await VerifyKeywordAsync( @"unsafe class C { void Goo() { int v = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeEmptySpace_AfterPointer() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { int* v = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInField() { // While assigning stackalloc'd value to a field is invalid, // using one in the initializer is OK. e.g. // int _f = stackalloc[] { 1, 2, 3 }.IndexOf(1); await VerifyKeywordAsync( @"class C { int v = $$"); } [WorkItem(544504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideForStatementVarDecl1() { await VerifyKeywordAsync( @"class C { unsafe static void Main(string[] args) { for (var i = $$"); } [WorkItem(544504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideForStatementVarDecl2() { await VerifyKeywordAsync( @"class C { unsafe static void Main(string[] args) { for (int* i = $$"); } [WorkItem(544504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideForStatementVarDecl3() { await VerifyKeywordAsync( @"class C { unsafe static void Main(string[] args) { for (string i = $$"); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSOfAssignment_Span() { await VerifyKeywordAsync(AddInsideMethod(@" Span<int> s = $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSOfAssignment_Pointer() { await VerifyKeywordAsync(AddInsideMethod( @"int* v = $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSOfAssignment_ReAssignment() { await VerifyKeywordAsync(AddInsideMethod( @"v = $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithCast() { await VerifyKeywordAsync(AddInsideMethod(@" var s = (Span<char>)$$")); await VerifyKeywordAsync(AddInsideMethod(@" s = (Span<char>)$$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_True() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value ? $$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value ? $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_True_WithCast() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value ? (Span<int>)$$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value ? (Span<int>)$$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_False() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value ? stackalloc int[10] : $$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value ? stackalloc int[10] : $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_False_WithCast() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value ? stackalloc int[10] : (Span<int>)$$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value ? stackalloc int[10] : (Span<int>)$$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_NestedConditional_True() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value1 ? value2 ? $$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value1 ? value2 ? $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_NestedConditional_WithCast_True() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value1 ? value2 ? (Span<int>)$$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value1 ? value2 ? (Span<int>)$$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_NestedConditional_False() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value1 ? value2 ? stackalloc int [10] : $$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value1 ? value2 ? stackalloc int [10] : $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_NestedConditional_WithCast_False() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value1 ? value2 ? stackalloc int [10] : (Span<int>)$$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value1 ? value2 ? stackalloc int [10] : (Span<int>)$$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInLHSOfAssignment() { await VerifyAbsenceAsync(AddInsideMethod(@" var x $$ =")); await VerifyAbsenceAsync(AddInsideMethod(@" x $$ =")); } [WorkItem(41736, "https://github.com/dotnet/roslyn/issues/41736")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInArgument() { await VerifyKeywordAsync(@" class Program { static void Method(System.Span<byte> span) { Method($$); } }"); await VerifyKeywordAsync(@" class Program { static void Method(int x, System.Span<byte> span) { Method(1, $$); } }"); } [WorkItem(41736, "https://github.com/dotnet/roslyn/issues/41736")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInConstFieldInitializer() { await VerifyAbsenceAsync(@" class Program { private const int _f = $$ }"); } } }
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class StackAllocKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { // e.g. this is a valid statement // stackalloc[] { 1, 2, 3 }.IndexOf(1); await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptySpaceAfterAssignment() { await VerifyKeywordAsync(AddInsideMethod( @"var v = $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeEmptySpace() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { var v = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeEmptySpace_AfterNonPointer() { // There can be an implicit conversion to int await VerifyKeywordAsync( @"unsafe class C { void Goo() { int v = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeEmptySpace_AfterPointer() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { int* v = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInField() { // While assigning stackalloc'd value to a field is invalid, // using one in the initializer is OK. e.g. // int _f = stackalloc[] { 1, 2, 3 }.IndexOf(1); await VerifyKeywordAsync( @"class C { int v = $$"); } [WorkItem(544504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideForStatementVarDecl1() { await VerifyKeywordAsync( @"class C { unsafe static void Main(string[] args) { for (var i = $$"); } [WorkItem(544504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideForStatementVarDecl2() { await VerifyKeywordAsync( @"class C { unsafe static void Main(string[] args) { for (int* i = $$"); } [WorkItem(544504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideForStatementVarDecl3() { await VerifyKeywordAsync( @"class C { unsafe static void Main(string[] args) { for (string i = $$"); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSOfAssignment_Span() { await VerifyKeywordAsync(AddInsideMethod(@" Span<int> s = $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSOfAssignment_Pointer() { await VerifyKeywordAsync(AddInsideMethod( @"int* v = $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSOfAssignment_ReAssignment() { await VerifyKeywordAsync(AddInsideMethod( @"v = $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithCast() { await VerifyKeywordAsync(AddInsideMethod(@" var s = (Span<char>)$$")); await VerifyKeywordAsync(AddInsideMethod(@" s = (Span<char>)$$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_True() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value ? $$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value ? $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_True_WithCast() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value ? (Span<int>)$$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value ? (Span<int>)$$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_False() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value ? stackalloc int[10] : $$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value ? stackalloc int[10] : $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_False_WithCast() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value ? stackalloc int[10] : (Span<int>)$$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value ? stackalloc int[10] : (Span<int>)$$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_NestedConditional_True() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value1 ? value2 ? $$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value1 ? value2 ? $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_NestedConditional_WithCast_True() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value1 ? value2 ? (Span<int>)$$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value1 ? value2 ? (Span<int>)$$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_NestedConditional_False() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value1 ? value2 ? stackalloc int [10] : $$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value1 ? value2 ? stackalloc int [10] : $$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOnRHSWithConditionalExpression_NestedConditional_WithCast_False() { await VerifyKeywordAsync(AddInsideMethod(@" var s = value1 ? value2 ? stackalloc int [10] : (Span<int>)$$")); await VerifyKeywordAsync(AddInsideMethod(@" s = value1 ? value2 ? stackalloc int [10] : (Span<int>)$$")); } [WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInLHSOfAssignment() { await VerifyAbsenceAsync(AddInsideMethod(@" var x $$ =")); await VerifyAbsenceAsync(AddInsideMethod(@" x $$ =")); } [WorkItem(41736, "https://github.com/dotnet/roslyn/issues/41736")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInArgument() { await VerifyKeywordAsync(@" class Program { static void Method(System.Span<byte> span) { Method($$); } }"); await VerifyKeywordAsync(@" class Program { static void Method(int x, System.Span<byte> span) { Method(1, $$); } }"); } [WorkItem(41736, "https://github.com/dotnet/roslyn/issues/41736")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInConstFieldInitializer() { await VerifyAbsenceAsync(@" class Program { private const int _f = $$ }"); } } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core.Wpf/ReferenceHighlighting/WrittenReferenceHighlightTagDefinition.cs
// 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. #nullable disable using System; using System.ComponentModel.Composition; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.ReferenceHighlighting { [Export(typeof(EditorFormatDefinition))] [Name(WrittenReferenceHighlightTag.TagId)] [UserVisible(true)] internal class WrittenReferenceHighlightTagDefinition : MarkerFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WrittenReferenceHighlightTagDefinition() { // NOTE: This is the same color used by the editor for reference highlighting this.BackgroundColor = Color.FromRgb(219, 224, 204); this.DisplayName = EditorFeaturesResources.Highlighted_Written_Reference; } } }
// 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. #nullable disable using System; using System.ComponentModel.Composition; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.ReferenceHighlighting { [Export(typeof(EditorFormatDefinition))] [Name(WrittenReferenceHighlightTag.TagId)] [UserVisible(true)] internal class WrittenReferenceHighlightTagDefinition : MarkerFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WrittenReferenceHighlightTagDefinition() { // NOTE: This is the same color used by the editor for reference highlighting this.BackgroundColor = Color.FromRgb(219, 224, 204); this.DisplayName = EditorFeaturesResources.Highlighted_Written_Reference; } } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests.cs
// 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. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.IOperation)] public class IOperationTests : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)] [Fact] public void SuppressNullableWarningOperation() { var comp = CreateCompilation(@" class C { #nullable enable void M(string? x) /*<bind>*/{ x!.ToString(); }/*</bind>*/ }"); var expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x!.ToString();') Expression: IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x!.ToString()') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') Arguments(0)"; var diagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, diagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x!.ToString();') Expression: IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x!.ToString()') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(comp, expectedFlowGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)] [Fact] public void SuppressNullableWarningOperation_ConstantValue() { var comp = CreateCompilation(@" class C { #nullable enable void M() /*<bind>*/{ ((string)null)!.ToString(); }/*</bind>*/ }"); var expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '((string)nu ... ToString();') Expression: IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '((string)nu ... .ToString()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Arguments(0)"; var diagnostics = new[] { // (7,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((string)null)!.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(7, 10) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, diagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)] [Fact] public void SuppressNullableWarningOperation_NestedFlow() { var comp = CreateCompilation(@" class C { #nullable enable void M(bool b, string? x, string? y) /*<bind>*/{ (b ? x : y)!.ToString(); }/*</bind>*/ }"); comp.VerifyDiagnostics(); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String?) (Syntax: 'x') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String?) (Syntax: 'y') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(b ? x : y)!.ToString();') Expression: IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '(b ? x : y)!.ToString()') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b ? x : y') Arguments(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(comp, expectedFlowGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)] [Fact] public void RefReassignmentExpressions() { var comp = CreateCompilation(@" class C { ref readonly int M(ref int rx) { ref int ry = ref rx; rx = ref ry; ry = ref """".Length == 0 ? ref (rx = ref ry) : ref (ry = ref rx); return ref (ry = ref rx); } }"); comp.VerifyDiagnostics(); var m = comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<BlockSyntax>().Single(); comp.VerifyOperationTree(m, expectedOperationTree: @" IBlockOperation (4 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Int32 ry IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'ref int ry = ref rx;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'ref int ry = ref rx') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 ry) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'ry = ref rx') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ref rx') IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'rx = ref ry;') Expression: ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'rx = ref ry') Left: IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx') Right: ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ry = ref """" ... = ref rx);') Expression: ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'ry = ref """" ... y = ref rx)') Left: ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry') Right: IConditionalOperation (IsRef) (OperationKind.Conditional, Type: System.Int32) (Syntax: '"""".Length = ... y = ref rx)') Condition: IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: '"""".Length == 0') Left: IPropertyReferenceOperation: System.Int32 System.String.Length { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: '"""".Length') Instance Receiver: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') WhenTrue: ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'rx = ref ry') Left: IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx') Right: ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry') WhenFalse: ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'ry = ref rx') Left: ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry') Right: IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx') IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return ref ... = ref rx);') ReturnedValue: ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'ry = ref rx') Left: ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry') Right: IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx')"); } [CompilerTrait(CompilerFeature.RefLocalsReturns)] [Fact] public void IOperationRefFor() { var tree = CSharpSyntaxTree.ParseText(@" using System; class C { public class LinkedList { public int Value; public LinkedList Next; } public void M(LinkedList list) { for (ref readonly var cur = ref list; cur != null; cur = ref cur.Next) { Console.WriteLine(cur.Value); } } }", options: TestOptions.Regular); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var m = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First(); comp.VerifyOperationTree(m, @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (ref re ... }') Locals: Local_1: C.LinkedList cur Condition: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'cur != null') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'cur') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'ref readonl ... = ref list') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'ref readonl ... = ref list') Declarators: IVariableDeclaratorOperation (Symbol: C.LinkedList cur) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'cur = ref list') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ref list') IParameterReferenceOperation: list (OperationKind.ParameterReference, Type: C.LinkedList) (Syntax: 'list') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'cur = ref cur.Next') Expression: ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: C.LinkedList) (Syntax: 'cur = ref cur.Next') Left: ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur') Right: IFieldReferenceOperation: C.LinkedList C.LinkedList.Next (OperationKind.FieldReference, Type: C.LinkedList) (Syntax: 'cur.Next') Instance Receiver: ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... cur.Value);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... (cur.Value)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'cur.Value') IFieldReferenceOperation: System.Int32 C.LinkedList.Value (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'cur.Value') Instance Receiver: ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)"); var op = (IForLoopOperation)comp.GetSemanticModel(tree).GetOperation(tree.GetRoot().DescendantNodes().OfType<ForStatementSyntax>().Single()); Assert.Equal(RefKind.RefReadOnly, op.Locals.Single().RefKind); } [CompilerTrait(CompilerFeature.RefLocalsReturns)] [Fact] public void IOperationRefForeach() { var tree = CSharpSyntaxTree.ParseText(@" using System; class C { public void M(RefEnumerable re) { foreach (ref readonly var x in re) { Console.WriteLine(x); } } } class RefEnumerable { private readonly int[] _arr = new int[5]; public StructEnum GetEnumerator() => new StructEnum(_arr); public struct StructEnum { private readonly int[] _arr; private int _current; public StructEnum(int[] arr) { _arr = arr; _current = -1; } public ref int Current => ref _arr[_current]; public bool MoveNext() => ++_current != _arr.Length; } }", options: TestOptions.Regular); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var m = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First(); comp.VerifyOperationTree(m, @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'foreach (re ... }') Locals: Local_1: System.Int32 x LoopControlVariable: IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'var') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: RefEnumerable, IsImplicit) (Syntax: 're') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: re (OperationKind.ParameterReference, Type: RefEnumerable) (Syntax: 're') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(x);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(x)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0)"); var op = (IForEachLoopOperation)comp.GetSemanticModel(tree).GetOperation(tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single()); Assert.Equal(RefKind.RefReadOnly, op.Locals.Single().RefKind); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(382240, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=382240")] public void NullInPlaceOfParamArray() { var text = @" public class Cls { public static void Main() { Test1(null); Test2(new object(), null); } static void Test1(params int[] x) { } static void Test2(int y, params int[] x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,15): error CS1503: Argument 1: cannot convert from 'object' to 'int' // Test2(new object(), null); Diagnostic(ErrorCode.ERR_BadArgType, "new object()").WithArguments("1", "object", "int").WithLocation(7, 15) ); var tree = compilation.SyntaxTrees.Single(); var nodes = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray(); compilation.VerifyOperationTree(nodes[0], expectedOperationTree: @"IInvocationOperation (void Cls.Test1(params System.Int32[] x)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test1(null)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32[], Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); compilation.VerifyOperationTree(nodes[1], expectedOperationTree: @"IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'Test2(new o ... ct(), null)') Children(2): IObjectCreationOperation (Constructor: System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object, IsInvalid) (Syntax: 'new object()') Arguments(0) Initializer: null ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')"); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DeconstructionAssignmentFromTuple() { var text = @" public class C { public static void M() { int x, y, z; (x, y, z) = (1, 2, 3); (x, y, z) = new C(); var (a, b) = (1, 2); } public void Deconstruct(out int a, out int b, out int c) { a = b = c = 1; } }"; var compilation = CreateCompilationWithMscorlib40(text, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var assignments = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().ToArray(); Assert.Equal("(x, y, z) = (1, 2, 3)", assignments[0].ToString()); IOperation operation1 = model.GetOperation(assignments[0]); Assert.NotNull(operation1); Assert.Equal(OperationKind.DeconstructionAssignment, operation1.Kind); Assert.False(operation1 is ISimpleAssignmentOperation); Assert.Equal("(x, y, z) = new C()", assignments[1].ToString()); IOperation operation2 = model.GetOperation(assignments[1]); Assert.NotNull(operation2); Assert.Equal(OperationKind.DeconstructionAssignment, operation2.Kind); Assert.False(operation2 is ISimpleAssignmentOperation); Assert.Equal("var (a, b) = (1, 2)", assignments[2].ToString()); IOperation operation3 = model.GetOperation(assignments[2]); Assert.NotNull(operation3); Assert.Equal(OperationKind.DeconstructionAssignment, operation3.Kind); Assert.False(operation3 is ISimpleAssignmentOperation); } [CompilerTrait(CompilerFeature.IOperation)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/45687")] public void TestClone() { var sourceCode = TestResource.AllInOneCSharpCode; var compilation = CreateCompilationWithMscorlib40(sourceCode, new[] { SystemRef, SystemCoreRef, ValueTupleRef, SystemRuntimeFacadeRef }, sourceFileName: "file.cs"); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); VerifyClone(model); } [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(22964, "https://github.com/dotnet/roslyn/issues/22964")] [Fact] public void GlobalStatement_Parent() { var source = @" System.Console.WriteLine(); "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var statement = tree.GetRoot().DescendantNodes().OfType<StatementSyntax>().Single(); var model = compilation.GetSemanticModel(tree); var operation = model.GetOperation(statement); Assert.Equal(OperationKind.ExpressionStatement, operation.Kind); Assert.Null(operation.Parent); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestParentOperations() { var sourceCode = TestResource.AllInOneCSharpCode; var compilation = CreateCompilationWithMscorlib40(sourceCode, new[] { SystemRef, SystemCoreRef, ValueTupleRef, SystemRuntimeFacadeRef }, sourceFileName: "file.cs"); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); VerifyParentOperations(model); } [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(23001, "https://github.com/dotnet/roslyn/issues/23001")] [Fact] public void TestGetOperationForQualifiedName() { var text = @"using System; public class Test { class A { public B b; } class B { } void M(A a) { int x2 = /*<bind>*/a.b/*</bind>*/; } } "; var comp = CreateCompilation(text); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); // Verify we return non-null operation only for topmost member access expression. var expr = (MemberAccessExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal("a.b", expr.ToString()); var operation = model.GetOperation(expr); Assert.NotNull(operation); Assert.Equal(OperationKind.FieldReference, operation.Kind); var fieldOperation = (IFieldReferenceOperation)operation; Assert.Equal("b", fieldOperation.Field.Name); // Verify we return null operation for child nodes of member access expression. Assert.Null(model.GetOperation(expr.Name)); } [Fact] public void TestSemanticModelOnOperationAncestors() { var compilation = CreateCompilation(@" class C { void M(bool flag) { if (flag) { int y = 1000; } } } "); var tree = compilation.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var literal = root.DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var methodDeclSyntax = literal.Ancestors().OfType<MethodDeclarationSyntax>().Single(); var model = compilation.GetSemanticModel(tree); IOperation operation = model.GetOperation(literal); VerifyRootAndModelForOperationAncestors(operation, model, expectedRootOperationKind: OperationKind.MethodBody, expectedRootSyntax: methodDeclSyntax); } [Fact] public void TestGetOperationOnSpeculativeSemanticModel() { var compilation = CreateCompilation(@" class C { void M(int x) { int y = 1000; } } "); var speculatedBlock = (BlockSyntax)SyntaxFactory.ParseStatement(@" { int z = 0; } "); var tree = compilation.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var typeDecl = (TypeDeclarationSyntax)root.Members[0]; var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0]; var model = compilation.GetSemanticModel(tree); SemanticModel speculativeModel; bool success = model.TryGetSpeculativeSemanticModel(methodDecl.Body.Statements[0].SpanStart, speculatedBlock, out speculativeModel); Assert.True(success); Assert.NotNull(speculativeModel); var localDecl = (LocalDeclarationStatementSyntax)speculatedBlock.Statements[0]; IOperation operation = speculativeModel.GetOperation(localDecl); VerifyRootAndModelForOperationAncestors(operation, speculativeModel, expectedRootOperationKind: OperationKind.Block, expectedRootSyntax: speculatedBlock); speculativeModel.VerifyOperationTree(localDecl, expectedOperationTree: @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int z = 0;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int z = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 z) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'z = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null "); } [Fact, WorkItem(26649, "https://github.com/dotnet/roslyn/issues/26649")] public void IncrementalBindingReusesBlock() { var source = @" class C { void M() { try { } catch (Exception e) { throw new Exception(); } } }"; var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees[0]; var semanticModel = compilation.GetSemanticModel(syntaxTree); // We want to get the IOperation for the { throw new Exception(); } first, and then for the containing catch block, to // force the semantic model to bind the inner first. It should reuse that inner block when binding the outer catch. var catchBlock = syntaxTree.GetRoot().DescendantNodes().OfType<CatchClauseSyntax>().Single(); var exceptionBlock = catchBlock.Block; var blockOperation = semanticModel.GetOperation(exceptionBlock); var catchOperation = (ICatchClauseOperation)semanticModel.GetOperation(catchBlock); Assert.Same(blockOperation, catchOperation.Handler); } private static void VerifyRootAndModelForOperationAncestors( IOperation operation, SemanticModel model, OperationKind expectedRootOperationKind, SyntaxNode expectedRootSyntax) { SemanticModel memberModel = ((Operation)operation).OwningSemanticModel; while (true) { Assert.Same(model, operation.SemanticModel); Assert.Same(memberModel, ((Operation)operation).OwningSemanticModel); if (operation.Parent == null) { Assert.Equal(expectedRootOperationKind, operation.Kind); Assert.Same(expectedRootSyntax, operation.Syntax); break; } operation = operation.Parent; } } [Fact, WorkItem(45955, "https://github.com/dotnet/roslyn/issues/45955")] public void SemanticModelFieldInitializerRace() { var source = $@" #nullable enable public class C {{ // Use a big initializer to increase the odds of hitting the race public static object o = null; public string s = {string.Join(" + ", Enumerable.Repeat("(string)o", 1000))}; }}"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees[0]; var fieldInitializer = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Last().Value; for (int i = 0; i < 5; i++) { // We had a race condition where the first attempt to access a field initializer could cause an assert to be hit, // and potentially more work to be done than was necessary. So we kick off a parallel task to attempt to // get info on a bunch of different threads at the same time and reproduce the issue. var model = comp.GetSemanticModel(tree); const int nTasks = 10; Enumerable.Range(0, nTasks).AsParallel() .ForAll(_ => Assert.Equal("System.String System.String.op_Addition(System.String left, System.String right)", model.GetSymbolInfo(fieldInitializer).Symbol.ToTestDisplayString(includeNonNullable: false))); } } } }
// 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. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.IOperation)] public class IOperationTests : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)] [Fact] public void SuppressNullableWarningOperation() { var comp = CreateCompilation(@" class C { #nullable enable void M(string? x) /*<bind>*/{ x!.ToString(); }/*</bind>*/ }"); var expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x!.ToString();') Expression: IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x!.ToString()') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') Arguments(0)"; var diagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, diagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x!.ToString();') Expression: IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x!.ToString()') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(comp, expectedFlowGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)] [Fact] public void SuppressNullableWarningOperation_ConstantValue() { var comp = CreateCompilation(@" class C { #nullable enable void M() /*<bind>*/{ ((string)null)!.ToString(); }/*</bind>*/ }"); var expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '((string)nu ... ToString();') Expression: IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '((string)nu ... .ToString()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Arguments(0)"; var diagnostics = new[] { // (7,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((string)null)!.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(7, 10) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, diagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)] [Fact] public void SuppressNullableWarningOperation_NestedFlow() { var comp = CreateCompilation(@" class C { #nullable enable void M(bool b, string? x, string? y) /*<bind>*/{ (b ? x : y)!.ToString(); }/*</bind>*/ }"); comp.VerifyDiagnostics(); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String?) (Syntax: 'x') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String?) (Syntax: 'y') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(b ? x : y)!.ToString();') Expression: IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '(b ? x : y)!.ToString()') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b ? x : y') Arguments(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(comp, expectedFlowGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)] [Fact] public void RefReassignmentExpressions() { var comp = CreateCompilation(@" class C { ref readonly int M(ref int rx) { ref int ry = ref rx; rx = ref ry; ry = ref """".Length == 0 ? ref (rx = ref ry) : ref (ry = ref rx); return ref (ry = ref rx); } }"); comp.VerifyDiagnostics(); var m = comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<BlockSyntax>().Single(); comp.VerifyOperationTree(m, expectedOperationTree: @" IBlockOperation (4 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Int32 ry IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'ref int ry = ref rx;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'ref int ry = ref rx') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 ry) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'ry = ref rx') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ref rx') IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'rx = ref ry;') Expression: ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'rx = ref ry') Left: IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx') Right: ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ry = ref """" ... = ref rx);') Expression: ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'ry = ref """" ... y = ref rx)') Left: ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry') Right: IConditionalOperation (IsRef) (OperationKind.Conditional, Type: System.Int32) (Syntax: '"""".Length = ... y = ref rx)') Condition: IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: '"""".Length == 0') Left: IPropertyReferenceOperation: System.Int32 System.String.Length { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: '"""".Length') Instance Receiver: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') WhenTrue: ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'rx = ref ry') Left: IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx') Right: ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry') WhenFalse: ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'ry = ref rx') Left: ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry') Right: IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx') IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return ref ... = ref rx);') ReturnedValue: ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'ry = ref rx') Left: ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry') Right: IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx')"); } [CompilerTrait(CompilerFeature.RefLocalsReturns)] [Fact] public void IOperationRefFor() { var tree = CSharpSyntaxTree.ParseText(@" using System; class C { public class LinkedList { public int Value; public LinkedList Next; } public void M(LinkedList list) { for (ref readonly var cur = ref list; cur != null; cur = ref cur.Next) { Console.WriteLine(cur.Value); } } }", options: TestOptions.Regular); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var m = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First(); comp.VerifyOperationTree(m, @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (ref re ... }') Locals: Local_1: C.LinkedList cur Condition: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'cur != null') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'cur') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'ref readonl ... = ref list') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'ref readonl ... = ref list') Declarators: IVariableDeclaratorOperation (Symbol: C.LinkedList cur) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'cur = ref list') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ref list') IParameterReferenceOperation: list (OperationKind.ParameterReference, Type: C.LinkedList) (Syntax: 'list') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'cur = ref cur.Next') Expression: ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: C.LinkedList) (Syntax: 'cur = ref cur.Next') Left: ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur') Right: IFieldReferenceOperation: C.LinkedList C.LinkedList.Next (OperationKind.FieldReference, Type: C.LinkedList) (Syntax: 'cur.Next') Instance Receiver: ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... cur.Value);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... (cur.Value)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'cur.Value') IFieldReferenceOperation: System.Int32 C.LinkedList.Value (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'cur.Value') Instance Receiver: ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)"); var op = (IForLoopOperation)comp.GetSemanticModel(tree).GetOperation(tree.GetRoot().DescendantNodes().OfType<ForStatementSyntax>().Single()); Assert.Equal(RefKind.RefReadOnly, op.Locals.Single().RefKind); } [CompilerTrait(CompilerFeature.RefLocalsReturns)] [Fact] public void IOperationRefForeach() { var tree = CSharpSyntaxTree.ParseText(@" using System; class C { public void M(RefEnumerable re) { foreach (ref readonly var x in re) { Console.WriteLine(x); } } } class RefEnumerable { private readonly int[] _arr = new int[5]; public StructEnum GetEnumerator() => new StructEnum(_arr); public struct StructEnum { private readonly int[] _arr; private int _current; public StructEnum(int[] arr) { _arr = arr; _current = -1; } public ref int Current => ref _arr[_current]; public bool MoveNext() => ++_current != _arr.Length; } }", options: TestOptions.Regular); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var m = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First(); comp.VerifyOperationTree(m, @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'foreach (re ... }') Locals: Local_1: System.Int32 x LoopControlVariable: IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'var') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: RefEnumerable, IsImplicit) (Syntax: 're') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: re (OperationKind.ParameterReference, Type: RefEnumerable) (Syntax: 're') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(x);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(x)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0)"); var op = (IForEachLoopOperation)comp.GetSemanticModel(tree).GetOperation(tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single()); Assert.Equal(RefKind.RefReadOnly, op.Locals.Single().RefKind); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(382240, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=382240")] public void NullInPlaceOfParamArray() { var text = @" public class Cls { public static void Main() { Test1(null); Test2(new object(), null); } static void Test1(params int[] x) { } static void Test2(int y, params int[] x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,15): error CS1503: Argument 1: cannot convert from 'object' to 'int' // Test2(new object(), null); Diagnostic(ErrorCode.ERR_BadArgType, "new object()").WithArguments("1", "object", "int").WithLocation(7, 15) ); var tree = compilation.SyntaxTrees.Single(); var nodes = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray(); compilation.VerifyOperationTree(nodes[0], expectedOperationTree: @"IInvocationOperation (void Cls.Test1(params System.Int32[] x)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test1(null)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32[], Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); compilation.VerifyOperationTree(nodes[1], expectedOperationTree: @"IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'Test2(new o ... ct(), null)') Children(2): IObjectCreationOperation (Constructor: System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object, IsInvalid) (Syntax: 'new object()') Arguments(0) Initializer: null ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')"); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DeconstructionAssignmentFromTuple() { var text = @" public class C { public static void M() { int x, y, z; (x, y, z) = (1, 2, 3); (x, y, z) = new C(); var (a, b) = (1, 2); } public void Deconstruct(out int a, out int b, out int c) { a = b = c = 1; } }"; var compilation = CreateCompilationWithMscorlib40(text, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var assignments = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().ToArray(); Assert.Equal("(x, y, z) = (1, 2, 3)", assignments[0].ToString()); IOperation operation1 = model.GetOperation(assignments[0]); Assert.NotNull(operation1); Assert.Equal(OperationKind.DeconstructionAssignment, operation1.Kind); Assert.False(operation1 is ISimpleAssignmentOperation); Assert.Equal("(x, y, z) = new C()", assignments[1].ToString()); IOperation operation2 = model.GetOperation(assignments[1]); Assert.NotNull(operation2); Assert.Equal(OperationKind.DeconstructionAssignment, operation2.Kind); Assert.False(operation2 is ISimpleAssignmentOperation); Assert.Equal("var (a, b) = (1, 2)", assignments[2].ToString()); IOperation operation3 = model.GetOperation(assignments[2]); Assert.NotNull(operation3); Assert.Equal(OperationKind.DeconstructionAssignment, operation3.Kind); Assert.False(operation3 is ISimpleAssignmentOperation); } [CompilerTrait(CompilerFeature.IOperation)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/45687")] public void TestClone() { var sourceCode = TestResource.AllInOneCSharpCode; var compilation = CreateCompilationWithMscorlib40(sourceCode, new[] { SystemRef, SystemCoreRef, ValueTupleRef, SystemRuntimeFacadeRef }, sourceFileName: "file.cs"); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); VerifyClone(model); } [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(22964, "https://github.com/dotnet/roslyn/issues/22964")] [Fact] public void GlobalStatement_Parent() { var source = @" System.Console.WriteLine(); "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var statement = tree.GetRoot().DescendantNodes().OfType<StatementSyntax>().Single(); var model = compilation.GetSemanticModel(tree); var operation = model.GetOperation(statement); Assert.Equal(OperationKind.ExpressionStatement, operation.Kind); Assert.Null(operation.Parent); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestParentOperations() { var sourceCode = TestResource.AllInOneCSharpCode; var compilation = CreateCompilationWithMscorlib40(sourceCode, new[] { SystemRef, SystemCoreRef, ValueTupleRef, SystemRuntimeFacadeRef }, sourceFileName: "file.cs"); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); VerifyParentOperations(model); } [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(23001, "https://github.com/dotnet/roslyn/issues/23001")] [Fact] public void TestGetOperationForQualifiedName() { var text = @"using System; public class Test { class A { public B b; } class B { } void M(A a) { int x2 = /*<bind>*/a.b/*</bind>*/; } } "; var comp = CreateCompilation(text); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); // Verify we return non-null operation only for topmost member access expression. var expr = (MemberAccessExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal("a.b", expr.ToString()); var operation = model.GetOperation(expr); Assert.NotNull(operation); Assert.Equal(OperationKind.FieldReference, operation.Kind); var fieldOperation = (IFieldReferenceOperation)operation; Assert.Equal("b", fieldOperation.Field.Name); // Verify we return null operation for child nodes of member access expression. Assert.Null(model.GetOperation(expr.Name)); } [Fact] public void TestSemanticModelOnOperationAncestors() { var compilation = CreateCompilation(@" class C { void M(bool flag) { if (flag) { int y = 1000; } } } "); var tree = compilation.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var literal = root.DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var methodDeclSyntax = literal.Ancestors().OfType<MethodDeclarationSyntax>().Single(); var model = compilation.GetSemanticModel(tree); IOperation operation = model.GetOperation(literal); VerifyRootAndModelForOperationAncestors(operation, model, expectedRootOperationKind: OperationKind.MethodBody, expectedRootSyntax: methodDeclSyntax); } [Fact] public void TestGetOperationOnSpeculativeSemanticModel() { var compilation = CreateCompilation(@" class C { void M(int x) { int y = 1000; } } "); var speculatedBlock = (BlockSyntax)SyntaxFactory.ParseStatement(@" { int z = 0; } "); var tree = compilation.SyntaxTrees[0]; var root = tree.GetCompilationUnitRoot(); var typeDecl = (TypeDeclarationSyntax)root.Members[0]; var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0]; var model = compilation.GetSemanticModel(tree); SemanticModel speculativeModel; bool success = model.TryGetSpeculativeSemanticModel(methodDecl.Body.Statements[0].SpanStart, speculatedBlock, out speculativeModel); Assert.True(success); Assert.NotNull(speculativeModel); var localDecl = (LocalDeclarationStatementSyntax)speculatedBlock.Statements[0]; IOperation operation = speculativeModel.GetOperation(localDecl); VerifyRootAndModelForOperationAncestors(operation, speculativeModel, expectedRootOperationKind: OperationKind.Block, expectedRootSyntax: speculatedBlock); speculativeModel.VerifyOperationTree(localDecl, expectedOperationTree: @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int z = 0;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int z = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 z) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'z = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null "); } [Fact, WorkItem(26649, "https://github.com/dotnet/roslyn/issues/26649")] public void IncrementalBindingReusesBlock() { var source = @" class C { void M() { try { } catch (Exception e) { throw new Exception(); } } }"; var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees[0]; var semanticModel = compilation.GetSemanticModel(syntaxTree); // We want to get the IOperation for the { throw new Exception(); } first, and then for the containing catch block, to // force the semantic model to bind the inner first. It should reuse that inner block when binding the outer catch. var catchBlock = syntaxTree.GetRoot().DescendantNodes().OfType<CatchClauseSyntax>().Single(); var exceptionBlock = catchBlock.Block; var blockOperation = semanticModel.GetOperation(exceptionBlock); var catchOperation = (ICatchClauseOperation)semanticModel.GetOperation(catchBlock); Assert.Same(blockOperation, catchOperation.Handler); } private static void VerifyRootAndModelForOperationAncestors( IOperation operation, SemanticModel model, OperationKind expectedRootOperationKind, SyntaxNode expectedRootSyntax) { SemanticModel memberModel = ((Operation)operation).OwningSemanticModel; while (true) { Assert.Same(model, operation.SemanticModel); Assert.Same(memberModel, ((Operation)operation).OwningSemanticModel); if (operation.Parent == null) { Assert.Equal(expectedRootOperationKind, operation.Kind); Assert.Same(expectedRootSyntax, operation.Syntax); break; } operation = operation.Parent; } } [Fact, WorkItem(45955, "https://github.com/dotnet/roslyn/issues/45955")] public void SemanticModelFieldInitializerRace() { var source = $@" #nullable enable public class C {{ // Use a big initializer to increase the odds of hitting the race public static object o = null; public string s = {string.Join(" + ", Enumerable.Repeat("(string)o", 1000))}; }}"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees[0]; var fieldInitializer = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Last().Value; for (int i = 0; i < 5; i++) { // We had a race condition where the first attempt to access a field initializer could cause an assert to be hit, // and potentially more work to be done than was necessary. So we kick off a parallel task to attempt to // get info on a bunch of different threads at the same time and reproduce the issue. var model = comp.GetSemanticModel(tree); const int nTasks = 10; Enumerable.Range(0, nTasks).AsParallel() .ForAll(_ => Assert.Equal("System.String System.String.op_Addition(System.String left, System.String right)", model.GetSymbolInfo(fieldInitializer).Symbol.ToTestDisplayString(includeNonNullable: false))); } } } }
-1
dotnet/roslyn
55,246
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicKeywordHighlighting.cs
// 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 System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicKeywordHighlighting : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicKeywordHighlighting(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicKeywordHighlighting)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void NavigationBetweenKeywords() { VisualStudio.Editor.SetText(@" Class C Sub Main() For a = 0 To 1 Step 1 For b = 0 To 2 Next b, a End Sub End Class"); Verify("To", 4); VisualStudio.Editor.InvokeNavigateToNextHighlightedReference(); VisualStudio.Editor.Verify.CurrentLineText("For a = 0 To 1 Step$$ 1", assertCaretPosition: true, trimWhitespace: true); } private void Verify(string marker, int expectedCount) { VisualStudio.Editor.PlaceCaret(marker, charsOffset: -1); VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.Classification, FeatureAttribute.KeywordHighlighting); Assert.Equal(expectedCount, VisualStudio.Editor.GetKeywordHighlightTags().Length); } } }
// 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 System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicKeywordHighlighting : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicKeywordHighlighting(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicKeywordHighlighting)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void NavigationBetweenKeywords() { VisualStudio.Editor.SetText(@" Class C Sub Main() For a = 0 To 1 Step 1 For b = 0 To 2 Next b, a End Sub End Class"); Verify("To", 4); VisualStudio.Editor.InvokeNavigateToNextHighlightedReference(); VisualStudio.Editor.Verify.CurrentLineText("For a = 0 To 1 Step$$ 1", assertCaretPosition: true, trimWhitespace: true); } private void Verify(string marker, int expectedCount) { VisualStudio.Editor.PlaceCaret(marker, charsOffset: -1); VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.Classification, FeatureAttribute.KeywordHighlighting); Assert.Equal(expectedCount, VisualStudio.Editor.GetKeywordHighlightTags().Length); } } }
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/Version.Details.xml
<?xml version="1.0" encoding="utf-8"?> <Dependencies> <ProductDependencies> <Dependency Name="XliffTasks" Version="1.0.0-beta.21215.1"> <Uri>https://github.com/dotnet/xliff-tasks</Uri> <Sha>7e80445ee82adbf9a8e6ae601ac5e239d982afaa</Sha> <SourceBuild RepoName="xliff-tasks" ManagedOnly="true" /> </Dependency> <Dependency Name="Microsoft.SourceBuild.Intermediate.source-build" Version="0.1.0-alpha.1.21377.1"> <Uri>https://github.com/dotnet/source-build</Uri> <Sha>3855598428e676010315576808fcca0a29363cfc</Sha> <SourceBuild RepoName="source-build" ManagedOnly="true" /> </Dependency> </ProductDependencies> <ToolsetDependencies> <Dependency Name="Microsoft.DotNet.Arcade.Sdk" Version="6.0.0-beta.21377.2"> <Uri>https://github.com/dotnet/arcade</Uri> <Sha>cab4a3c50fd042677ea17cfc5171b4ce8b29930f</Sha> <SourceBuild RepoName="arcade" ManagedOnly="true" /> </Dependency> <Dependency Name="Microsoft.Net.Compilers.Toolset" Version="4.0.0-3.21373.8"> <Uri>https://github.com/dotnet/roslyn</Uri> <Sha>5f124755232afa7b9903d6bdfcaeb47f39c8838e</Sha> </Dependency> <Dependency Name="Microsoft.DotNet.Helix.Sdk" Version="6.0.0-beta.21377.2"> <Uri>https://github.com/dotnet/arcade</Uri> <Sha>cab4a3c50fd042677ea17cfc5171b4ce8b29930f</Sha> </Dependency> </ToolsetDependencies> </Dependencies>
<?xml version="1.0" encoding="utf-8"?> <Dependencies> <ProductDependencies> <Dependency Name="XliffTasks" Version="1.0.0-beta.21215.1"> <Uri>https://github.com/dotnet/xliff-tasks</Uri> <Sha>7e80445ee82adbf9a8e6ae601ac5e239d982afaa</Sha> <SourceBuild RepoName="xliff-tasks" ManagedOnly="true" /> </Dependency> <Dependency Name="Microsoft.SourceBuild.Intermediate.source-build" Version="0.1.0-alpha.1.21377.1"> <Uri>https://github.com/dotnet/source-build</Uri> <Sha>3855598428e676010315576808fcca0a29363cfc</Sha> <SourceBuild RepoName="source-build" ManagedOnly="true" /> </Dependency> </ProductDependencies> <ToolsetDependencies> <Dependency Name="Microsoft.DotNet.Arcade.Sdk" Version="6.0.0-beta.21378.2"> <Uri>https://github.com/dotnet/arcade</Uri> <Sha>dd3652e2ae5ea89703a2286295de9efe908974f1</Sha> <SourceBuild RepoName="arcade" ManagedOnly="true" /> </Dependency> <Dependency Name="Microsoft.Net.Compilers.Toolset" Version="4.0.0-3.21373.8"> <Uri>https://github.com/dotnet/roslyn</Uri> <Sha>5f124755232afa7b9903d6bdfcaeb47f39c8838e</Sha> </Dependency> <Dependency Name="Microsoft.DotNet.Helix.Sdk" Version="6.0.0-beta.21378.2"> <Uri>https://github.com/dotnet/arcade</Uri> <Sha>dd3652e2ae5ea89703a2286295de9efe908974f1</Sha> </Dependency> </ToolsetDependencies> </Dependencies>
1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/internal/Tools.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net472</TargetFramework> <ImportDirectoryBuildTargets>false</ImportDirectoryBuildTargets> <AutomaticallyUseReferenceAssemblyPackages>false</AutomaticallyUseReferenceAssemblyPackages> </PropertyGroup> <ItemGroup> <!-- Clear references, the SDK may add some depending on UsuingToolXxx settings, but we only want to restore the following --> <PackageReference Remove="@(PackageReference)"/> <PackageReference Include="Microsoft.DotNet.IBCMerge" Version="$(MicrosoftDotNetIBCMergeVersion)" Condition="'$(UsingToolIbcOptimization)' == 'true'" /> <PackageReference Include="Drop.App" Version="$(DropAppVersion)" ExcludeAssets="all" Condition="'$(UsingToolVisualStudioIbcTraining)' == 'true'"/> </ItemGroup> <PropertyGroup> <RestoreSources></RestoreSources> <RestoreSources Condition="'$(UsingToolIbcOptimization)' == 'true'"> https://devdiv.pkgs.visualstudio.com/_packaging/dotnet-core-internal-tooling/nuget/v3/index.json; </RestoreSources> <RestoreSources Condition="'$(UsingToolVisualStudioIbcTraining)' == 'true'"> $(RestoreSources); https://devdiv.pkgs.visualstudio.com/_packaging/VS/nuget/v3/index.json; </RestoreSources> </PropertyGroup> <!-- Repository extensibility point --> <Import Project="$(RepositoryEngineeringDir)InternalTools.props" Condition="Exists('$(RepositoryEngineeringDir)InternalTools.props')" /> </Project>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. --> <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net472</TargetFramework> <ImportDirectoryBuildTargets>false</ImportDirectoryBuildTargets> <AutomaticallyUseReferenceAssemblyPackages>false</AutomaticallyUseReferenceAssemblyPackages> </PropertyGroup> <ItemGroup> <!-- Clear references, the SDK may add some depending on UsuingToolXxx settings, but we only want to restore the following --> <PackageReference Remove="@(PackageReference)"/> <PackageReference Include="Microsoft.DotNet.IBCMerge" Version="$(MicrosoftDotNetIBCMergeVersion)" Condition="'$(UsingToolIbcOptimization)' == 'true'" /> <PackageReference Include="Drop.App" Version="$(DropAppVersion)" ExcludeAssets="all" Condition="'$(UsingToolVisualStudioIbcTraining)' == 'true'"/> </ItemGroup> <PropertyGroup> <RestoreSources></RestoreSources> <RestoreSources Condition="'$(UsingToolIbcOptimization)' == 'true'"> https://devdiv.pkgs.visualstudio.com/_packaging/dotnet-core-internal-tooling/nuget/v3/index.json; </RestoreSources> <RestoreSources Condition="'$(UsingToolVisualStudioIbcTraining)' == 'true'"> $(RestoreSources); https://devdiv.pkgs.visualstudio.com/_packaging/VS/nuget/v3/index.json; </RestoreSources> </PropertyGroup> <!-- Repository extensibility point --> <Import Project="$(RepositoryEngineeringDir)InternalTools.props" Condition="Exists('$(RepositoryEngineeringDir)InternalTools.props')" /> </Project>
1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./global.json
{ "sdk": { "version": "6.0.100-preview.6.21355.2" }, "tools": { "dotnet": "6.0.100-preview.6.21355.2", "vs": { "version": "16.10" }, "xcopy-msbuild": "16.10.0-preview2" }, "msbuild-sdks": { "Microsoft.DotNet.Arcade.Sdk": "6.0.0-beta.21377.2", "Microsoft.DotNet.Helix.Sdk": "6.0.0-beta.21377.2" } }
{ "sdk": { "version": "6.0.100-preview.6.21355.2" }, "tools": { "dotnet": "6.0.100-preview.6.21355.2", "vs": { "version": "16.10" }, "xcopy-msbuild": "16.10.0-preview2" }, "msbuild-sdks": { "Microsoft.DotNet.Arcade.Sdk": "6.0.0-beta.21378.2", "Microsoft.DotNet.Helix.Sdk": "6.0.0-beta.21378.2" } }
1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/Core/MSBuildTask/Microsoft.Build.Tasks.CodeAnalysis.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.BuildTasks</RootNamespace> <DefaultLanguage>en-US</DefaultLanguage> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> <AutoGenerateAssemblyVersion>true</AutoGenerateAssemblyVersion> <AssemblyVersion/> <!-- CA1819 (Properties should not return arrays) disabled as it is very common across this project. --> <NoWarn>$(NoWarn);CA1819</NoWarn> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis.Build.Tasks</PackageId> <PackageDescription> The build task and targets used by MSBuild to run the C# and VB compilers. Supports using VBCSCompiler on Windows. </PackageDescription> <GenerateMicrosoftCodeAnalysisCommitHashAttribute>true</GenerateMicrosoftCodeAnalysisCommitHashAttribute> </PropertyGroup> <ItemGroup> <Content Include="*.targets"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <Pack>true</Pack> <BuildAction>None</BuildAction> <PackageCopyToOutput>true</PackageCopyToOutput> <PackagePath>contentFiles\any\any</PackagePath> </Content> </ItemGroup> <ItemGroup> <Compile Include="..\..\Shared\NamedPipeUtil.cs" /> <Compile Include="..\..\Shared\BuildServerConnection.cs" /> <Compile Include="..\..\Shared\RuntimeHostInfo.cs" /> <Compile Include="..\Portable\CommitHashAttribute.cs" /> <Compile Include="..\Portable\InternalUtilities\CommandLineUtilities.cs" /> <Compile Include="..\Portable\InternalUtilities\CompilerOptionParseUtilities.cs" /> <Compile Include="..\Portable\InternalUtilities\Debug.cs" Link="Debug.cs" /> <Compile Include="..\Portable\InternalUtilities\IReadOnlySet.cs" /> <Compile Include="..\Portable\InternalUtilities\NullableAttributes.cs" /> <Compile Include="..\Portable\InternalUtilities\PlatformInformation.cs" /> <Compile Include="..\Portable\InternalUtilities\ReflectionUtilities.cs" /> <Compile Include="..\Portable\InternalUtilities\RoslynString.cs" /> <Compile Include="..\Portable\InternalUtilities\UnicodeCharacterUtilities.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="ErrorString.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildFrameworkVersion)" ExcludeAssets="Runtime" /> <PackageReference Include="Microsoft.Build.Tasks.Core" Version="$(MicrosoftBuildTasksCoreVersion)" ExcludeAssets="Runtime" /> <PackageReference Include="System.IO.Pipes.AccessControl" Version="$(SystemIOPipesAccessControlVersion)" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" /> <PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" Condition="'$(TargetFramework)' != 'netcoreapp3.1'" /> <PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="$(SystemRuntimeCompilerServicesUnsafeVersion)" Condition="'$(TargetFramework)' != 'netcoreapp3.1'" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.Build.Tasks.CodeAnalysis.UnitTests" /> </ItemGroup> <Import Project="..\CommandLine\CommandLine.projitems" Label="Shared" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.BuildTasks</RootNamespace> <DefaultLanguage>en-US</DefaultLanguage> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> <AutoGenerateAssemblyVersion>true</AutoGenerateAssemblyVersion> <AssemblyVersion/> <!-- CA1819 (Properties should not return arrays) disabled as it is very common across this project. --> <NoWarn>$(NoWarn);CA1819</NoWarn> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis.Build.Tasks</PackageId> <PackageDescription> The build task and targets used by MSBuild to run the C# and VB compilers. Supports using VBCSCompiler on Windows. </PackageDescription> <GenerateMicrosoftCodeAnalysisCommitHashAttribute>true</GenerateMicrosoftCodeAnalysisCommitHashAttribute> </PropertyGroup> <ItemGroup> <Content Include="*.targets"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <Pack>true</Pack> <BuildAction>None</BuildAction> <PackageCopyToOutput>true</PackageCopyToOutput> <PackagePath>contentFiles\any\any</PackagePath> </Content> </ItemGroup> <ItemGroup> <Compile Include="..\..\Shared\NamedPipeUtil.cs" /> <Compile Include="..\..\Shared\BuildServerConnection.cs" /> <Compile Include="..\..\Shared\RuntimeHostInfo.cs" /> <Compile Include="..\Portable\CommitHashAttribute.cs" /> <Compile Include="..\Portable\InternalUtilities\CommandLineUtilities.cs" /> <Compile Include="..\Portable\InternalUtilities\CompilerOptionParseUtilities.cs" /> <Compile Include="..\Portable\InternalUtilities\Debug.cs" Link="Debug.cs" /> <Compile Include="..\Portable\InternalUtilities\IReadOnlySet.cs" /> <Compile Include="..\Portable\InternalUtilities\NullableAttributes.cs" /> <Compile Include="..\Portable\InternalUtilities\PlatformInformation.cs" /> <Compile Include="..\Portable\InternalUtilities\ReflectionUtilities.cs" /> <Compile Include="..\Portable\InternalUtilities\RoslynString.cs" /> <Compile Include="..\Portable\InternalUtilities\UnicodeCharacterUtilities.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="ErrorString.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildFrameworkVersion)" ExcludeAssets="Runtime" /> <PackageReference Include="Microsoft.Build.Tasks.Core" Version="$(MicrosoftBuildTasksCoreVersion)" ExcludeAssets="Runtime" /> <PackageReference Include="System.IO.Pipes.AccessControl" Version="$(SystemIOPipesAccessControlVersion)" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" /> <PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" Condition="'$(TargetFramework)' != 'netcoreapp3.1'" /> <PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="$(SystemRuntimeCompilerServicesUnsafeVersion)" Condition="'$(TargetFramework)' != 'netcoreapp3.1'" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.Build.Tasks.CodeAnalysis.UnitTests" /> </ItemGroup> <Import Project="..\CommandLine\CommandLine.projitems" Label="Shared" /> </Project>
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/My Project/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/VisualBasic/Test/Emit/My Project/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/NuGet/Microsoft.CodeAnalysis.Package.csproj
<!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>net472;netstandard2.0</TargetFrameworks> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis</PackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <PackageDescription> .NET Compiler Platform ("Roslyn"). This is the all-in-one package (a superset of all assemblies). You can install any of these sub-packages if you only want part of the functionality: - "Microsoft.CodeAnalysis.CSharp.Workspaces" (C# compiler + services) - "Microsoft.CodeAnalysis.VisualBasic.Workspaces" (VB compiler + services) - "Microsoft.CodeAnalysis.Compilers" (both compilers) - "Microsoft.CodeAnalysis.CSharp" (only the C# compiler) - "Microsoft.CodeAnalysis.VisualBasic (only the VB compiler) </PackageDescription> <!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed --> <NoWarn>$(NoWarn);NU5128</NoWarn> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> </ItemGroup> </Project>
<!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>net472;netstandard2.0</TargetFrameworks> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis</PackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <PackageDescription> .NET Compiler Platform ("Roslyn"). This is the all-in-one package (a superset of all assemblies). You can install any of these sub-packages if you only want part of the functionality: - "Microsoft.CodeAnalysis.CSharp.Workspaces" (C# compiler + services) - "Microsoft.CodeAnalysis.VisualBasic.Workspaces" (VB compiler + services) - "Microsoft.CodeAnalysis.Compilers" (both compilers) - "Microsoft.CodeAnalysis.CSharp" (only the C# compiler) - "Microsoft.CodeAnalysis.VisualBasic (only the VB compiler) </PackageDescription> <!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed --> <NoWarn>$(NoWarn);NU5128</NoWarn> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/Remote/Core/Microsoft.CodeAnalysis.Remote.Workspaces.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.Remote</RootNamespace> <TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <ApplyNgenOptimization Condition="'$(TargetFramework)' == 'netstandard2.0'">partial</ApplyNgenOptimization> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageDescription> A shared package used by the .NET Compiler Platform ("Roslyn") including support for coordinating analysis of projects and solutions using a separate server process. Do not install this package manually, it will be added as a prerequisite by other packages that require it. </PackageDescription> </PropertyGroup> <ItemGroup Label="Project References"> <!-- Features are currently required due to dependencies from JSON serializer and SolutionChecksumUpdater (Solution Crawler). https://github.com/dotnet/roslyn/issues/46519 --> <ProjectReference Include="..\..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Composition" Version="$(SystemCompositionVersion)" /> <PackageReference Include="System.ComponentModel.Composition" Version="$(SystemComponentModelCompositionVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Telemetry" Version="$(MicrosoftVisualStudioTelemetryVersion)" PrivateAssets="all" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> <PackageReference Include="Microsoft.ServiceHub.Client" Version="$(MicrosoftServiceHubClientVersion)" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="RemoteWorkspacesResources.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Razor.ServiceHub" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.LiveUnitTesting.BuildManager" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.LiveUnitTesting.BuildManager.Core" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTesting.SourceBasedTestDiscovery" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTesting.SourceBasedTestDiscovery.Core" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CodeLens" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Implementation" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.Completion.Tests" Key="$(IntelliCodeCSharpKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35081" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.Razor"/> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.IntelliCode.CSharp" Partner="Pythia" Key="$(IntelliCodeCSharpKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.IntelliCode.CSharp.Extraction" Partner="Pythia" Key="$(IntelliCodeCSharpKey)" /> <!-- BEGIN MONODEVELOP These MonoDevelop dependencies don't ship with Visual Studio, so can't break our binary insertions and are exempted from the ExternalAccess adapter assembly policies. --> <InternalsVisibleTo Include="MonoDevelop.Ide" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Ide.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <!-- END MONODEVELOP --> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.Remote</RootNamespace> <TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <ApplyNgenOptimization Condition="'$(TargetFramework)' == 'netstandard2.0'">partial</ApplyNgenOptimization> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageDescription> A shared package used by the .NET Compiler Platform ("Roslyn") including support for coordinating analysis of projects and solutions using a separate server process. Do not install this package manually, it will be added as a prerequisite by other packages that require it. </PackageDescription> </PropertyGroup> <ItemGroup Label="Project References"> <!-- Features are currently required due to dependencies from JSON serializer and SolutionChecksumUpdater (Solution Crawler). https://github.com/dotnet/roslyn/issues/46519 --> <ProjectReference Include="..\..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Composition" Version="$(SystemCompositionVersion)" /> <PackageReference Include="System.ComponentModel.Composition" Version="$(SystemComponentModelCompositionVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Telemetry" Version="$(MicrosoftVisualStudioTelemetryVersion)" PrivateAssets="all" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> <PackageReference Include="Microsoft.ServiceHub.Client" Version="$(MicrosoftServiceHubClientVersion)" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="RemoteWorkspacesResources.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Razor.ServiceHub" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.LiveUnitTesting.BuildManager" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.LiveUnitTesting.BuildManager.Core" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTesting.SourceBasedTestDiscovery" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTesting.SourceBasedTestDiscovery.Core" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CodeLens" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Implementation" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.Completion.Tests" Key="$(IntelliCodeCSharpKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35081" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.Razor"/> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.IntelliCode.CSharp" Partner="Pythia" Key="$(IntelliCodeCSharpKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.IntelliCode.CSharp.Extraction" Partner="Pythia" Key="$(IntelliCodeCSharpKey)" /> <!-- BEGIN MONODEVELOP These MonoDevelop dependencies don't ship with Visual Studio, so can't break our binary insertions and are exempted from the ExternalAccess adapter assembly policies. --> <InternalsVisibleTo Include="MonoDevelop.Ide" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Ide.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <!-- END MONODEVELOP --> </ItemGroup> </Project>
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/VisualStudio/CodeLens/Microsoft.VisualStudio.LanguageServices.CodeLens.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <OutputType>Library</OutputType> <RootNamespace>Microsoft.VisualStudio.LanguageServices.CodeLens</RootNamespace> <TargetFramework>net472</TargetFramework> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- NuGet --> <IsPackable>false</IsPackable> <PackageDescription> .NET Compiler Platform ("Roslyn") support for Visual Studio Code Lens. </PackageDescription> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\VisualStudio\Core\Def\Microsoft.VisualStudio.LanguageServices.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language" Version="$(MicrosoftVisualStudioLanguageVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI.Wpf" Version="$(MicrosoftVisualStudioTextUIWpfVersion)" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="CodeLensVSResources.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Roslyn.VisualStudio.Setup" /> <InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <OutputType>Library</OutputType> <RootNamespace>Microsoft.VisualStudio.LanguageServices.CodeLens</RootNamespace> <TargetFramework>net472</TargetFramework> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- NuGet --> <IsPackable>false</IsPackable> <PackageDescription> .NET Compiler Platform ("Roslyn") support for Visual Studio Code Lens. </PackageDescription> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\VisualStudio\Core\Def\Microsoft.VisualStudio.LanguageServices.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language" Version="$(MicrosoftVisualStudioLanguageVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI.Wpf" Version="$(MicrosoftVisualStudioTextUIWpfVersion)" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="CodeLensVSResources.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Roslyn.VisualStudio.Setup" /> <InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Dependencies/Collections/Microsoft.CodeAnalysis.Collections.Package.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks> <GenerateDocumentationFile>false</GenerateDocumentationFile> <DebugType>none</DebugType> <GenerateDependencyFile>false</GenerateDependencyFile> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- NuGet --> <IsPackable>true</IsPackable> <IsSourcePackage>true</IsSourcePackage> <PackageId>Microsoft.CodeAnalysis.Collections</PackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <PackageDescription> Package containing sources of Microsoft .NET Compiler Platform ("Roslyn") collections. </PackageDescription> <!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed --> <NoWarn>$(NoWarn);NU5128</NoWarn> </PropertyGroup> <ItemGroup> <!-- ⚠ Consuming projects outside dotnet/roslyn will be required to manually reproduce the APIs for any linked files added here --> <Compile Include="..\..\Compilers\Core\Portable\InternalUtilities\NullableAttributes.cs" Link="NullableAttributes.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="Internal\Strings.resx" GenerateSource="true" ClassName="Microsoft.CodeAnalysis.Collections.Internal.SR" /> </ItemGroup> <!-- Source packaging helpers. --> <PropertyGroup> <TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_AddResourceFilesToSourcePackage</TargetsForTfmSpecificContentInPackage> </PropertyGroup> <Target Name="_AddResourceFilesToSourcePackage"> <PropertyGroup> <!-- TODO: language to dir name mapping (https://github.com/Microsoft/msbuild/issues/2101) --> <_LanguageDirName>$(DefaultLanguageSourceExtension.TrimStart('.'))</_LanguageDirName> </PropertyGroup> <ItemGroup> <_File Remove="@(_File)"/> <_File Include="$(MSBuildProjectDirectory)\**\*.resx" TargetDir="contentFiles/$(_LanguageDirName)/$(TargetFramework)" BuildAction="EmbeddedResource" /> <_File Include="$(MSBuildProjectDirectory)\**\*.xlf" TargetDir="contentFiles/$(_LanguageDirName)/$(TargetFramework)" BuildAction="None" /> <TfmSpecificPackageFile Include="@(_File)" PackagePath="%(_File.TargetDir)/%(_File.RecursiveDir)%(_File.FileName)%(_File.Extension)"/> </ItemGroup> </Target> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks> <GenerateDocumentationFile>false</GenerateDocumentationFile> <DebugType>none</DebugType> <GenerateDependencyFile>false</GenerateDependencyFile> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- NuGet --> <IsPackable>true</IsPackable> <IsSourcePackage>true</IsSourcePackage> <PackageId>Microsoft.CodeAnalysis.Collections</PackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <PackageDescription> Package containing sources of Microsoft .NET Compiler Platform ("Roslyn") collections. </PackageDescription> <!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed --> <NoWarn>$(NoWarn);NU5128</NoWarn> </PropertyGroup> <ItemGroup> <!-- ⚠ Consuming projects outside dotnet/roslyn will be required to manually reproduce the APIs for any linked files added here --> <Compile Include="..\..\Compilers\Core\Portable\InternalUtilities\NullableAttributes.cs" Link="NullableAttributes.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="Internal\Strings.resx" GenerateSource="true" ClassName="Microsoft.CodeAnalysis.Collections.Internal.SR" /> </ItemGroup> <!-- Source packaging helpers. --> <PropertyGroup> <TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_AddResourceFilesToSourcePackage</TargetsForTfmSpecificContentInPackage> </PropertyGroup> <Target Name="_AddResourceFilesToSourcePackage"> <PropertyGroup> <!-- TODO: language to dir name mapping (https://github.com/Microsoft/msbuild/issues/2101) --> <_LanguageDirName>$(DefaultLanguageSourceExtension.TrimStart('.'))</_LanguageDirName> </PropertyGroup> <ItemGroup> <_File Remove="@(_File)"/> <_File Include="$(MSBuildProjectDirectory)\**\*.resx" TargetDir="contentFiles/$(_LanguageDirName)/$(TargetFramework)" BuildAction="EmbeddedResource" /> <_File Include="$(MSBuildProjectDirectory)\**\*.xlf" TargetDir="contentFiles/$(_LanguageDirName)/$(TargetFramework)" BuildAction="None" /> <TfmSpecificPackageFile Include="@(_File)" PackagePath="%(_File.TargetDir)/%(_File.RecursiveDir)%(_File.FileName)%(_File.Extension)"/> </ItemGroup> </Target> </Project>
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Tools/ExternalAccess/Xamarin.Remote/Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote.csproj
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote</RootNamespace> <TargetFramework>net472</TargetFramework> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote</PackageId> <PackageDescription> A supporting package for Xamarin: https://github.com/xamarin/CodeAnalysis </PackageDescription> </PropertyGroup> <ItemGroup> <!-- ⚠ ONLY XAMARIN ASSEMBLIES MAY BE ADDED HERE ⚠ --> <InternalsVisibleTo Include="Xamarin.CodeAnalysis.Remote" Key="$(XamarinKey)" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualStudio.CoreUtility" Version="$(MicrosoftVisualStudioCoreUtilityVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.Data" Version="$(MicrosoftVisualStudioTextDataVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.Logic" Version="$(MicrosoftVisualStudioTextLogicVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="StreamJsonRpc" Version="$(StreamJsonRpcVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote</RootNamespace> <TargetFramework>net472</TargetFramework> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote</PackageId> <PackageDescription> A supporting package for Xamarin: https://github.com/xamarin/CodeAnalysis </PackageDescription> </PropertyGroup> <ItemGroup> <!-- ⚠ ONLY XAMARIN ASSEMBLIES MAY BE ADDED HERE ⚠ --> <InternalsVisibleTo Include="Xamarin.CodeAnalysis.Remote" Key="$(XamarinKey)" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualStudio.CoreUtility" Version="$(MicrosoftVisualStudioCoreUtilityVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.Data" Version="$(MicrosoftVisualStudioTextDataVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.Logic" Version="$(MicrosoftVisualStudioTextLogicVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="StreamJsonRpc" Version="$(StreamJsonRpcVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.UnitTests.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.CSharp.UnitTests</RootNamespace> <AssemblyName>Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.UnitTests</AssemblyName> <TargetFramework>net472</TargetFramework> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\..\Compilers\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Core\Source\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.csproj" /> <ProjectReference Include="..\..\..\Core\Test\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.Utilities.csproj" /> <ProjectReference Include="..\..\Source\ExpressionCompiler\Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.csproj" /> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> </ItemGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml" /> <PackageReference Include="Microsoft.VisualStudio.Debugger.Engine-implementation" Version="$(MicrosoftVisualStudioDebuggerEngineimplementationVersion)" /> <PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.CSharp.UnitTests</RootNamespace> <AssemblyName>Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.UnitTests</AssemblyName> <TargetFramework>net472</TargetFramework> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\..\Compilers\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Core\Source\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.csproj" /> <ProjectReference Include="..\..\..\Core\Test\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.Utilities.csproj" /> <ProjectReference Include="..\..\Source\ExpressionCompiler\Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.csproj" /> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> </ItemGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml" /> <PackageReference Include="Microsoft.VisualStudio.Debugger.Engine-implementation" Version="$(MicrosoftVisualStudioDebuggerEngineimplementationVersion)" /> <PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" /> </Project>
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/MSBuildTest/Resources/NetCoreMultiTFM_ProjectReference/Project.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFrameworks>netcoreapp2.1;net461</TargetFrameworks> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\Library\Library.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFrameworks>netcoreapp2.1;net461</TargetFrameworks> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\Library\Library.csproj" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/Core/Desktop/Microsoft.CodeAnalysis.Workspaces.Desktop.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis</RootNamespace> <TargetFrameworks>net472;netcoreapp3.1</TargetFrameworks> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> <!-- NuGet --> <IsPackable>true</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="System.ComponentModel.Composition" Version="$(SystemComponentModelCompositionVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Features" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Implementation" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Razor.RemoteClient" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Workspaces" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Razor.ServiceHub" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" /> <InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Setup" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" /> <!-- BEGIN MONODEVELOP These MonoDevelop dependencies don't ship with Visual Studio, so can't break our binary insertions and are exempted from the ExternalAccess adapter assembly policies. --> <InternalsVisibleTo Include="MonoDevelop.Ide" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Ide.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <!-- END MONODEVELOP --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" LoadsWithinVisualStudio="false" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis</RootNamespace> <TargetFrameworks>net472;netcoreapp3.1</TargetFrameworks> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> <!-- NuGet --> <IsPackable>true</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="System.ComponentModel.Composition" Version="$(SystemComponentModelCompositionVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Features" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Implementation" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Razor.RemoteClient" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Workspaces" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Razor.ServiceHub" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" /> <InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Setup" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" /> <!-- BEGIN MONODEVELOP These MonoDevelop dependencies don't ship with Visual Studio, so can't break our binary insertions and are exempted from the ExternalAccess adapter assembly policies. --> <InternalsVisibleTo Include="MonoDevelop.Ide" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Ide.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <!-- END MONODEVELOP --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" LoadsWithinVisualStudio="false" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/Test/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Tools/ManifestGenerator/ManifestGenerator.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <UseVSHostingProcess>false</UseVSHostingProcess> </PropertyGroup> <ItemGroup> <PackageReference Include="Mono.Options" Version="$(MonoOptionsVersion)" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <UseVSHostingProcess>false</UseVSHostingProcess> </PropertyGroup> <ItemGroup> <PackageReference Include="Mono.Options" Version="$(MonoOptionsVersion)" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/CSharp/Portable/BoundTree/BoundNodes.xml
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <!-- To re-generate source from this file, run eng/generate-compiler-code.cmd Important things to know about reference types, value types, and nulls. By default, all fields of reference type are checked (in debug) to be non-null. This can be modified by used the "Null" attribute, which can be one of the following values: disallow (default) - disallow null values allow - allow null values always - always null - only used in an override to indicate that this subclass always sets this field to null. notApplicable - its a value type, so it cannot be null In order to generate code, the generator needs to know what types beyond the built-in types are value types. This is indicated via a "ValueType" declaration. --> <Tree Root="BoundNode"> <!-- Don't put ImmutableArray here, that's handled in a special way internally.--> <ValueType Name="ConversionKind"/> <ValueType Name="Conversion"/> <ValueType Name="TextSpan"/> <ValueType Name="UnaryOperatorKind"/> <ValueType Name="BinaryOperatorKind"/> <ValueType Name="LookupResultKind"/> <ValueType Name="NoOpStatementFlavor"/> <ValueType Name="RefKind"/> <ValueType Name="BoundTypeOrValueData"/> <ValueType Name="BoundLocalDeclarationKind"/> <ValueType Name="NullableAnnotation"/> <ValueType Name="ErrorCode"/> <ValueType Name="ImmutableBindingDiagnostic"/> <ValueType Name="InterpolatedStringHandlerData"/> <AbstractNode Name="BoundInitializer" Base="BoundNode"/> <AbstractNode Name="BoundEqualsValue" Base="BoundInitializer"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <!-- Expression representing the value. --> <Field Name="Value" Type="BoundExpression"/> </AbstractNode> <!-- Bound node that represents the binding of an "= Value" construct in a field declaration. Appears only in bound trees generated by a SemanticModel. --> <Node Name="BoundFieldEqualsValue" Base="BoundEqualsValue"> <!-- Field receiving the value. --> <Field Name="Field" Type="FieldSymbol"/> </Node> <!-- Bound node that represents the binding of an "= Value" construct in a property declaration. Appears only in bound trees generated by a SemanticModel. --> <Node Name="BoundPropertyEqualsValue" Base="BoundEqualsValue"> <!-- Property receiving the value. --> <Field Name="Property" Type="PropertySymbol"/> </Node> <!-- Bound node that represents the binding of an "= Value" construct in a parameter declaration. Appears only in bound trees generated by a SemanticModel. --> <Node Name="BoundParameterEqualsValue" Base="BoundEqualsValue"> <!-- Parameter receiving the value. --> <Field Name="Parameter" Type="ParameterSymbol"/> </Node> <Node Name="BoundGlobalStatementInitializer" Base="BoundInitializer"> <Field Name="Statement" Type="BoundStatement"/> </Node> <AbstractNode Name="BoundExpression" Base="BoundNode"> <Field Name="Type" Type="TypeSymbol?"/> </AbstractNode> <AbstractNode Name="BoundValuePlaceholderBase" Base="BoundExpression"> </AbstractNode> <!-- This node is used to represent an expression returning value of a certain type. It is used to perform intermediate binding, and will not survive the local rewriting. --> <Node Name="BoundDeconstructValuePlaceholder" Base="BoundValuePlaceholderBase"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ValEscape" Type="uint" Null="NotApplicable"/> </Node> <!-- In a tuple binary operator, this node is used to represent tuple elements in a tuple binary operator, and to represent an element-wise comparison result to convert back to bool. It does not survive the initial binding. --> <Node Name="BoundTupleOperandPlaceholder" Base="BoundValuePlaceholderBase"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <!-- This node is used to represent an awaitable expression of a certain type, when binding an using-await statement. --> <Node Name="BoundAwaitableValuePlaceholder" Base="BoundValuePlaceholderBase"> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="allow"/> <Field Name="ValEscape" Type="uint" Null="NotApplicable"/> </Node> <!-- This node is used to represent an expression of a certain type, when attempting to bind its pattern dispose method It does not survive past initial binding. --> <Node Name="BoundDisposableValuePlaceholder" Base="BoundValuePlaceholderBase"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <!-- The implicit collection in an object or collection initializer expression. --> <Node Name="BoundObjectOrCollectionValuePlaceholder" Base="BoundValuePlaceholderBase"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="IsNewInstance" Type="bool" Null="NotApplicable"/> </Node> <!-- only used by codegen --> <Node Name="BoundDup" Base="BoundExpression"> <!-- when duplicating a local or parameter, must remember original ref kind --> <Field Name="RefKind" Type="RefKind" Null="NotApplicable"/> </Node> <!-- Wrapper node used to prevent passing the underlying expression by direct reference --> <Node Name="BoundPassByCopy" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression"/> </Node> <!-- An expression is classified as one of the following: A value. Every value has an associated type. A variable. Every variable has an associated type. A namespace. A type. A method group. ... A null literal. An anonymous function. A property access. An event access. An indexer access. Nothing. (An expression which is a method call that returns void.) --> <!-- This node is used when we can't create a real expression node because things are too broken. Example: lookup of a name fails to find anything. --> <Node Name="BoundBadExpression" Base="BoundExpression"> <!-- Categorizes the way in which "Symbols" is bad. --> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!-- These symbols will be returned from the GetSemanticInfo API if it examines this bound node. --> <Field Name="Symbols" Type="ImmutableArray&lt;Symbol?&gt;" SkipInNullabilityRewriter="true"/> <!-- Any child bound nodes that we need to preserve are put here. --> <Field Name="ChildBoundNodes" Type="ImmutableArray&lt;BoundExpression&gt;"/> </Node> <!-- This node is used when we can't create a real statement because things are too broken. --> <Node Name="BoundBadStatement" Base="BoundStatement"> <!-- Any child bound nodes that we need to preserve are put here. --> <Field Name="ChildBoundNodes" Type="ImmutableArray&lt;BoundNode&gt;"/> </Node> <!-- This node is used to wrap the BoundBlock for a finally extracted by AsyncExceptionHandlerRewriter. It is processed and removed by AsyncIteratorRewriter. --> <Node Name="BoundExtractedFinallyBlock" Base="BoundStatement"> <Field Name="FinallyBlock" Type="BoundBlock"/> </Node> <Node Name="BoundTypeExpression" Base="BoundExpression"> <Field Name="AliasOpt" Type="AliasSymbol?"/> <!-- We're going to stash some extra information in the Color Color case so that the binding API can return the correct information. Consider the following example: class C { public class Inner { public static C M() { return null; } } } class F { public C C; void M(C c) { M(/*<bind>*/C/*</bind>*/.Inner.M()); } } The bound tree for "C.Inner.M()" is a bound call with a bound type expression (C.Inner) as its receiver. However, there is no bound node corresponding to C. As a result, the semantic model will attempt to bind it and the binder will return F.C, since it will have no context. That's why we need to have a node for C in the (initial) bound tree. It could conceivably be useful to store other types of expressions as well (e.g. BoundNamespaceExpressions), but then it would be much harder to identify the scenarios in which this property is populated. --> <Field Name="BoundContainingTypeOpt" Type="BoundTypeExpression?"/> <!-- The provided dimensions in an array type expression where dimensions were provided in error. --> <Field Name="BoundDimensionsOpt" Type="ImmutableArray&lt;BoundExpression&gt;" Null="allow"/> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="TypeWithAnnotations" Type="TypeWithAnnotations"/> </Node> <!-- When binding "name1.name2" we normally can tell what name1 is. There is however a case where name1 could be either a value (field, property, parameter, local) or its type. This only happens if value named exactly the same as its type - famous "Color As Color". That alone is not enough to cause trouble as we can do a lookup for name2 and see if it requires a receiver (then name1 is a value) or if it does not (then name1 is a type). The problem only arises when name2 is an overloaded method or property. In such case we must defer type/value decision until overload resolution selects one of the candidates. As a result we need this node that represents name1 in the state where we only know its type and syntax, but do not know yet if it is a Type or Value. NOTE: * The node can only be a qualifier of a method or a property group access as only those may require overload resolution. * It is possible for a node of this type to appear in a tree where there are no errors. Consider (Color.M is Object). M may be overloaded to contain both static and instance methods. In this case the expression is always *false*, but the left-hand-side of the is operator is a method group whose receiver is a BoundTypeOrValueExpression. --> <Node Name="BoundTypeOrValueExpression" Base="BoundExpression"> <!-- Type is required for this node type; may not be null --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Data" Type="BoundTypeOrValueData"/> </Node> <Node Name="BoundNamespaceExpression" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <Field Name="NamespaceSymbol" Type="NamespaceSymbol"/> <Field Name="AliasOpt" Type="AliasSymbol?"/> </Node> <!-- EricLi thought we might need a node like this to do "Color Color" correctly. Currently we're handling that in a different way. Dev10 compiler had a node like this. [removed 3/30/2011 by petergo] <Node Name="BoundTypeOrName" Base="BoundExpression"> <Field Name="Type" Type="BoundTypeExpression"/> <Field Name="Name" Type="BoundExpression"/> </Node> --> <Node Name="BoundUnaryOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="OperatorKind" Type="UnaryOperatorKind"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <Field Name="MethodOpt" Type="MethodSymbol?"/> <Field Name="ConstrainedToTypeOpt" Type="TypeSymbol?" Null="allow"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!--The set of method symbols from which this operator's method was chosen. Only kept in the tree if the operator was an error and overload resolution was unable to choose a best method.--> <Field Name="OriginalUserDefinedOperatorsOpt" Type="ImmutableArray&lt;MethodSymbol&gt;" Null="Allow" SkipInNullabilityRewriter="true"/> </Node> <Node Name="BoundIncrementOperator" Base="BoundExpression"> <!-- x++ might need a conversion from the type of x to the operand type of the ++ operator (that produces the incremented value) and a conversion from the result of the ++ operator back to x. --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="OperatorKind" Type="UnaryOperatorKind"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="MethodOpt" Type="MethodSymbol?"/> <Field Name="ConstrainedToTypeOpt" Type="TypeSymbol?" Null="allow"/> <Field Name="OperandConversion" Type="Conversion"/> <Field Name="ResultConversion" Type="Conversion"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!--The set of method symbols from which this operator's method was chosen. Only kept in the tree if the operator was an error and overload resolution was unable to choose a best method.--> <Field Name="OriginalUserDefinedOperatorsOpt" Type="ImmutableArray&lt;MethodSymbol&gt;" Null="Allow" SkipInNullabilityRewriter="true"/> </Node> <!-- Not really an operator since overload resolution is never required. --> <Node Name="BoundAddressOfOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <!-- True only in some lowered/synthesized nodes. It suppresses conversion of operand reference to unmanaged pointer (which has effect of losing GC-tracking) NB: The language does not have a concept of managed pointers. However, managed (GC-tracked) pointers have some limited support at IL level and could be used in lowering of certain kinds of unsafe code - such as fixed field indexing. --> <Field Name="IsManaged" Type="bool"/> </Node> <!-- Represents an AddressOf operator that has not yet been assigned to a target-type. It has no natural type, and should not survive initial binding except in error cases that are observable via the SemanticModel. --> <Node Name="BoundUnconvertedAddressOfOperator" Base="BoundExpression"> <Field Name="Operand" Type="BoundMethodGroup"/> <!-- Type is null. --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> </Node> <!-- Represents a resolved AddressOf function pointer. Not used in initial binding. --> <Node Name="BoundFunctionPointerLoad" Base="BoundExpression"> <Field Name="TargetMethod" Type="MethodSymbol"/> <Field Name="ConstrainedToTypeOpt" Type="TypeSymbol?" Null="allow"/> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <Node Name="BoundPointerIndirectionOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> </Node> <Node Name="BoundPointerElementAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Expression" Type="BoundExpression"/> <Field Name="Index" Type="BoundExpression"/> <Field Name="Checked" Type="bool"/> </Node> <Node Name="BoundFunctionPointerInvocation" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="InvokedExpression" Type="BoundExpression"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind" /> </Node> <Node Name="BoundRefTypeOperator" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <!-- Well-known member populated during lowering --> <Field Name="GetTypeFromHandle" Type="MethodSymbol?"/> </Node> <Node Name="BoundMakeRefOperator" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> </Node> <Node Name="BoundRefValueOperator" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="NullableAnnotation" Type="NullableAnnotation" /> <Field Name="Operand" Type="BoundExpression"/> </Node> <Node Name="BoundFromEndIndexExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="MethodOpt" Type="MethodSymbol?"/> </Node> <Node Name="BoundRangeExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="LeftOperandOpt" Type="BoundExpression?"/> <Field Name="RightOperandOpt" Type="BoundExpression?"/> <Field Name="MethodOpt" Type="MethodSymbol?"/> </Node> <AbstractNode Name="BoundBinaryOperatorBase" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Left" Type="BoundExpression"/> <Field Name="Right" Type="BoundExpression"/> </AbstractNode> <Node Name="BoundBinaryOperator" Base="BoundBinaryOperatorBase" SkipInNullabilityRewriter="true"> <Field Name="OperatorKind" Type="BinaryOperatorKind"/> <Field Name="Data" Type="BoundBinaryOperator.UncommonData?" /> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> </Node> <Node Name="BoundTupleBinaryOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Left" Type="BoundExpression"/> <Field Name="Right" Type="BoundExpression"/> <Field Name="OperatorKind" Type="BinaryOperatorKind"/> <Field Name="Operators" Type="TupleBinaryOperatorInfo.Multiple"/> </Node> <Node Name="BoundUserDefinedConditionalLogicalOperator" Base="BoundBinaryOperatorBase" SkipInNullabilityRewriter="true"> <Field Name="OperatorKind" Type="BinaryOperatorKind"/> <Field Name="LogicalOperator" Type="MethodSymbol"/> <Field Name="TrueOperator" Type="MethodSymbol"/> <Field Name="FalseOperator" Type="MethodSymbol"/> <Field Name="ConstrainedToTypeOpt" Type="TypeSymbol?" Null="allow"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!--The set of method symbols from which this operator's method was chosen. Only kept in the tree if the operator was an error and overload resolution was unable to choose a best method.--> <Field Name="OriginalUserDefinedOperatorsOpt" Type="ImmutableArray&lt;MethodSymbol&gt;" Null="Allow" SkipInNullabilityRewriter="true"/> </Node> <Node Name="BoundCompoundAssignmentOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- A compound assignment operator has the following facts that must be deduced about it for codegen to work. Suppose you have shorts "x |= y;" That will be analyzed as "x = (short)(((int)x)|((int)y));" We need to know what the left hand and right hand sides are, what the binary operator is, how the left and right sides are converted to the types expected by the operator, whether the operator should check for overflow, and how the result of the binary operator is converted to the target variable's type. We'll lower this to operations on temporaries before codegen. Thought we can represent the operation as these seven facts, in fact we can conflate three of them. We need never do the right-hand-side-of-the-operator conversion during the rewrite. We can get away with binding the conversion on the right early and just having the converted right operand in the bound node. We also conflate whether we should check for overflow with the identity of the operator. This makes it a bit easier to handle the lambda case; when we have something like d += lambda, we want to represent the lambda in its bound form, not in its unbound form to be converted to the bound form later. This helps us maintain the invariant that non-error cases never produce an "unbound" lambda from the initial binding pass. --> <Field Name="Operator" Type="BinaryOperatorSignature" Null="NotApplicable"/> <Field Name="Left" Type="BoundExpression"/> <Field Name="Right" Type="BoundExpression"/> <Field Name="LeftConversion" Type="Conversion"/> <Field Name="FinalConversion" Type="Conversion"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!--The set of method symbols from which this operator's method was chosen. Only kept in the tree if the operator was an error and overload resolution was unable to choose a best method.--> <Field Name="OriginalUserDefinedOperatorsOpt" Type="ImmutableArray&lt;MethodSymbol&gt;" Null="Allow" SkipInNullabilityRewriter="true"/> </Node> <Node Name="BoundAssignmentOperator" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Left" Type="BoundExpression"/> <Field Name="Right" Type="BoundExpression" Null="NotApplicable"/> <!-- This is almost always false. In C# most assignments to a variable are simply writes to the logical variable. For example, when you say void M(ref int x){ x = C.y } that writes the value of C.y to the variable that x is an alias for. It does not write the address of C.y to the actual underlying storage of the parameter, which is of course actually a ref to an int variable. However, in some codegen scenarios we need to distinguish between a ref local assignment and a value assignment. When you say int s = 123; s+=10; then we generate that as int s = 123; ref int addr = ref s; int sum = addr + 10; addr = sum; Note that there are two assignment to addr; one assigns the address of s to addr; the other assigns the value of sum to s, indirectly through addr. We therefore need to disambiguate what kind of assignment we are doing based on something other than the refness of the left hand side. --> <Field Name="IsRef" Type="bool" Null="NotApplicable"/> </Node> <Node Name="BoundDeconstructionAssignmentOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Left" Type="BoundTupleExpression" Null="disallow"/> <Field Name="Right" Type="BoundConversion" Null="disallow"/> <Field Name="IsUsed" Type="bool" Null="NotApplicable"/> </Node> <Node Name="BoundNullCoalescingOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="LeftOperand" Type="BoundExpression"/> <Field Name="RightOperand" Type="BoundExpression"/> <Field Name="LeftConversion" Type="Conversion"/> <Field Name="OperatorResultKind" Type="BoundNullCoalescingOperatorResultKind" Null="NotApplicable"/> </Node> <Node Name="BoundNullCoalescingAssignmentOperator" Base="BoundExpression"> <Field Name="LeftOperand" Type="BoundExpression" /> <Field Name="RightOperand" Type="BoundExpression" /> </Node> <Node Name="BoundUnconvertedConditionalOperator" Base="BoundExpression"> <Field Name="Condition" Type="BoundExpression"/> <Field Name="Consequence" Type="BoundExpression"/> <Field Name="Alternative" Type="BoundExpression"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <Field Name="NoCommonTypeError" Type="ErrorCode"/> </Node> <Node Name="BoundConditionalOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="IsRef" Type="bool"/> <Field Name="Condition" Type="BoundExpression"/> <Field Name="Consequence" Type="BoundExpression"/> <Field Name="Alternative" Type="BoundExpression"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <Field Name="NaturalTypeOpt" Type="TypeSymbol?" Null="allow"/> <Field Name="WasTargetTyped" Type="bool" /> </Node> <Node Name="BoundArrayAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Expression" Type="BoundExpression"/> <Field Name="Indices" Type="ImmutableArray&lt;BoundExpression&gt;"/> </Node> <!-- Represents an operation that is special in both IL and Expression trees - getting length of a one-dimensional 0-based array (vector) This node should not be produced in initial binding since it is not a part of language (.Length is just a property on System.Array) and is normally introduced during the lowering phases. --> <Node Name="BoundArrayLength" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Expression" Type="BoundExpression"/> </Node> <Node Name="BoundAwaitableInfo" Base="BoundNode"> <!-- Used to refer to the awaitable expression in GetAwaiter --> <Field Name="AwaitableInstancePlaceholder" Type="BoundAwaitableValuePlaceholder?" Null="allow" /> <Field Name="IsDynamic" Type="bool"/> <Field Name="GetAwaiter" Type="BoundExpression?" Null="allow"/> <Field Name="IsCompleted" Type="PropertySymbol?" Null="allow"/> <Field Name="GetResult" Type="MethodSymbol?" Null="allow"/> </Node> <Node Name="BoundAwaitExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Expression" Type="BoundExpression"/> <Field Name="AwaitableInfo" Type="BoundAwaitableInfo" Null="disallow"/> </Node> <AbstractNode Name="BoundTypeOf" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- Well-known member populated during lowering --> <Field Name="GetTypeFromHandle" Type="MethodSymbol?"/> </AbstractNode> <Node Name="BoundTypeOfOperator" Base="BoundTypeOf"> <Field Name="SourceType" Type="BoundTypeExpression"/> </Node> <!-- Represents the raw metadata token index value for a method definition. Used by dynamic instrumentation to index into tables or arrays of per-method information. --> <Node Name="BoundMethodDefIndex" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Method" Type="MethodSymbol"/> </Node> <!-- Represents the maximum raw metadata token index value for any method definition in the current module. --> <Node Name="BoundMaximumMethodDefIndex" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <!-- Represents the dynamic analysis instrumentation payload array for the analysis kind in the current module. Implemented as a reference to a field of PrivateImplementationDetails, which has no language-level symbol. --> <Node Name="BoundInstrumentationPayloadRoot" Base="BoundExpression"> <Field Name="AnalysisKind" Type="int"/> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <!-- Represents the GUID that is the current module's MVID. Implemented as a reference to PrivateImplementationDetails.MVID, which has no language-level symbol. --> <Node Name="BoundModuleVersionId" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <!-- Represents a string encoding of the GUID that is the current module's MVID. Implemented as a reference to a string constant that is backpatched after the MVID is computed. --> <Node Name="BoundModuleVersionIdString" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <!-- Represents the index in the documents table of the source document containing a method definition. Used by dynamic instrumentation to identify the source document containing a method. --> <Node Name="BoundSourceDocumentIndex" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Document" Type="Cci.DebugSourceDocument"/> </Node> <Node Name="BoundMethodInfo" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Method" Type="MethodSymbol"/> <!-- Well-known member populated during lowering --> <Field Name="GetMethodFromHandle" Type="MethodSymbol?"/> </Node> <Node Name="BoundFieldInfo" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Field" Type="FieldSymbol"/> <!-- Well-known member populated during lowering --> <Field Name="GetFieldFromHandle" Type="MethodSymbol?"/> </Node> <!-- Default literals can convert to the target type. Does not survive initial lowering. --> <Node Name="BoundDefaultLiteral" Base="BoundExpression"> <!-- Type is null. --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> </Node> <!-- The default expression is `default(T)` expression or `default` literal which has been already converted to a target type. --> <Node Name="BoundDefaultExpression" Base="BoundExpression"> <!-- Converted default expression must have a type. --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="TargetType" Type="BoundTypeExpression?" SkipInVisitor="true"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> </Node> <Node Name="BoundIsOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="TargetType" Type="BoundTypeExpression"/> <Field Name="Conversion" Type="Conversion"/> </Node> <Node Name="BoundAsOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="TargetType" Type="BoundTypeExpression"/> <Field Name="Conversion" Type="Conversion"/> </Node> <Node Name="BoundSizeOfOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="SourceType" Type="BoundTypeExpression"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> </Node> <Node Name="BoundConversion" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="Conversion" Type="Conversion"/> <Field Name="IsBaseConversion" Type="bool"/> <Field Name="Checked" Type="bool"/> <Field Name="ExplicitCastInCode" Type="bool"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <!-- A group instance common to all BoundConversions that represent a single Conversion. The field is used in NullableWalker to identify the chained conversions in user-defined conversions in particular. For instance, with the following declarations, an explicit conversion from B to D: expr -> ImplicitReference conversion -> ExplicitUserDefined conversion -> ExplicitReference conversion. class A { public static explicit operator C(A a) => new D(); } class B : A { } class C { } class D : C { } ConversionGroupOpt also contains the target type specified in source in the case of explicit conversions. ConversionGroupOpt may be null for implicit conversions if the Conversion is represented by a single BoundConversion. --> <Field Name="ConversionGroupOpt" Type="ConversionGroup?"/> <!--The set of method symbols from which this conversion's method was chosen. Only kept in the tree if the conversion was an error and overload resolution was unable to choose a best method.--> <Field Name="OriginalUserDefinedConversionsOpt" Type="ImmutableArray&lt;MethodSymbol&gt;" Null="Allow" SkipInNullabilityRewriter="true"/> </Node> <!-- A special node for emitting the implicit conversion from an array (of T) to System.ReadOnlySpan<T>. Although the conversion has an explicitly declared conversion operator, we want to retain it as something other than a method call after lowering so it can be recognized as a special case and possibly optimized during code generation. --> <Node Name="BoundReadOnlySpanFromArray" Base="BoundExpression"> <!-- The type is required to be an instance of the well-known type System.ReadOnlySpan<T> --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="ConversionMethod" Type="MethodSymbol"/> </Node> <!-- <Node Name="BoundRefValueOperator" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="SourceType" Type="BoundTypeExpression"/> </Node> --> <Node Name="BoundArgList" Base="BoundExpression"> <!-- This is the "__arglist" expression that may appear inside a varargs method. --> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <Node Name="BoundArgListOperator" Base="BoundExpression"> <!-- This is the "__arglist(x, y, z)" expression that may appear in a call to a varargs method. --> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol?" Override="true"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> </Node> <!-- Used when a fixed statement local is initialized with either a string or an array. Encapsulates extra info that will be required during rewriting. --> <Node Name="BoundFixedLocalCollectionInitializer" Base="BoundExpression"> <!-- Either string or an array type. --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- char* for type string, T* for type T[]. --> <Field Name="ElementPointerType" Type="TypeSymbol" Null="disallow"/> <!-- Conversion from ElementPointerType to the type of the corresponding local. --> <Field Name="ElementPointerTypeConversion" Type="Conversion"/> <!-- Wrapped expression. --> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> <!-- optional method that returns a pinnable reference for the instance --> <Field Name="GetPinnableOpt" Type="MethodSymbol?"/> </Node> <AbstractNode Name="BoundStatement" Base="BoundNode"/> <Node Name="BoundSequencePoint" Base="BoundStatement"> <!-- if Statement is null, a NOP may be emitted, to make sure the point is not associated with next statement (which could be a fairly random statement in random scope). --> <Field Name="StatementOpt" Type="BoundStatement?"/> </Node> <!--EDMAURER Use this in the event that the span you must represent is not that of a SyntaxNode. If a SyntaxNode captures the correct span, use a BoundSequencePoint.--> <Node Name="BoundSequencePointWithSpan" Base="BoundStatement"> <!-- if Statement is null, a NOP may be emitted, to make sure the point is not associated with next statement (which could be a fairly random statement in random scope). --> <Field Name="StatementOpt" Type="BoundStatement?"/> <Field Name="Span" Type="TextSpan"/> </Node> <!-- This is used to save the debugger's idea of what the enclosing sequence point is at this location in the code so that it can be restored later by a BoundRestorePreviousSequencePoint node. When this statement appears, the previous non-hidden sequence point is saved and associated with the given Identifier. --> <Node Name="BoundSavePreviousSequencePoint" Base="BoundStatement"> <Field Name="Identifier" Type="object"/> </Node> <!-- This is used to restore the debugger's idea of what the enclosing statement is to some previous location without introducing a place where a breakpoint would cause the debugger to stop. The identifier must have previously been given in a BoundSavePreviousSequencePoint statement. This is used to implement breakpoints within expressions (e.g. a switch expression). --> <Node Name="BoundRestorePreviousSequencePoint" Base="BoundStatement"> <Field Name="Identifier" Type="object"/> </Node> <!-- This is used to set the debugger's idea of what the enclosing statement is without causing the debugger to stop here when single stepping. --> <Node Name="BoundStepThroughSequencePoint" Base="BoundStatement"> <Field Name="Span" Type="TextSpan"/> </Node> <!-- BoundBlock contains a) Statements - actions performed within the scope of the block b) Locals - local variable symbols that are visible within the scope of the block BoundBlock specify SCOPE (visibility) of a variable. TODO: it appears in C#, variable's extent (life time) never escapes its scope. Is that always guaranteed or there are exceptions? Note - in VB variable's extent is the whole method and can be larger than its scope. That is why unassigned use is just a warning and jumps into blocks are generally allowed. --> <Node Name="BoundBlock" Base="BoundStatementList"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="LocalFunctions" Type="ImmutableArray&lt;LocalFunctionSymbol&gt;"/> </Node> <!-- This node is used to represent a visibility scope for locals, for which lifetime is extended beyond the visibility scope. At the moment, only locals declared within CaseSwitchLabelSyntax and SwitchExpressionSyntax have their lifetime expanded to the entire switch body, whereas their visibility scope is the declaring switch section. The node is added into the tree during lowering phase. --> <Node Name="BoundScope" Base="BoundStatementList"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> </Node> <!-- BoundStateMachineScope represents a scope within a translated iterator/async method. It is used to emit debugging information that allows the EE to map fields to locals. --> <Node Name="BoundStateMachineScope" Base="BoundStatement"> <Field Name="Fields" Type="ImmutableArray&lt;StateMachineFieldSymbol&gt;"/> <Field Name="Statement" Type="BoundStatement" Null="disallow"/> </Node> <!-- Bound node that represents a single local declaration: int x = Foo(); NOTE: The node does NOT introduce the referenced local into surrounding scope. A local must be explicitly declared in a BoundBlock to be usable inside it. NOTE: In an error recovery scenario we might have a local declaration parsed as int x[123] - This is an error commonly made by C++ developers who come to C#. We will give a good error about it at parse time, but we should preserve the semantic analysis of the argument list in the bound tree. --> <Node Name="BoundLocalDeclaration" Base="BoundStatement"> <Field Name="LocalSymbol" Type="LocalSymbol"/> <!-- Only set for the first declaration in BoundMultipleLocalDeclarations unless the type is inferred --> <Field Name="DeclaredTypeOpt" Type="BoundTypeExpression?"/> <Field Name="InitializerOpt" Type="BoundExpression?"/> <Field Name="ArgumentsOpt" Type="ImmutableArray&lt;BoundExpression&gt;" Null="allow"/> <!-- Was the type inferred via "var"? --> <Field Name="InferredType" Type="bool"/> </Node> <!-- Base node shared by BoundMultipleLocalDeclarations and BoundUsingLocalDeclarations --> <AbstractNode Name="BoundMultipleLocalDeclarationsBase" Base="BoundStatement"> <Field Name="LocalDeclarations" Type="ImmutableArray&lt;BoundLocalDeclaration&gt;"/> </AbstractNode> <!-- Bound node that represents multiple local declarations: int x =1, y =2; Works like multiple BoundLocalDeclaration nodes. --> <Node Name="BoundMultipleLocalDeclarations" Base="BoundMultipleLocalDeclarationsBase" /> <!-- Bound node that represents a using local declaration [async] using var x = ..., y = ...; --> <Node Name="BoundUsingLocalDeclarations" Base="BoundMultipleLocalDeclarationsBase"> <Field Name="PatternDisposeInfoOpt" Type="MethodArgumentInfo?"/> <Field Name="IDisposableConversion" Type="Conversion"/> <Field Name="AwaitOpt" Type="BoundAwaitableInfo?"/> </Node> <!-- Bound node that represents a local function declaration: void Foo() { } --> <Node Name="BoundLocalFunctionStatement" Base="BoundStatement"> <Field Name="Symbol" Type="LocalFunctionSymbol"/> <Field Name="BlockBody" Type="BoundBlock?"/> <Field Name="ExpressionBody" Type="BoundBlock?"/> </Node> <Node Name="BoundNoOpStatement" Base="BoundStatement"> <!-- No operation. Empty statement. --> <!-- BoundNoOpStatement node may serve as a vehicle for passing some internal information between lowering phases and/or codegen; for example, async rewriter needs to mark some particular places in the emitted code so that we could emit proper PDB information for generated methods. --> <Field Name="Flavor" Type="NoOpStatementFlavor"/> </Node> <Node Name="BoundReturnStatement" Base="BoundStatement"> <Field Name="RefKind" Type="RefKind"/> <Field Name="ExpressionOpt" Type="BoundExpression?"/> </Node> <Node Name="BoundYieldReturnStatement" Base="BoundStatement"> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> </Node> <Node Name="BoundYieldBreakStatement" Base="BoundStatement"/> <Node Name="BoundThrowStatement" Base="BoundStatement"> <Field Name="ExpressionOpt" Type="BoundExpression?"/> </Node> <Node Name="BoundExpressionStatement" Base="BoundStatement"> <Field Name="Expression" Type="BoundExpression"/> </Node> <Node Name="BoundBreakStatement" Base="BoundStatement"> <Field Name="Label" Type="GeneratedLabelSymbol" /> </Node> <Node Name="BoundContinueStatement" Base="BoundStatement"> <Field Name="Label" Type="GeneratedLabelSymbol" /> </Node> <Node Name="BoundSwitchStatement" Base="BoundStatement"> <Field Name="Expression" Type="BoundExpression"/> <!-- Locals declared immediately within the switch block. --> <Field Name="InnerLocals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="InnerLocalFunctions" Type="ImmutableArray&lt;LocalFunctionSymbol&gt;"/> <Field Name="SwitchSections" Type="ImmutableArray&lt;BoundSwitchSection&gt;"/> <Field Name="DecisionDag" Type="BoundDecisionDag" Null="disallow" SkipInVisitor="true"/> <Field Name="DefaultLabel" Type="BoundSwitchLabel?"/> <Field Name="BreakLabel" Type="GeneratedLabelSymbol"/> </Node> <!-- Part of a lowered integral switch statement. This evaluates Value, and then branches to the corresponding Target. If no Value is equal to the input, branches to the default label. The input Value and the constants must be of the same type. Currently emit only supports integral types and string. BoundSwitchDispatch is also used to mark labels in the code that will be the target of backward branches, but should be treated as having the same stack depth as the location where the BoundForwardLabels appears. Although we will necessarily produce some IL instructions for this in order to comply with the verifier constraints, the effect of the code shall be a no-op. The form of the code produced will likely be something of the form ldc.i4.m1 // load constant -1 switch ( IL_nnnn, // all of the labels of interest IL_nnnn, IL_nnnn) This is needed for the lowering of the pattern switch expression, which produces a state machine that may contain backward branches. Due to the fact that it is an expression, it may appear where the stack is not empty. A BoundSwitchDispatch statement (used inside of a BoundSequence containing the state machine) permits us to (cause the verifier to) classify all of the labels as forward labels by producing a dummy inoperable forward jump to them. --> <Node Name="BoundSwitchDispatch" Base="BoundStatement"> <Field Name="Expression" Type="BoundExpression" Null="disallow" /> <Field Name="Cases" Type="ImmutableArray&lt;(ConstantValue value, LabelSymbol label)&gt;" /> <Field Name="DefaultLabel" Type="LabelSymbol" Null="disallow" /> <!-- Equality method to be used when dispatching on a non-integral type such as string. --> <Field Name="EqualityMethod" Type="MethodSymbol?" /> </Node> <Node Name="BoundIfStatement" Base="BoundStatement"> <Field Name="Condition" Type="BoundExpression"/> <Field Name="Consequence" Type="BoundStatement"/> <Field Name="AlternativeOpt" Type="BoundStatement?"/> </Node> <AbstractNode Name="BoundLoopStatement" Base="BoundStatement"> <Field Name="BreakLabel" Type="GeneratedLabelSymbol"/> <Field Name="ContinueLabel" Type="GeneratedLabelSymbol"/> </AbstractNode> <AbstractNode Name="BoundConditionalLoopStatement" Base="BoundLoopStatement"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="Condition" Type="BoundExpression"/> <Field Name="Body" Type="BoundStatement"/> </AbstractNode> <Node Name="BoundDoStatement" Base="BoundConditionalLoopStatement"> </Node> <Node Name="BoundWhileStatement" Base="BoundConditionalLoopStatement"> </Node> <Node Name="BoundForStatement" Base="BoundLoopStatement"> <!-- OuterLocals are the locals declared within the loop Initializer statement and are in scope throughout the whole loop statement --> <Field Name="OuterLocals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="Initializer" Type="BoundStatement?"/> <!-- InnerLocals are the locals declared within the loop Condition and are in scope throughout the Condition, Increment and Body. They are considered to be declared per iteration. --> <Field Name="InnerLocals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="Condition" Type="BoundExpression?"/> <Field Name="Increment" Type="BoundStatement?"/> <Field Name="Body" Type="BoundStatement"/> </Node> <Node Name="BoundForEachStatement" Base="BoundLoopStatement"> <!-- Extracted information --> <Field Name="EnumeratorInfoOpt" Type="ForEachEnumeratorInfo?"/> <Field Name="ElementConversion" Type="Conversion"/> <!-- Pieces corresponding to the syntax --> <!-- This is so the binding API can find produce semantic info if the type is "var". --> <!-- If there is a deconstruction, there will be no iteration variable (but we'll still have a type for it). --> <Field Name="IterationVariableType" Type="BoundTypeExpression"/> <Field Name="IterationVariables" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <!-- In error scenarios where the iteration variable is some arbitrary expression, we stick the error recovery in this node. This will always be null in valid code. --> <Field Name="IterationErrorExpressionOpt" Type="BoundExpression?"/> <!-- If this node does not have errors, then this is the foreach expression wrapped in a conversion to the collection type used by the foreach loop. The conversion is here so that the binding API can return the correct ConvertedType in semantic info. It will be stripped off in the rewriter if it is redundant or causes extra boxing. If this node has errors, then the conversion may not be present.--> <Field Name="Expression" Type="BoundExpression"/> <Field Name="DeconstructionOpt" Type="BoundForEachDeconstructStep?"/> <Field Name="AwaitOpt" Type="BoundAwaitableInfo?"/> <Field Name="Body" Type="BoundStatement"/> <Field Name="Checked" Type="bool"/> </Node> <!-- All the information need to apply a deconstruction at each iteration of a foreach loop involving a deconstruction-declaration. --> <Node Name="BoundForEachDeconstructStep" Base="BoundNode"> <Field Name="DeconstructionAssignment" Type="BoundDeconstructionAssignmentOperator" Null="disallow"/> <Field Name="TargetPlaceholder" Type="BoundDeconstructValuePlaceholder" Null="disallow"/> </Node> <Node Name="BoundUsingStatement" Base="BoundStatement"> <!-- DeclarationsOpt and ExpressionOpt cannot both be non-null. --> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="DeclarationsOpt" Type="BoundMultipleLocalDeclarations?"/> <Field Name="ExpressionOpt" Type="BoundExpression?"/> <Field Name="IDisposableConversion" Type="Conversion" /> <Field Name="Body" Type="BoundStatement"/> <Field Name="AwaitOpt" Type="BoundAwaitableInfo?"/> <Field Name="PatternDisposeInfoOpt" Type="MethodArgumentInfo?"/> </Node> <Node Name="BoundFixedStatement" Base="BoundStatement"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="Declarations" Type="BoundMultipleLocalDeclarations"/> <Field Name="Body" Type="BoundStatement"/> </Node> <Node Name="BoundLockStatement" Base="BoundStatement"> <Field Name="Argument" Type="BoundExpression"/> <Field Name="Body" Type="BoundStatement"/> </Node> <Node Name="BoundTryStatement" Base="BoundStatement"> <Field Name="TryBlock" Type="BoundBlock"/> <Field Name="CatchBlocks" Type="ImmutableArray&lt;BoundCatchBlock&gt;"/> <Field Name="FinallyBlockOpt" Type="BoundBlock?"/> <!-- When lowering trys, we sometimes extract the finally clause out of the try. For example, `try { } finally { await expr; }` becomes something like `try { } catch { ... } finallyLabel: { await expr; ... }`. We need to save the label for the finally so that async-iterator rewriting can implement proper disposal. --> <Field Name="FinallyLabelOpt" Type="LabelSymbol?"/> <!-- PreferFaultHandler is a hint to the codegen to emit Finally in the following shape - try { } fault { finallyBlock } finallyBlock This pattern preserves semantics of Finally while not using finally handler. As a result any kind of analysis can continue treating Finally blocks as Finally blocks. NOTE!! When Fault emit is used - 1) The code is emitted twice 2) The second copy is outside of a handler block. 3) Branches out of the try will NOT be intercepted by the surrogate finally. User of this flag must ensure that the above caveats are acceptable. For example when this flag is used in Iterator rewrite, the second copy is always unreachable and not intercepting the return is intended behavior since the only branch out of Iterator body is "goto exitLabel". --> <Field Name="PreferFaultHandler" Type="bool"/> </Node> <Node Name="BoundCatchBlock" Base="BoundNode"> <!-- Local symbols owned by the catch block. Empty if the catch syntax doesn't declare a local variable. In the initial bound tree the first variable is the exception variable (if present). After the node is lowered the exception variable might become a field and will be removed from the array, otherwise it will stay at the first position. --> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <!-- Refers to the location where the exception object is stored. The expression is a local or a BoundSequence, whose last expression refers to the location of the exception object and the sideeffects initialize its storage (e.g. if the catch identifier is lifted into a closure the sideeffects initialize the closure). Null if the exception object is not referred to. --> <Field Name="ExceptionSourceOpt" Type="BoundExpression?"/> <Field Name="ExceptionTypeOpt" Type="TypeSymbol?"/> <Field Name="ExceptionFilterPrologueOpt" Type="BoundStatementList?"/> <Field Name="ExceptionFilterOpt" Type="BoundExpression?"/> <Field Name="Body" Type="BoundBlock"/> <Field Name="IsSynthesizedAsyncCatchAll" Type="bool" /> </Node> <Node Name="BoundLiteral" Base="BoundExpression"> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> </Node> <Node Name="BoundThisReference" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- Note that "this" is classified as a variable in some scenarios. We'll treat it as a value generally and special-case those cases. --> </Node> <Node Name="BoundPreviousSubmissionReference" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <Node Name="BoundHostObjectMemberReference" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <Node Name="BoundBaseReference" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" /> </Node> <Node Name="BoundLocal" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="LocalSymbol" Type="LocalSymbol"/> <Field Name="DeclarationKind" Type="BoundLocalDeclarationKind" Null="NotApplicable"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <!-- True if LocalSymbol.Type.IsNullable could not be inferred. --> <Field Name="IsNullableUnknown" Type="bool"/> </Node> <Node Name="BoundPseudoVariable" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="LocalSymbol" Type="LocalSymbol" Null="disallow"/> <Field Name="EmitExpressions" Type ="PseudoVariableExpressions" Null="disallow"/> </Node> <Node Name="BoundRangeVariable" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="RangeVariableSymbol" Type="RangeVariableSymbol"/> <Field Name="Value" Type="BoundExpression"/> </Node> <Node Name="BoundParameter" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ParameterSymbol" Type="ParameterSymbol"/> </Node> <Node Name="BoundLabelStatement" Base="BoundStatement"> <!-- A label is not actually a statement but it is convenient to model it as one because then you can do rewrites without having to know "what comes next". For example suppose you have statement list A(); if(B()) C(); else D(); E(); If you are rewriting the "if" then it is convenient to be able to rewrite it as GotoIfFalse B() LabElse C(); Goto LabDone LabElse D(); LabDone without having to rewrite E(); as a labeled statement. Note that this statement represents the label itself as a "stand-alone" statement, unattached to any other statement. Rewriting will remove this statement and replace it with a LabeledStatement, that references both this LabelSymbol and the specific other statement it actually labels. --> <Field Name="Label" Type="LabelSymbol"/> </Node> <Node Name="BoundGotoStatement" Base="BoundStatement"> <Field Name="Label" Type="LabelSymbol"/> <Field Name="CaseExpressionOpt" Type="BoundExpression?"/> <Field Name="LabelExpressionOpt" Type="BoundLabel?"/> </Node> <!-- This represents a statement which has been labeled. This allows us to recursively bind the labeled expression during binding. --> <Node Name="BoundLabeledStatement" Base="BoundStatement"> <Field Name="Label" Type="LabelSymbol"/> <Field Name="Body" Type="BoundStatement"/> </Node> <!-- This represents the bound form of a label reference (i.e. in a goto). It is only used for the SemanticModel API. --> <Node Name="BoundLabel" Base="BoundExpression"> <Field Name="Label" Type="LabelSymbol"/> </Node> <Node Name="BoundStatementList" Base="BoundStatement"> <!-- A statement list is produced by a rewrite that turns one statement into multiple statements. It does not have the semantics of a block. --> <Field Name="Statements" Type="ImmutableArray&lt;BoundStatement&gt;"/> </Node> <Node Name="BoundConditionalGoto" Base="BoundStatement"> <!-- A compiler-generated conditional goto - jumps if condition == JumpIfTrue --> <Field Name="Condition" Type="BoundExpression"/> <Field Name="JumpIfTrue" Type="bool"/> <Field Name="Label" Type="LabelSymbol"/> </Node> <AbstractNode Name="BoundSwitchExpression" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> <Field Name="SwitchArms" Type="ImmutableArray&lt;BoundSwitchExpressionArm&gt;"/> <Field Name="DecisionDag" Type="BoundDecisionDag" Null="disallow" SkipInVisitor="true"/> <Field Name="DefaultLabel" Type="LabelSymbol?"/> <Field Name="ReportedNotExhaustive" Type="bool"/> </AbstractNode> <Node Name="BoundSwitchExpressionArm" Base="BoundNode"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="Pattern" Type="BoundPattern" Null="disallow"/> <Field Name="WhenClause" Type="BoundExpression?"/> <Field Name="Value" Type="BoundExpression" Null="disallow"/> <Field Name="Label" Type="LabelSymbol" Null="disallow"/> </Node> <Node Name="BoundUnconvertedSwitchExpression" Base="BoundSwitchExpression"> </Node> <!-- Switch expressions can convert to the target type. Once converted to a target type, they cannot be target-typed again. The Converted switch expression is one which has been already converted to a target type. Converted switch expressions always have a type. --> <Node Name="BoundConvertedSwitchExpression" Base="BoundSwitchExpression"> <!-- Converted switch expression must have a type, even if that's an error type. --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- Natural type is preserved for the purpose of semantic model. Can be `null`. --> <Field Name="NaturalTypeOpt" Type="TypeSymbol?" Null="allow"/> <Field Name="WasTargetTyped" Type="bool" /> <!-- The conversion to Type. Either a switch expression conversion or an identity conversion --> <Field Name="Conversion" Type="Conversion"/> </Node> <Node Name="BoundDecisionDag" Base="BoundNode"> <Field Name="RootNode" Type="BoundDecisionDagNode" Null="disallow"/> </Node> <AbstractNode Name="BoundDecisionDagNode" Base="BoundNode"> </AbstractNode> <!-- This node is used to indicate a point in the decision dag where an evaluation is performed, such as invoking Deconstruct. --> <Node Name="BoundEvaluationDecisionDagNode" Base="BoundDecisionDagNode"> <Field Name="Evaluation" Type="BoundDagEvaluation" Null="disallow"/> <Field Name="Next" Type="BoundDecisionDagNode" Null="disallow"/> </Node> <!-- This node is used to indicate a point in the decision dag where a test may change the path of the decision dag. --> <Node Name="BoundTestDecisionDagNode" Base="BoundDecisionDagNode"> <Field Name="Test" Type="BoundDagTest" Null="disallow"/> <Field Name="WhenTrue" Type="BoundDecisionDagNode" Null="disallow"/> <Field Name="WhenFalse" Type="BoundDecisionDagNode" Null="disallow"/> </Node> <Node Name="BoundWhenDecisionDagNode" Base="BoundDecisionDagNode"> <Field Name="Bindings" Type="ImmutableArray&lt;BoundPatternBinding&gt;" Null="disallow"/> <!-- WhenExpression is null when there was no when clause in source but there are bindings. In that case WhenFalse is null. --> <Field Name="WhenExpression" Type="BoundExpression?"/> <Field Name="WhenTrue" Type="BoundDecisionDagNode" Null="disallow"/> <Field Name="WhenFalse" Type="BoundDecisionDagNode?"/> </Node> <!-- This node is used to indicate a point in the decision dag where the decision has been completed. --> <Node Name="BoundLeafDecisionDagNode" Base="BoundDecisionDagNode"> <Field Name="Label" Type="LabelSymbol"/> </Node> <AbstractNode Name="BoundDagTest" Base="BoundNode"> Input is the input to the decision point. <Field Name="Input" Type="BoundDagTemp"/> </AbstractNode> <Node Name="BoundDagTemp" Base="BoundNode"> <Field Name="Type" Type="TypeSymbol" Null="disallow"/> <Field Name="Source" Type="BoundDagEvaluation?"/> <Field Name="Index" Type="int"/> </Node> <Node Name="BoundDagTypeTest" Base="BoundDagTest"> <!--Check that the input is of the given type. Null check is separate.--> <Field Name="Type" Type="TypeSymbol" Null="disallow"/> </Node> <Node Name="BoundDagNonNullTest" Base="BoundDagTest"> <!--Check that the input is not null. Used as part of a type test.--> <Field Name="IsExplicitTest" Type="bool"/> </Node> <Node Name="BoundDagExplicitNullTest" Base="BoundDagTest"> <!--Check that the input is null. Used when an explicit null test appears in source.--> </Node> <Node Name="BoundDagValueTest" Base="BoundDagTest"> <!--Check that the input is the same as the given constant value (other than null).--> <Field Name="Value" Type="ConstantValue" Null="disallow"/> </Node> <Node Name="BoundDagRelationalTest" Base="BoundDagTest"> <!--Check that the input is related to (equal, not equal, less, less or equal, greater, greater or equal) the given constant value (other than null).--> <Field Name="OperatorKind" Type="BinaryOperatorKind"/> <Field Name="Value" Type="ConstantValue" Null="disallow"/> </Node> <!-- As a decision, an evaluation is considered to always succeed. --> <AbstractNode Name="BoundDagEvaluation" Base="BoundDagTest"> </AbstractNode> <Node Name="BoundDagDeconstructEvaluation" Base="BoundDagEvaluation"> <Field Name="DeconstructMethod" Type="MethodSymbol" Null="disallow"/> </Node> <Node Name="BoundDagTypeEvaluation" Base="BoundDagEvaluation"> <!--Cast to the given type, assumed to be used after a successful type check.--> <Field Name="Type" Type="TypeSymbol" Null="disallow"/> </Node> <Node Name="BoundDagFieldEvaluation" Base="BoundDagEvaluation"> <Field Name="Field" Type="FieldSymbol" Null="disallow"/> </Node> <Node Name="BoundDagPropertyEvaluation" Base="BoundDagEvaluation"> <Field Name="Property" Type="PropertySymbol" Null="disallow"/> </Node> <Node Name="BoundDagIndexEvaluation" Base="BoundDagEvaluation"> <Field Name="Property" Type="PropertySymbol" Null="disallow"/> <Field Name="Index" Type="int"/> </Node> <Node Name="BoundSwitchSection" Base="BoundStatementList"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="SwitchLabels" Type="ImmutableArray&lt;BoundSwitchLabel&gt;"/> </Node> <Node Name="BoundSwitchLabel" Base="BoundNode"> <Field Name="Label" Type="LabelSymbol"/> <Field Name="Pattern" Type="BoundPattern"/> <Field Name="WhenClause" Type="BoundExpression?"/> </Node> <AbstractNode Name="BoundMethodOrPropertyGroup" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <!--We wish to keep the left-hand-side of the member access in the method group even if the *instance* expression ought to be null. For example, if we have System.Console.WriteLine then we want to keep the System.Console type expression as the receiver, even though the spec says that the instance expression is null in this case. We'll add a helper property that gets the instance expression from the receiver should we need it. --> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> </AbstractNode> <!-- Use this in the event that the sequence point must be applied to expression.--> <Node Name="BoundSequencePointExpression" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> </Node> <!-- A node specially to represent the idea of "compute this side effects while discarding results, and then compute this value" The node may also declare locals (temporaries). The sequence node is both SCOPE and EXTENT of these locals. As a result non-intersecting sequences can reuse variable slots. --> <Node Name="BoundSequence" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="SideEffects" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="Value" Type="BoundExpression"/> </Node> <!-- Like BoundSequence, but the side-effects are statements. This node is produced during initial lowering for the `await` expression and for the switch expression. A separate pass removes these nodes by moving the statements to the top level (i.e. to a statement list that is not in a BoundSpillSequence). It is called a spill sequence because the process of moving it to the top level causes values that would be on the stack during its evaluation to be spilled to temporary variables. --> <Node Name="BoundSpillSequence" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="SideEffects" Type="ImmutableArray&lt;BoundStatement&gt;"/> <Field Name="Value" Type="BoundExpression"/> </Node> <Node Name="BoundDynamicMemberAccess" Base="BoundExpression"> <!--Non-null type is required, and will always be "dynamic". --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Receiver" Type="BoundExpression"/> <Field Name="TypeArgumentsOpt" Type="ImmutableArray&lt;TypeWithAnnotations&gt;" Null="allow"/> <Field Name="Name" Type="string" Null="disallow"/> <!-- TODO (tomat): do we really need these flags here? it should be possible to infer them from the context --> <Field Name="Invoked" Type="bool"/> <Field Name="Indexed" Type="bool"/> </Node> <AbstractNode Name="BoundDynamicInvocableBase" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> </AbstractNode> <Node Name="BoundDynamicInvocation" Base="BoundDynamicInvocableBase"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <!-- If the receiver is statically typed the set of applicable methods that may be invoked at runtime. Empty otherwise. --> <Field Name="ApplicableMethods" Type="ImmutableArray&lt;MethodSymbol&gt;" /> </Node> <Node Name="BoundConditionalAccess" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Receiver" Type="BoundExpression"/> <Field Name="AccessExpression" Type="BoundExpression"/> </Node> <Node Name="BoundLoweredConditionalAccess" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Receiver" Type="BoundExpression"/> <Field Name="HasValueMethodOpt" Type="MethodSymbol?"/> <Field Name="WhenNotNull" Type="BoundExpression"/> <Field Name="WhenNullOpt" Type="BoundExpression?"/> <!-- Async rewriter needs to replace receivers with their spilled values and for that it needs to match receivers and the containing conditional expressions. To be able to do that, during lowering, we will assign BoundLoweredConditionalAccess and corresponding BoundConditionalReceiver matching Id that are integers unique for the containing method body. --> <Field Name="Id" Type="int"/> </Node> <!-- represents the receiver of a conditional access expression --> <Node Name="BoundConditionalReceiver" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- See the comment in BoundLoweredConditionalAccess --> <Field Name="Id" Type="int"/> </Node> <!-- This node represents a complex receiver for a conditional access. At runtime, when its type is a value type, ValueTypeReceiver should be used as a receiver. Otherwise, ReferenceTypeReceiver should be used. This kind of receiver is created only by Async rewriter. --> <Node Name="BoundComplexConditionalReceiver" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ValueTypeReceiver" Type="BoundExpression" Null="disallow"/> <Field Name="ReferenceTypeReceiver" Type="BoundExpression" Null="disallow"/> </Node> <Node Name="BoundMethodGroup" Base="BoundMethodOrPropertyGroup"> <!-- SPEC: A method group is a set of overloaded methods resulting from a member lookup. SPEC: A method group may have an associated instance expression and SPEC: an associated type argument list. --> <Field Name="TypeArgumentsOpt" Type="ImmutableArray&lt;TypeWithAnnotations&gt;" Null="allow"/> <Field Name="Name" Type="string" Null="disallow"/> <Field Name="Methods" Type="ImmutableArray&lt;MethodSymbol&gt;" /> <Field Name="LookupSymbolOpt" Type="Symbol?"/> <Field Name="LookupError" Type="DiagnosticInfo?"/> <Field Name="Flags" Type="BoundMethodGroupFlags?"/> </Node> <Node Name="BoundPropertyGroup" Base="BoundMethodOrPropertyGroup"> <Field Name="Properties" Type="ImmutableArray&lt;PropertySymbol&gt;" /> </Node> <Node Name="BoundCall" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="Method" Type="MethodSymbol"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="IsDelegateCall" Type="bool"/> <Field Name="Expanded" Type="bool"/> <Field Name="InvokedAsExtensionMethod" Type="bool"/> <Field Name="ArgsToParamsOpt" Type="ImmutableArray&lt;int&gt;" Null="allow"/> <Field Name="DefaultArguments" Type="BitVector" /> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!--The set of method symbols from which this call's method was chosen. Only kept in the tree if the call was an error and overload resolution was unable to choose a best method.--> <Field Name="OriginalMethodsOpt" Type="ImmutableArray&lt;MethodSymbol&gt;" Null="Allow" SkipInNullabilityRewriter="true"/> </Node> <Node Name="BoundEventAssignmentOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Event" Type="EventSymbol"/> <Field Name="IsAddition" Type="bool"/> <Field Name="IsDynamic" Type="bool"/> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="Argument" Type="BoundExpression"/> </Node> <Node Name="BoundAttribute" Base="BoundExpression"> <!-- Type is required for this node type; may not be null --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Constructor" Type="MethodSymbol?"/> <Field Name="ConstructorArguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ConstructorArgumentNamesOpt" Type="ImmutableArray&lt;string?&gt;" Null="allow"/> <Field Name="ConstructorArgumentsToParamsOpt" Type="ImmutableArray&lt;int&gt;" Null="allow"/> <Field Name="ConstructorExpanded" Type="bool" /> <Field Name="NamedArguments" Type ="ImmutableArray&lt;BoundAssignmentOperator&gt;"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> </Node> <!-- This node is used to represent a target-typed object creation expression It does not survive past initial binding. --> <Node Name="BoundUnconvertedObjectCreationExpression" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;(string Name, Location Location)?&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="InitializerOpt" Type="InitializerExpressionSyntax?" Null="allow"/> </Node> <!-- Constructor is optional because value types can be created without calling any constructor - int x = new int(); --> <Node Name="BoundObjectCreationExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Constructor" Type="MethodSymbol"/> <!-- These symbols will be returned from the GetSemanticInfo API if it examines this bound node. --> <Field Name="ConstructorsGroup" Type="ImmutableArray&lt;MethodSymbol&gt;"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="Expanded" Type="bool"/> <Field Name="ArgsToParamsOpt" Type="ImmutableArray&lt;int&gt;" Null="allow"/> <Field Name="DefaultArguments" Type="BitVector" /> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <Field Name="InitializerExpressionOpt" Type="BoundObjectInitializerExpressionBase?"/> <Field Name="WasTargetTyped" Type="bool"/> </Node> <!-- Tuple literals can exist in two forms - literal and converted literal. This is the base node for both forms. --> <AbstractNode Name="BoundTupleExpression" Base="BoundExpression"> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string?&gt;" Null="allow"/> <!-- Which argument names were inferred (as opposed to explicitly provided)? --> <Field Name="InferredNamesOpt" Type="ImmutableArray&lt;bool&gt;" Null="allow"/> </AbstractNode> <!-- Tuple literals can convert to the target type. Once converted to a target type, they cannot be target-typed again. The tuple literal is one which has not been converted to a target type. --> <Node Name="BoundTupleLiteral" Base="BoundTupleExpression"> <!-- It is possible for a tuple to not have a type in a literal form Ex: (a:=1, b:= (c:=1, d:=Nothing)) does not have a natural type, because "Nothing" does not have one --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="allow"/> </Node> <!-- Tuple literals can convert to the target type. Once converted to a target type, they cannot be target-typed again. The Converted tuple literal is one which has already been converted to a target type. Converted tuple literal always has a type. --> <Node Name="BoundConvertedTupleLiteral" Base="BoundTupleExpression"> <!-- Original tuple is preserved for the purpose of semantic model. When tuples are created as part of lowering, this could be null. --> <Field Name="SourceTuple" Type="BoundTupleLiteral?" Null="allow" SkipInVisitor="ExceptNullabilityRewriter" /> <Field Name="WasTargetTyped" Type="bool" /> </Node> <Node Name="BoundDynamicObjectCreationExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Name" Type="string" Null="disallow"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="InitializerExpressionOpt" Type="BoundObjectInitializerExpressionBase?"/> <Field Name="ApplicableMethods" Type="ImmutableArray&lt;MethodSymbol&gt;" /> </Node> <Node Name="BoundNoPiaObjectCreationExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="GuidString" Type="string?"/> <Field Name="InitializerExpressionOpt" Type="BoundObjectInitializerExpressionBase?"/> </Node> <AbstractNode Name="BoundObjectInitializerExpressionBase" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- An expression placeholder value representing the initialized object or collection. --> <Field Name="Placeholder" Type="BoundObjectOrCollectionValuePlaceholder" Null="disallow" /> <Field Name="Initializers" Type="ImmutableArray&lt;BoundExpression&gt;"/> </AbstractNode> <Node Name="BoundObjectInitializerExpression" Base="BoundObjectInitializerExpressionBase"> </Node> <Node Name="BoundObjectInitializerMember" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="MemberSymbol" Type="Symbol?"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="Expanded" Type="bool"/> <Field Name="ArgsToParamsOpt" Type="ImmutableArray&lt;int&gt;" Null="allow"/> <Field Name="DefaultArguments" Type="BitVector" /> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!-- Used by IOperation to reconstruct the receiver for this expression. --> <Field Name="ReceiverType" Type="TypeSymbol" Null="disallow"/> </Node> <Node Name="BoundDynamicObjectInitializerMember" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="MemberName" Type="string" Null="disallow"/> <Field Name="ReceiverType" Type="TypeSymbol" Null="disallow" /> </Node> <Node Name="BoundCollectionInitializerExpression" Base="BoundObjectInitializerExpressionBase"> </Node> <Node Name="BoundCollectionElementInitializer" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- We don't hold on BoundCall directly since dynamic invocation isn't specified explicitly in the source. --> <Field Name="AddMethod" Type="MethodSymbol"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <!-- Used for IOperation to enable translating the initializer to a IDynamicInvocationOperation --> <Field Name="ImplicitReceiverOpt" Type="BoundExpression?" /> <Field Name="Expanded" Type="bool"/> <Field Name="ArgsToParamsOpt" Type="ImmutableArray&lt;int&gt;" Null="allow"/> <Field Name="DefaultArguments" Type="BitVector" /> <Field Name="InvokedAsExtensionMethod" Type="bool"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> </Node> <Node Name="BoundDynamicCollectionElementInitializer" Base="BoundDynamicInvocableBase"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- We don't hold on DynamicMethodInvocation directly since dynamic invocation isn't specified explicitly in the source. --> <!-- The set of applicable Add methods that may be invoked at runtime. Empty otherwise. --> <Field Name="ApplicableMethods" Type="ImmutableArray&lt;MethodSymbol&gt;" /> </Node> <Node Name="BoundImplicitReceiver" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <Node Name="BoundAnonymousObjectCreationExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Constructor" Type="MethodSymbol" Null="disallow"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <!-- collection of BoundAnonymousPropertyDeclaration nodes representing bound identifiers for explicitly named field initializers, discarded during rewrite NOTE: 'Declarations' collection contain one node for each explicitly named field and does not have any for implicitly named ones, thus it may be empty in case there are no explicitly named fields --> <Field Name="Declarations" Type="ImmutableArray&lt;BoundAnonymousPropertyDeclaration&gt;"/> </Node> <Node Name="BoundAnonymousPropertyDeclaration" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Property" Type="PropertySymbol" Null="disallow"/> </Node> <Node Name="BoundNewT" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="InitializerExpressionOpt" Type="BoundObjectInitializerExpressionBase?"/> </Node> <Node Name="BoundDelegateCreationExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- Argument is one of the following: 1. A method group (before local lowering only). If the method is nonstatic or converted as an extension method, the method group contains a receiver expression (mg.ReceiverOpt) for the created delegate; or 2. A value of type dynamic (before local lowering only); or 3. A bound lambda (before lambda lowering only); or 4. A value of a delegate type with MethodOpt == null; or 5. The receiver of the method being converted to a delegate (after local lowering). It may be a BoundTypeExpression if the method is static and not converted as an extension method. --> <Field Name="Argument" Type="BoundExpression"/> <Field Name="MethodOpt" Type="MethodSymbol?"/> <Field Name="IsExtensionMethod" Type="bool"/> </Node> <Node Name="BoundArrayCreation" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Bounds" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="InitializerOpt" Type="BoundArrayInitialization?"/> </Node> <Node Name="BoundArrayInitialization" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <Field Name="Initializers" Type="ImmutableArray&lt;BoundExpression&gt;"/> </Node> <AbstractNode Name="BoundStackAllocArrayCreationBase" Base="BoundExpression"> <Field Name="ElementType" Type="TypeSymbol" Null="disallow"/> <Field Name="Count" Type="BoundExpression" Null="disallow" /> <Field Name="InitializerOpt" Type="BoundArrayInitialization?"/> </AbstractNode> <Node Name="BoundStackAllocArrayCreation" Base="BoundStackAllocArrayCreationBase"> <!-- A BoundStackAllocArrayCreation is given a null type when it is in a syntactic context where it could be either a pointer or a span, and in that case it requires conversion to one or the other. In the special case that it is the direct initializer of a local variable whose type is inferred, we treat it as a pointer. --> </Node> <Node Name="BoundConvertedStackAllocExpression" Base="BoundStackAllocArrayCreationBase"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <Node Name="BoundFieldAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="FieldSymbol" Type="FieldSymbol"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <Field Name="IsByValue" Type="bool"/> <Field Name="IsDeclaration" Type="bool" /> </Node> <!-- Used as a placeholder for synthesized fields in the expressions that are used to replace hoisted locals. When the local access expression is used, these placeholders are rewritten as field accesses on the appropriate frame object. --> <Node Name="BoundHoistedFieldAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="FieldSymbol" Type="FieldSymbol"/> </Node> <Node Name="BoundPropertyAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="PropertySymbol" Type="PropertySymbol"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> </Node> <Node Name="BoundEventAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="EventSymbol" Type="EventSymbol"/> <Field Name="IsUsableAsField" Type="bool"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> </Node> <Node Name="BoundIndexerAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="Indexer" Type="PropertySymbol"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="Expanded" Type="bool"/> <Field Name="ArgsToParamsOpt" Type="ImmutableArray&lt;int&gt;" Null="allow"/> <Field Name="DefaultArguments" Type="BitVector" /> <!--The set of indexer symbols from which this call's indexer was chosen. Only kept in the tree if the call was an error and overload resolution was unable to choose a best indexer.--> <Field Name="OriginalIndexersOpt" Type="ImmutableArray&lt;PropertySymbol&gt;" Null="allow" SkipInNullabilityRewriter="true"/> </Node> <Node Name="BoundIndexOrRangePatternIndexerAccess" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow" /> <Field Name="Receiver" Type="BoundExpression" Null="disallow" /> <Field Name="LengthOrCountProperty" Type="PropertySymbol" Null="disallow" /> <Field Name="PatternSymbol" Type="Symbol" Null="disallow" /> <Field Name="Argument" Type="BoundExpression" Null="disallow" /> </Node> <Node Name="BoundDynamicIndexerAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Receiver" Type="BoundExpression"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <!-- If the receiver is statically typed the set of applicable methods that may be invoked at runtime. Empty otherwise. --> <Field Name="ApplicableIndexers" Type="ImmutableArray&lt;PropertySymbol&gt;" /> </Node> <Node Name="BoundLambda" Base="BoundExpression"> <Field Name="UnboundLambda" Type="UnboundLambda" Null="disallow" SkipInVisitor="true"/> <!-- LambdaSymbol may differ from Binder.MemberSymbol after rewriting. --> <Field Name="Symbol" Type="LambdaSymbol" Null="disallow"/> <Field Name="Type" Type="TypeSymbol?" Override="true"/> <Field Name="Body" Type="BoundBlock"/> <Field Name="Diagnostics" Type="ImmutableBindingDiagnostic&lt;AssemblySymbol&gt;"/> <Field Name="Binder" Type="Binder" Null="disallow" /> </Node> <Node Name="UnboundLambda" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <Field Name="Data" Type="UnboundLambdaState" Null="disallow"/> <!-- Track dependencies while binding body, etc. --> <Field Name="WithDependencies" Type="Boolean"/> </Node> <Node Name="BoundQueryClause" Base="BoundExpression"> <!-- Equal to Value.Type. --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- The value computed for this query clause. --> <Field Name="Value" Type="BoundExpression" Null="disallow"/> <!-- The query variable introduced by this query clause, if any. --> <Field Name="DefinedSymbol" Type="RangeVariableSymbol?"/> <!-- The bound expression that invokes the operation of the query clause. --> <Field Name="Operation" Type="BoundExpression?" SkipInVisitor="true"/> <!-- The bound expression that is the invocation of a "Cast" method specified by the query translation. --> <Field Name="Cast" Type="BoundExpression?" SkipInVisitor="true"/> <!-- The enclosing binder in which the query clause was evaluated. --> <Field Name="Binder" Type="Binder" Null="disallow" /> <!-- The bound expression that is the query expression in "unoptimized" form. Specifically, a final ".Select" invocation that is omitted by the specification is included here. --> <Field Name="UnoptimizedForm" Type="BoundExpression?" SkipInVisitor="true"/> </Node> <!-- Special node to encapsulate initializers added into a constructor. Helps to do special optimizations in lowering, doesn't survive the lowering. --> <Node Name="BoundTypeOrInstanceInitializers" Base="BoundStatementList"> </Node> <Node Name="BoundNameOfOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Argument" Type="BoundExpression" Null="disallow"/> <Field Name="ConstantValueOpt" Type="ConstantValue" Null="disallow"/> </Node> <AbstractNode Name="BoundInterpolatedStringBase" Base="BoundExpression"> <!-- The sequence of parts of an interpolated string. The even numbered positions (starting with 0) are from the literal parts of the input. The odd numbered positions are the string inserts. If the interpolated string has been bound using the builder pattern, literals are replaced with calls. --> <Field Name="Parts" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> </AbstractNode> <Node Name="BoundUnconvertedInterpolatedString" Base="BoundInterpolatedStringBase"> </Node> <Node Name="BoundInterpolatedString" Base="BoundInterpolatedStringBase"> <Field Name="InterpolationData" Type="InterpolatedStringHandlerData?"/> </Node> <Node Name="BoundInterpolatedStringHandlerPlaceholder" Base="BoundValuePlaceholderBase"/> <!-- A typed expression placeholder for the arguments to the constructor call for an interpolated string handler conversion. We intentionally use a placeholder for overload resolution here to ensure that no conversion from expression can occur. This node is only used for intermediate binding and does not survive local rewriting. --> <Node Name="BoundInterpolatedStringArgumentPlaceholder" Base="BoundValuePlaceholderBase"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow" /> <!-- The index in the containing member of the argument this is the placeholder for. Should be a positive number or one of the constants in the other part of the partial class. --> <Field Name="ArgumentIndex" Type="int" /> <Field Name="ValSafeToEscape" Type="uint" /> </Node> <Node Name="BoundStringInsert" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <Field Name="Value" Type="BoundExpression" Null="disallow"/> <Field Name="Alignment" Type="BoundExpression?"/> <Field Name="Format" Type="BoundLiteral?"/> <Field Name="IsInterpolatedStringHandlerAppendCall" Type="bool"/> </Node> <!-- An 'is pattern'. The fields DecisionDag, WhenTrueLabel, and WhenFalseLabel represent the inner pattern after removing any outer 'not's, so consumers (such as lowering and definite assignment of the local in 'is not Type t') will need to compensate for negated patterns. IsNegated is set if Pattern is the negated form of the inner pattern represented by DecisionDag. --> <Node Name="BoundIsPatternExpression" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> <Field Name="Pattern" Type="BoundPattern" Null="disallow"/> <Field Name="IsNegated" Type="bool"/> <Field Name="DecisionDag" Type="BoundDecisionDag" Null="disallow" SkipInVisitor="true"/> <Field Name="WhenTrueLabel" Type="LabelSymbol" Null="disallow"/> <Field Name="WhenFalseLabel" Type="LabelSymbol" Null="disallow"/> </Node> <AbstractNode Name="BoundPattern" Base="BoundNode"> <Field Name="InputType" Type="TypeSymbol" Null="disallow"/> <Field Name="NarrowedType" Type="TypeSymbol" Null="disallow"/> </AbstractNode> <Node Name="BoundConstantPattern" Base="BoundPattern"> <Field Name="Value" Type="BoundExpression"/> <Field Name="ConstantValue" Type="ConstantValue" Null="disallow"/> </Node> <Node Name="BoundDiscardPattern" Base="BoundPattern"> </Node> <Node Name="BoundDeclarationPattern" Base="BoundPattern"> <!-- Variable is a local symbol, or in the case of top-level code in scripts and interactive, a field that is a member of the script class. Variable is null if `_` is used. --> <Field Name="Variable" Type="Symbol?"/> <!-- VariableAccess is an access to the declared variable, suitable for use in the lowered form in either an lvalue or rvalue position. We maintain it separately from the Symbol to facilitate lowerings in which the variable is no longer a simple variable access (e.g. in the expression evaluator). It is expected to be logically side-effect free. The necessity of this member is a consequence of a design issue documented in https://github.com/dotnet/roslyn/issues/13960 . When that is fixed this field can be removed. --> <Field Name="VariableAccess" Type="BoundExpression?"/> <Field Name="DeclaredType" Type="BoundTypeExpression" Null="disallow"/> <Field Name="IsVar" Type="bool"/> </Node> <Node Name="BoundRecursivePattern" Base="BoundPattern"> <Field Name="DeclaredType" Type="BoundTypeExpression?"/> <Field Name="DeconstructMethod" Type="MethodSymbol?"/> <Field Name="Deconstruction" Type="ImmutableArray&lt;BoundPositionalSubpattern&gt;" Null="allow"/> <Field Name="Properties" Type="ImmutableArray&lt;BoundPropertySubpattern&gt;" Null="allow"/> <!-- Variable is a local symbol, or in the case of top-level code in scripts and interactive, a field that is a member of the script class. Variable is null if `_` is used or if the identifier is omitted. --> <Field Name="Variable" Type="Symbol?"/> <!-- VariableAccess is an access to the declared variable, suitable for use in the lowered form in either an lvalue or rvalue position. We maintain it separately from the Symbol to facilitate lowerings in which the variable is no longer a simple variable access (e.g. in the expression evaluator). It is expected to be logically side-effect free. The necessity of this member is a consequence of a design issue documented in https://github.com/dotnet/roslyn/issues/13960 . When that is fixed this field can be removed. --> <Field Name="VariableAccess" Type="BoundExpression?"/> <Field Name="IsExplicitNotNullTest" Type="bool"/> </Node> <Node Name="BoundITuplePattern" Base="BoundPattern"> <Field Name="GetLengthMethod" Type="MethodSymbol" Null="disallow"/> <Field Name="GetItemMethod" Type="MethodSymbol" Null="disallow"/> <Field Name="Subpatterns" Type="ImmutableArray&lt;BoundPositionalSubpattern&gt;" Null="disallow"/> </Node> <AbstractNode Name="BoundSubpattern" Base="BoundNode"> <Field Name="Pattern" Type="BoundPattern"/> </AbstractNode> <Node Name="BoundPositionalSubpattern" Base="BoundSubpattern"> <!-- The tuple element or parameter in a positional pattern. --> <Field Name="Symbol" Type="Symbol?"/> </Node> <Node Name="BoundPropertySubpattern" Base="BoundSubpattern"> <!-- The property or field access in a property pattern. --> <Field Name="Member" Type="BoundPropertySubpatternMember?"/> </Node> <Node Name="BoundPropertySubpatternMember" Base="BoundNode"> <Field Name="Receiver" Type="BoundPropertySubpatternMember?"/> <Field Name="Symbol" Type="Symbol?"/> <Field Name="Type" Type="TypeSymbol"/> </Node> <Node Name="BoundTypePattern" Base="BoundPattern"> <Field Name="DeclaredType" Type="BoundTypeExpression"/> <Field Name="IsExplicitNotNullTest" Type="bool"/> </Node> <Node Name="BoundBinaryPattern" Base="BoundPattern"> <Field Name="Disjunction" Type="bool"/> <Field Name="Left" Type="BoundPattern"/> <Field Name="Right" Type="BoundPattern"/> </Node> <Node Name="BoundNegatedPattern" Base="BoundPattern"> <Field Name="Negated" Type="BoundPattern"/> </Node> <Node Name="BoundRelationalPattern" Base="BoundPattern"> <Field Name="Relation" Type="BinaryOperatorKind"/> <Field Name="Value" Type="BoundExpression"/> <Field Name="ConstantValue" Type="ConstantValue" Null="disallow"/> </Node> <Node Name="BoundDiscardExpression" Base="BoundExpression"> <!-- A discarded value, when a designator uses `_`. When the type is given as `var, its Type is null before type inference, and it is replaced by a BoundDiscardExpression with a non-null type after inference. --> <Field Name="Type" Type="TypeSymbol?" Override="true"/> </Node> <Node Name="BoundThrowExpression" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> </Node> <AbstractNode Name="VariablePendingInference" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <!-- A local symbol or a field symbol representing the variable --> <Field Name="VariableSymbol" Type="Symbol"/> <!-- A field receiver when VariableSymbol is a field --> <Field Name="ReceiverOpt" Type="BoundExpression?"/> </AbstractNode> <!-- The node is transformed into BoundLocal or BoundFieldAccess after inference --> <Node Name="OutVariablePendingInference" Base="VariablePendingInference" /> <!-- The node is transformed into BoundLocal or BoundFieldAccess after inference --> <Node Name="DeconstructionVariablePendingInference" Base="VariablePendingInference" /> <!-- The node is transformed into BoundDeconstructValuePlaceholder after inference --> <Node Name="OutDeconstructVarPendingInference" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> </Node> <AbstractNode Name="BoundMethodBodyBase" Base="BoundNode"> <Field Name="BlockBody" Type="BoundBlock?"/> <Field Name="ExpressionBody" Type="BoundBlock?"/> </AbstractNode> <Node Name="BoundNonConstructorMethodBody" Base="BoundMethodBodyBase"> </Node> <Node Name="BoundConstructorMethodBody" Base="BoundMethodBodyBase"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="Initializer" Type="BoundStatement?"/> </Node> <!-- Node only used during nullability flow analysis to represent an expression with an updated nullability --> <Node Name="BoundExpressionWithNullability" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> <Field Name="Type" Type="TypeSymbol?" Override="true"/> <!-- We use null Type for placeholders representing out vars --> <Field Name="NullableAnnotation" Type="NullableAnnotation"/> </Node> <Node Name="BoundWithExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Receiver" Type="BoundExpression" /> <!-- CloneMethod may be null in error scenarios--> <Field Name="CloneMethod" Type="MethodSymbol?" /> <!-- Members and expressions passed as arguments to the With expression. --> <Field Name="InitializerExpression" Type="BoundObjectInitializerExpressionBase" /> </Node> </Tree>
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <!-- To re-generate source from this file, run eng/generate-compiler-code.cmd Important things to know about reference types, value types, and nulls. By default, all fields of reference type are checked (in debug) to be non-null. This can be modified by used the "Null" attribute, which can be one of the following values: disallow (default) - disallow null values allow - allow null values always - always null - only used in an override to indicate that this subclass always sets this field to null. notApplicable - its a value type, so it cannot be null In order to generate code, the generator needs to know what types beyond the built-in types are value types. This is indicated via a "ValueType" declaration. --> <Tree Root="BoundNode"> <!-- Don't put ImmutableArray here, that's handled in a special way internally.--> <ValueType Name="ConversionKind"/> <ValueType Name="Conversion"/> <ValueType Name="TextSpan"/> <ValueType Name="UnaryOperatorKind"/> <ValueType Name="BinaryOperatorKind"/> <ValueType Name="LookupResultKind"/> <ValueType Name="NoOpStatementFlavor"/> <ValueType Name="RefKind"/> <ValueType Name="BoundTypeOrValueData"/> <ValueType Name="BoundLocalDeclarationKind"/> <ValueType Name="NullableAnnotation"/> <ValueType Name="ErrorCode"/> <ValueType Name="ImmutableBindingDiagnostic"/> <ValueType Name="InterpolatedStringHandlerData"/> <AbstractNode Name="BoundInitializer" Base="BoundNode"/> <AbstractNode Name="BoundEqualsValue" Base="BoundInitializer"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <!-- Expression representing the value. --> <Field Name="Value" Type="BoundExpression"/> </AbstractNode> <!-- Bound node that represents the binding of an "= Value" construct in a field declaration. Appears only in bound trees generated by a SemanticModel. --> <Node Name="BoundFieldEqualsValue" Base="BoundEqualsValue"> <!-- Field receiving the value. --> <Field Name="Field" Type="FieldSymbol"/> </Node> <!-- Bound node that represents the binding of an "= Value" construct in a property declaration. Appears only in bound trees generated by a SemanticModel. --> <Node Name="BoundPropertyEqualsValue" Base="BoundEqualsValue"> <!-- Property receiving the value. --> <Field Name="Property" Type="PropertySymbol"/> </Node> <!-- Bound node that represents the binding of an "= Value" construct in a parameter declaration. Appears only in bound trees generated by a SemanticModel. --> <Node Name="BoundParameterEqualsValue" Base="BoundEqualsValue"> <!-- Parameter receiving the value. --> <Field Name="Parameter" Type="ParameterSymbol"/> </Node> <Node Name="BoundGlobalStatementInitializer" Base="BoundInitializer"> <Field Name="Statement" Type="BoundStatement"/> </Node> <AbstractNode Name="BoundExpression" Base="BoundNode"> <Field Name="Type" Type="TypeSymbol?"/> </AbstractNode> <AbstractNode Name="BoundValuePlaceholderBase" Base="BoundExpression"> </AbstractNode> <!-- This node is used to represent an expression returning value of a certain type. It is used to perform intermediate binding, and will not survive the local rewriting. --> <Node Name="BoundDeconstructValuePlaceholder" Base="BoundValuePlaceholderBase"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ValEscape" Type="uint" Null="NotApplicable"/> </Node> <!-- In a tuple binary operator, this node is used to represent tuple elements in a tuple binary operator, and to represent an element-wise comparison result to convert back to bool. It does not survive the initial binding. --> <Node Name="BoundTupleOperandPlaceholder" Base="BoundValuePlaceholderBase"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <!-- This node is used to represent an awaitable expression of a certain type, when binding an using-await statement. --> <Node Name="BoundAwaitableValuePlaceholder" Base="BoundValuePlaceholderBase"> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="allow"/> <Field Name="ValEscape" Type="uint" Null="NotApplicable"/> </Node> <!-- This node is used to represent an expression of a certain type, when attempting to bind its pattern dispose method It does not survive past initial binding. --> <Node Name="BoundDisposableValuePlaceholder" Base="BoundValuePlaceholderBase"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <!-- The implicit collection in an object or collection initializer expression. --> <Node Name="BoundObjectOrCollectionValuePlaceholder" Base="BoundValuePlaceholderBase"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="IsNewInstance" Type="bool" Null="NotApplicable"/> </Node> <!-- only used by codegen --> <Node Name="BoundDup" Base="BoundExpression"> <!-- when duplicating a local or parameter, must remember original ref kind --> <Field Name="RefKind" Type="RefKind" Null="NotApplicable"/> </Node> <!-- Wrapper node used to prevent passing the underlying expression by direct reference --> <Node Name="BoundPassByCopy" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression"/> </Node> <!-- An expression is classified as one of the following: A value. Every value has an associated type. A variable. Every variable has an associated type. A namespace. A type. A method group. ... A null literal. An anonymous function. A property access. An event access. An indexer access. Nothing. (An expression which is a method call that returns void.) --> <!-- This node is used when we can't create a real expression node because things are too broken. Example: lookup of a name fails to find anything. --> <Node Name="BoundBadExpression" Base="BoundExpression"> <!-- Categorizes the way in which "Symbols" is bad. --> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!-- These symbols will be returned from the GetSemanticInfo API if it examines this bound node. --> <Field Name="Symbols" Type="ImmutableArray&lt;Symbol?&gt;" SkipInNullabilityRewriter="true"/> <!-- Any child bound nodes that we need to preserve are put here. --> <Field Name="ChildBoundNodes" Type="ImmutableArray&lt;BoundExpression&gt;"/> </Node> <!-- This node is used when we can't create a real statement because things are too broken. --> <Node Name="BoundBadStatement" Base="BoundStatement"> <!-- Any child bound nodes that we need to preserve are put here. --> <Field Name="ChildBoundNodes" Type="ImmutableArray&lt;BoundNode&gt;"/> </Node> <!-- This node is used to wrap the BoundBlock for a finally extracted by AsyncExceptionHandlerRewriter. It is processed and removed by AsyncIteratorRewriter. --> <Node Name="BoundExtractedFinallyBlock" Base="BoundStatement"> <Field Name="FinallyBlock" Type="BoundBlock"/> </Node> <Node Name="BoundTypeExpression" Base="BoundExpression"> <Field Name="AliasOpt" Type="AliasSymbol?"/> <!-- We're going to stash some extra information in the Color Color case so that the binding API can return the correct information. Consider the following example: class C { public class Inner { public static C M() { return null; } } } class F { public C C; void M(C c) { M(/*<bind>*/C/*</bind>*/.Inner.M()); } } The bound tree for "C.Inner.M()" is a bound call with a bound type expression (C.Inner) as its receiver. However, there is no bound node corresponding to C. As a result, the semantic model will attempt to bind it and the binder will return F.C, since it will have no context. That's why we need to have a node for C in the (initial) bound tree. It could conceivably be useful to store other types of expressions as well (e.g. BoundNamespaceExpressions), but then it would be much harder to identify the scenarios in which this property is populated. --> <Field Name="BoundContainingTypeOpt" Type="BoundTypeExpression?"/> <!-- The provided dimensions in an array type expression where dimensions were provided in error. --> <Field Name="BoundDimensionsOpt" Type="ImmutableArray&lt;BoundExpression&gt;" Null="allow"/> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="TypeWithAnnotations" Type="TypeWithAnnotations"/> </Node> <!-- When binding "name1.name2" we normally can tell what name1 is. There is however a case where name1 could be either a value (field, property, parameter, local) or its type. This only happens if value named exactly the same as its type - famous "Color As Color". That alone is not enough to cause trouble as we can do a lookup for name2 and see if it requires a receiver (then name1 is a value) or if it does not (then name1 is a type). The problem only arises when name2 is an overloaded method or property. In such case we must defer type/value decision until overload resolution selects one of the candidates. As a result we need this node that represents name1 in the state where we only know its type and syntax, but do not know yet if it is a Type or Value. NOTE: * The node can only be a qualifier of a method or a property group access as only those may require overload resolution. * It is possible for a node of this type to appear in a tree where there are no errors. Consider (Color.M is Object). M may be overloaded to contain both static and instance methods. In this case the expression is always *false*, but the left-hand-side of the is operator is a method group whose receiver is a BoundTypeOrValueExpression. --> <Node Name="BoundTypeOrValueExpression" Base="BoundExpression"> <!-- Type is required for this node type; may not be null --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Data" Type="BoundTypeOrValueData"/> </Node> <Node Name="BoundNamespaceExpression" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <Field Name="NamespaceSymbol" Type="NamespaceSymbol"/> <Field Name="AliasOpt" Type="AliasSymbol?"/> </Node> <!-- EricLi thought we might need a node like this to do "Color Color" correctly. Currently we're handling that in a different way. Dev10 compiler had a node like this. [removed 3/30/2011 by petergo] <Node Name="BoundTypeOrName" Base="BoundExpression"> <Field Name="Type" Type="BoundTypeExpression"/> <Field Name="Name" Type="BoundExpression"/> </Node> --> <Node Name="BoundUnaryOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="OperatorKind" Type="UnaryOperatorKind"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <Field Name="MethodOpt" Type="MethodSymbol?"/> <Field Name="ConstrainedToTypeOpt" Type="TypeSymbol?" Null="allow"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!--The set of method symbols from which this operator's method was chosen. Only kept in the tree if the operator was an error and overload resolution was unable to choose a best method.--> <Field Name="OriginalUserDefinedOperatorsOpt" Type="ImmutableArray&lt;MethodSymbol&gt;" Null="Allow" SkipInNullabilityRewriter="true"/> </Node> <Node Name="BoundIncrementOperator" Base="BoundExpression"> <!-- x++ might need a conversion from the type of x to the operand type of the ++ operator (that produces the incremented value) and a conversion from the result of the ++ operator back to x. --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="OperatorKind" Type="UnaryOperatorKind"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="MethodOpt" Type="MethodSymbol?"/> <Field Name="ConstrainedToTypeOpt" Type="TypeSymbol?" Null="allow"/> <Field Name="OperandConversion" Type="Conversion"/> <Field Name="ResultConversion" Type="Conversion"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!--The set of method symbols from which this operator's method was chosen. Only kept in the tree if the operator was an error and overload resolution was unable to choose a best method.--> <Field Name="OriginalUserDefinedOperatorsOpt" Type="ImmutableArray&lt;MethodSymbol&gt;" Null="Allow" SkipInNullabilityRewriter="true"/> </Node> <!-- Not really an operator since overload resolution is never required. --> <Node Name="BoundAddressOfOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <!-- True only in some lowered/synthesized nodes. It suppresses conversion of operand reference to unmanaged pointer (which has effect of losing GC-tracking) NB: The language does not have a concept of managed pointers. However, managed (GC-tracked) pointers have some limited support at IL level and could be used in lowering of certain kinds of unsafe code - such as fixed field indexing. --> <Field Name="IsManaged" Type="bool"/> </Node> <!-- Represents an AddressOf operator that has not yet been assigned to a target-type. It has no natural type, and should not survive initial binding except in error cases that are observable via the SemanticModel. --> <Node Name="BoundUnconvertedAddressOfOperator" Base="BoundExpression"> <Field Name="Operand" Type="BoundMethodGroup"/> <!-- Type is null. --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> </Node> <!-- Represents a resolved AddressOf function pointer. Not used in initial binding. --> <Node Name="BoundFunctionPointerLoad" Base="BoundExpression"> <Field Name="TargetMethod" Type="MethodSymbol"/> <Field Name="ConstrainedToTypeOpt" Type="TypeSymbol?" Null="allow"/> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <Node Name="BoundPointerIndirectionOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> </Node> <Node Name="BoundPointerElementAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Expression" Type="BoundExpression"/> <Field Name="Index" Type="BoundExpression"/> <Field Name="Checked" Type="bool"/> </Node> <Node Name="BoundFunctionPointerInvocation" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="InvokedExpression" Type="BoundExpression"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind" /> </Node> <Node Name="BoundRefTypeOperator" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <!-- Well-known member populated during lowering --> <Field Name="GetTypeFromHandle" Type="MethodSymbol?"/> </Node> <Node Name="BoundMakeRefOperator" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> </Node> <Node Name="BoundRefValueOperator" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="NullableAnnotation" Type="NullableAnnotation" /> <Field Name="Operand" Type="BoundExpression"/> </Node> <Node Name="BoundFromEndIndexExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="MethodOpt" Type="MethodSymbol?"/> </Node> <Node Name="BoundRangeExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="LeftOperandOpt" Type="BoundExpression?"/> <Field Name="RightOperandOpt" Type="BoundExpression?"/> <Field Name="MethodOpt" Type="MethodSymbol?"/> </Node> <AbstractNode Name="BoundBinaryOperatorBase" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Left" Type="BoundExpression"/> <Field Name="Right" Type="BoundExpression"/> </AbstractNode> <Node Name="BoundBinaryOperator" Base="BoundBinaryOperatorBase" SkipInNullabilityRewriter="true"> <Field Name="OperatorKind" Type="BinaryOperatorKind"/> <Field Name="Data" Type="BoundBinaryOperator.UncommonData?" /> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> </Node> <Node Name="BoundTupleBinaryOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Left" Type="BoundExpression"/> <Field Name="Right" Type="BoundExpression"/> <Field Name="OperatorKind" Type="BinaryOperatorKind"/> <Field Name="Operators" Type="TupleBinaryOperatorInfo.Multiple"/> </Node> <Node Name="BoundUserDefinedConditionalLogicalOperator" Base="BoundBinaryOperatorBase" SkipInNullabilityRewriter="true"> <Field Name="OperatorKind" Type="BinaryOperatorKind"/> <Field Name="LogicalOperator" Type="MethodSymbol"/> <Field Name="TrueOperator" Type="MethodSymbol"/> <Field Name="FalseOperator" Type="MethodSymbol"/> <Field Name="ConstrainedToTypeOpt" Type="TypeSymbol?" Null="allow"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!--The set of method symbols from which this operator's method was chosen. Only kept in the tree if the operator was an error and overload resolution was unable to choose a best method.--> <Field Name="OriginalUserDefinedOperatorsOpt" Type="ImmutableArray&lt;MethodSymbol&gt;" Null="Allow" SkipInNullabilityRewriter="true"/> </Node> <Node Name="BoundCompoundAssignmentOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- A compound assignment operator has the following facts that must be deduced about it for codegen to work. Suppose you have shorts "x |= y;" That will be analyzed as "x = (short)(((int)x)|((int)y));" We need to know what the left hand and right hand sides are, what the binary operator is, how the left and right sides are converted to the types expected by the operator, whether the operator should check for overflow, and how the result of the binary operator is converted to the target variable's type. We'll lower this to operations on temporaries before codegen. Thought we can represent the operation as these seven facts, in fact we can conflate three of them. We need never do the right-hand-side-of-the-operator conversion during the rewrite. We can get away with binding the conversion on the right early and just having the converted right operand in the bound node. We also conflate whether we should check for overflow with the identity of the operator. This makes it a bit easier to handle the lambda case; when we have something like d += lambda, we want to represent the lambda in its bound form, not in its unbound form to be converted to the bound form later. This helps us maintain the invariant that non-error cases never produce an "unbound" lambda from the initial binding pass. --> <Field Name="Operator" Type="BinaryOperatorSignature" Null="NotApplicable"/> <Field Name="Left" Type="BoundExpression"/> <Field Name="Right" Type="BoundExpression"/> <Field Name="LeftConversion" Type="Conversion"/> <Field Name="FinalConversion" Type="Conversion"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!--The set of method symbols from which this operator's method was chosen. Only kept in the tree if the operator was an error and overload resolution was unable to choose a best method.--> <Field Name="OriginalUserDefinedOperatorsOpt" Type="ImmutableArray&lt;MethodSymbol&gt;" Null="Allow" SkipInNullabilityRewriter="true"/> </Node> <Node Name="BoundAssignmentOperator" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Left" Type="BoundExpression"/> <Field Name="Right" Type="BoundExpression" Null="NotApplicable"/> <!-- This is almost always false. In C# most assignments to a variable are simply writes to the logical variable. For example, when you say void M(ref int x){ x = C.y } that writes the value of C.y to the variable that x is an alias for. It does not write the address of C.y to the actual underlying storage of the parameter, which is of course actually a ref to an int variable. However, in some codegen scenarios we need to distinguish between a ref local assignment and a value assignment. When you say int s = 123; s+=10; then we generate that as int s = 123; ref int addr = ref s; int sum = addr + 10; addr = sum; Note that there are two assignment to addr; one assigns the address of s to addr; the other assigns the value of sum to s, indirectly through addr. We therefore need to disambiguate what kind of assignment we are doing based on something other than the refness of the left hand side. --> <Field Name="IsRef" Type="bool" Null="NotApplicable"/> </Node> <Node Name="BoundDeconstructionAssignmentOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Left" Type="BoundTupleExpression" Null="disallow"/> <Field Name="Right" Type="BoundConversion" Null="disallow"/> <Field Name="IsUsed" Type="bool" Null="NotApplicable"/> </Node> <Node Name="BoundNullCoalescingOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="LeftOperand" Type="BoundExpression"/> <Field Name="RightOperand" Type="BoundExpression"/> <Field Name="LeftConversion" Type="Conversion"/> <Field Name="OperatorResultKind" Type="BoundNullCoalescingOperatorResultKind" Null="NotApplicable"/> </Node> <Node Name="BoundNullCoalescingAssignmentOperator" Base="BoundExpression"> <Field Name="LeftOperand" Type="BoundExpression" /> <Field Name="RightOperand" Type="BoundExpression" /> </Node> <Node Name="BoundUnconvertedConditionalOperator" Base="BoundExpression"> <Field Name="Condition" Type="BoundExpression"/> <Field Name="Consequence" Type="BoundExpression"/> <Field Name="Alternative" Type="BoundExpression"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <Field Name="NoCommonTypeError" Type="ErrorCode"/> </Node> <Node Name="BoundConditionalOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="IsRef" Type="bool"/> <Field Name="Condition" Type="BoundExpression"/> <Field Name="Consequence" Type="BoundExpression"/> <Field Name="Alternative" Type="BoundExpression"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <Field Name="NaturalTypeOpt" Type="TypeSymbol?" Null="allow"/> <Field Name="WasTargetTyped" Type="bool" /> </Node> <Node Name="BoundArrayAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Expression" Type="BoundExpression"/> <Field Name="Indices" Type="ImmutableArray&lt;BoundExpression&gt;"/> </Node> <!-- Represents an operation that is special in both IL and Expression trees - getting length of a one-dimensional 0-based array (vector) This node should not be produced in initial binding since it is not a part of language (.Length is just a property on System.Array) and is normally introduced during the lowering phases. --> <Node Name="BoundArrayLength" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Expression" Type="BoundExpression"/> </Node> <Node Name="BoundAwaitableInfo" Base="BoundNode"> <!-- Used to refer to the awaitable expression in GetAwaiter --> <Field Name="AwaitableInstancePlaceholder" Type="BoundAwaitableValuePlaceholder?" Null="allow" /> <Field Name="IsDynamic" Type="bool"/> <Field Name="GetAwaiter" Type="BoundExpression?" Null="allow"/> <Field Name="IsCompleted" Type="PropertySymbol?" Null="allow"/> <Field Name="GetResult" Type="MethodSymbol?" Null="allow"/> </Node> <Node Name="BoundAwaitExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Expression" Type="BoundExpression"/> <Field Name="AwaitableInfo" Type="BoundAwaitableInfo" Null="disallow"/> </Node> <AbstractNode Name="BoundTypeOf" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- Well-known member populated during lowering --> <Field Name="GetTypeFromHandle" Type="MethodSymbol?"/> </AbstractNode> <Node Name="BoundTypeOfOperator" Base="BoundTypeOf"> <Field Name="SourceType" Type="BoundTypeExpression"/> </Node> <!-- Represents the raw metadata token index value for a method definition. Used by dynamic instrumentation to index into tables or arrays of per-method information. --> <Node Name="BoundMethodDefIndex" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Method" Type="MethodSymbol"/> </Node> <!-- Represents the maximum raw metadata token index value for any method definition in the current module. --> <Node Name="BoundMaximumMethodDefIndex" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <!-- Represents the dynamic analysis instrumentation payload array for the analysis kind in the current module. Implemented as a reference to a field of PrivateImplementationDetails, which has no language-level symbol. --> <Node Name="BoundInstrumentationPayloadRoot" Base="BoundExpression"> <Field Name="AnalysisKind" Type="int"/> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <!-- Represents the GUID that is the current module's MVID. Implemented as a reference to PrivateImplementationDetails.MVID, which has no language-level symbol. --> <Node Name="BoundModuleVersionId" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <!-- Represents a string encoding of the GUID that is the current module's MVID. Implemented as a reference to a string constant that is backpatched after the MVID is computed. --> <Node Name="BoundModuleVersionIdString" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <!-- Represents the index in the documents table of the source document containing a method definition. Used by dynamic instrumentation to identify the source document containing a method. --> <Node Name="BoundSourceDocumentIndex" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Document" Type="Cci.DebugSourceDocument"/> </Node> <Node Name="BoundMethodInfo" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Method" Type="MethodSymbol"/> <!-- Well-known member populated during lowering --> <Field Name="GetMethodFromHandle" Type="MethodSymbol?"/> </Node> <Node Name="BoundFieldInfo" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Field" Type="FieldSymbol"/> <!-- Well-known member populated during lowering --> <Field Name="GetFieldFromHandle" Type="MethodSymbol?"/> </Node> <!-- Default literals can convert to the target type. Does not survive initial lowering. --> <Node Name="BoundDefaultLiteral" Base="BoundExpression"> <!-- Type is null. --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> </Node> <!-- The default expression is `default(T)` expression or `default` literal which has been already converted to a target type. --> <Node Name="BoundDefaultExpression" Base="BoundExpression"> <!-- Converted default expression must have a type. --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="TargetType" Type="BoundTypeExpression?" SkipInVisitor="true"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> </Node> <Node Name="BoundIsOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="TargetType" Type="BoundTypeExpression"/> <Field Name="Conversion" Type="Conversion"/> </Node> <Node Name="BoundAsOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="TargetType" Type="BoundTypeExpression"/> <Field Name="Conversion" Type="Conversion"/> </Node> <Node Name="BoundSizeOfOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="SourceType" Type="BoundTypeExpression"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> </Node> <Node Name="BoundConversion" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="Conversion" Type="Conversion"/> <Field Name="IsBaseConversion" Type="bool"/> <Field Name="Checked" Type="bool"/> <Field Name="ExplicitCastInCode" Type="bool"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <!-- A group instance common to all BoundConversions that represent a single Conversion. The field is used in NullableWalker to identify the chained conversions in user-defined conversions in particular. For instance, with the following declarations, an explicit conversion from B to D: expr -> ImplicitReference conversion -> ExplicitUserDefined conversion -> ExplicitReference conversion. class A { public static explicit operator C(A a) => new D(); } class B : A { } class C { } class D : C { } ConversionGroupOpt also contains the target type specified in source in the case of explicit conversions. ConversionGroupOpt may be null for implicit conversions if the Conversion is represented by a single BoundConversion. --> <Field Name="ConversionGroupOpt" Type="ConversionGroup?"/> <!--The set of method symbols from which this conversion's method was chosen. Only kept in the tree if the conversion was an error and overload resolution was unable to choose a best method.--> <Field Name="OriginalUserDefinedConversionsOpt" Type="ImmutableArray&lt;MethodSymbol&gt;" Null="Allow" SkipInNullabilityRewriter="true"/> </Node> <!-- A special node for emitting the implicit conversion from an array (of T) to System.ReadOnlySpan<T>. Although the conversion has an explicitly declared conversion operator, we want to retain it as something other than a method call after lowering so it can be recognized as a special case and possibly optimized during code generation. --> <Node Name="BoundReadOnlySpanFromArray" Base="BoundExpression"> <!-- The type is required to be an instance of the well-known type System.ReadOnlySpan<T> --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="ConversionMethod" Type="MethodSymbol"/> </Node> <!-- <Node Name="BoundRefValueOperator" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Operand" Type="BoundExpression"/> <Field Name="SourceType" Type="BoundTypeExpression"/> </Node> --> <Node Name="BoundArgList" Base="BoundExpression"> <!-- This is the "__arglist" expression that may appear inside a varargs method. --> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <Node Name="BoundArgListOperator" Base="BoundExpression"> <!-- This is the "__arglist(x, y, z)" expression that may appear in a call to a varargs method. --> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol?" Override="true"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> </Node> <!-- Used when a fixed statement local is initialized with either a string or an array. Encapsulates extra info that will be required during rewriting. --> <Node Name="BoundFixedLocalCollectionInitializer" Base="BoundExpression"> <!-- Either string or an array type. --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- char* for type string, T* for type T[]. --> <Field Name="ElementPointerType" Type="TypeSymbol" Null="disallow"/> <!-- Conversion from ElementPointerType to the type of the corresponding local. --> <Field Name="ElementPointerTypeConversion" Type="Conversion"/> <!-- Wrapped expression. --> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> <!-- optional method that returns a pinnable reference for the instance --> <Field Name="GetPinnableOpt" Type="MethodSymbol?"/> </Node> <AbstractNode Name="BoundStatement" Base="BoundNode"/> <Node Name="BoundSequencePoint" Base="BoundStatement"> <!-- if Statement is null, a NOP may be emitted, to make sure the point is not associated with next statement (which could be a fairly random statement in random scope). --> <Field Name="StatementOpt" Type="BoundStatement?"/> </Node> <!--EDMAURER Use this in the event that the span you must represent is not that of a SyntaxNode. If a SyntaxNode captures the correct span, use a BoundSequencePoint.--> <Node Name="BoundSequencePointWithSpan" Base="BoundStatement"> <!-- if Statement is null, a NOP may be emitted, to make sure the point is not associated with next statement (which could be a fairly random statement in random scope). --> <Field Name="StatementOpt" Type="BoundStatement?"/> <Field Name="Span" Type="TextSpan"/> </Node> <!-- This is used to save the debugger's idea of what the enclosing sequence point is at this location in the code so that it can be restored later by a BoundRestorePreviousSequencePoint node. When this statement appears, the previous non-hidden sequence point is saved and associated with the given Identifier. --> <Node Name="BoundSavePreviousSequencePoint" Base="BoundStatement"> <Field Name="Identifier" Type="object"/> </Node> <!-- This is used to restore the debugger's idea of what the enclosing statement is to some previous location without introducing a place where a breakpoint would cause the debugger to stop. The identifier must have previously been given in a BoundSavePreviousSequencePoint statement. This is used to implement breakpoints within expressions (e.g. a switch expression). --> <Node Name="BoundRestorePreviousSequencePoint" Base="BoundStatement"> <Field Name="Identifier" Type="object"/> </Node> <!-- This is used to set the debugger's idea of what the enclosing statement is without causing the debugger to stop here when single stepping. --> <Node Name="BoundStepThroughSequencePoint" Base="BoundStatement"> <Field Name="Span" Type="TextSpan"/> </Node> <!-- BoundBlock contains a) Statements - actions performed within the scope of the block b) Locals - local variable symbols that are visible within the scope of the block BoundBlock specify SCOPE (visibility) of a variable. TODO: it appears in C#, variable's extent (life time) never escapes its scope. Is that always guaranteed or there are exceptions? Note - in VB variable's extent is the whole method and can be larger than its scope. That is why unassigned use is just a warning and jumps into blocks are generally allowed. --> <Node Name="BoundBlock" Base="BoundStatementList"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="LocalFunctions" Type="ImmutableArray&lt;LocalFunctionSymbol&gt;"/> </Node> <!-- This node is used to represent a visibility scope for locals, for which lifetime is extended beyond the visibility scope. At the moment, only locals declared within CaseSwitchLabelSyntax and SwitchExpressionSyntax have their lifetime expanded to the entire switch body, whereas their visibility scope is the declaring switch section. The node is added into the tree during lowering phase. --> <Node Name="BoundScope" Base="BoundStatementList"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> </Node> <!-- BoundStateMachineScope represents a scope within a translated iterator/async method. It is used to emit debugging information that allows the EE to map fields to locals. --> <Node Name="BoundStateMachineScope" Base="BoundStatement"> <Field Name="Fields" Type="ImmutableArray&lt;StateMachineFieldSymbol&gt;"/> <Field Name="Statement" Type="BoundStatement" Null="disallow"/> </Node> <!-- Bound node that represents a single local declaration: int x = Foo(); NOTE: The node does NOT introduce the referenced local into surrounding scope. A local must be explicitly declared in a BoundBlock to be usable inside it. NOTE: In an error recovery scenario we might have a local declaration parsed as int x[123] - This is an error commonly made by C++ developers who come to C#. We will give a good error about it at parse time, but we should preserve the semantic analysis of the argument list in the bound tree. --> <Node Name="BoundLocalDeclaration" Base="BoundStatement"> <Field Name="LocalSymbol" Type="LocalSymbol"/> <!-- Only set for the first declaration in BoundMultipleLocalDeclarations unless the type is inferred --> <Field Name="DeclaredTypeOpt" Type="BoundTypeExpression?"/> <Field Name="InitializerOpt" Type="BoundExpression?"/> <Field Name="ArgumentsOpt" Type="ImmutableArray&lt;BoundExpression&gt;" Null="allow"/> <!-- Was the type inferred via "var"? --> <Field Name="InferredType" Type="bool"/> </Node> <!-- Base node shared by BoundMultipleLocalDeclarations and BoundUsingLocalDeclarations --> <AbstractNode Name="BoundMultipleLocalDeclarationsBase" Base="BoundStatement"> <Field Name="LocalDeclarations" Type="ImmutableArray&lt;BoundLocalDeclaration&gt;"/> </AbstractNode> <!-- Bound node that represents multiple local declarations: int x =1, y =2; Works like multiple BoundLocalDeclaration nodes. --> <Node Name="BoundMultipleLocalDeclarations" Base="BoundMultipleLocalDeclarationsBase" /> <!-- Bound node that represents a using local declaration [async] using var x = ..., y = ...; --> <Node Name="BoundUsingLocalDeclarations" Base="BoundMultipleLocalDeclarationsBase"> <Field Name="PatternDisposeInfoOpt" Type="MethodArgumentInfo?"/> <Field Name="IDisposableConversion" Type="Conversion"/> <Field Name="AwaitOpt" Type="BoundAwaitableInfo?"/> </Node> <!-- Bound node that represents a local function declaration: void Foo() { } --> <Node Name="BoundLocalFunctionStatement" Base="BoundStatement"> <Field Name="Symbol" Type="LocalFunctionSymbol"/> <Field Name="BlockBody" Type="BoundBlock?"/> <Field Name="ExpressionBody" Type="BoundBlock?"/> </Node> <Node Name="BoundNoOpStatement" Base="BoundStatement"> <!-- No operation. Empty statement. --> <!-- BoundNoOpStatement node may serve as a vehicle for passing some internal information between lowering phases and/or codegen; for example, async rewriter needs to mark some particular places in the emitted code so that we could emit proper PDB information for generated methods. --> <Field Name="Flavor" Type="NoOpStatementFlavor"/> </Node> <Node Name="BoundReturnStatement" Base="BoundStatement"> <Field Name="RefKind" Type="RefKind"/> <Field Name="ExpressionOpt" Type="BoundExpression?"/> </Node> <Node Name="BoundYieldReturnStatement" Base="BoundStatement"> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> </Node> <Node Name="BoundYieldBreakStatement" Base="BoundStatement"/> <Node Name="BoundThrowStatement" Base="BoundStatement"> <Field Name="ExpressionOpt" Type="BoundExpression?"/> </Node> <Node Name="BoundExpressionStatement" Base="BoundStatement"> <Field Name="Expression" Type="BoundExpression"/> </Node> <Node Name="BoundBreakStatement" Base="BoundStatement"> <Field Name="Label" Type="GeneratedLabelSymbol" /> </Node> <Node Name="BoundContinueStatement" Base="BoundStatement"> <Field Name="Label" Type="GeneratedLabelSymbol" /> </Node> <Node Name="BoundSwitchStatement" Base="BoundStatement"> <Field Name="Expression" Type="BoundExpression"/> <!-- Locals declared immediately within the switch block. --> <Field Name="InnerLocals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="InnerLocalFunctions" Type="ImmutableArray&lt;LocalFunctionSymbol&gt;"/> <Field Name="SwitchSections" Type="ImmutableArray&lt;BoundSwitchSection&gt;"/> <Field Name="DecisionDag" Type="BoundDecisionDag" Null="disallow" SkipInVisitor="true"/> <Field Name="DefaultLabel" Type="BoundSwitchLabel?"/> <Field Name="BreakLabel" Type="GeneratedLabelSymbol"/> </Node> <!-- Part of a lowered integral switch statement. This evaluates Value, and then branches to the corresponding Target. If no Value is equal to the input, branches to the default label. The input Value and the constants must be of the same type. Currently emit only supports integral types and string. BoundSwitchDispatch is also used to mark labels in the code that will be the target of backward branches, but should be treated as having the same stack depth as the location where the BoundForwardLabels appears. Although we will necessarily produce some IL instructions for this in order to comply with the verifier constraints, the effect of the code shall be a no-op. The form of the code produced will likely be something of the form ldc.i4.m1 // load constant -1 switch ( IL_nnnn, // all of the labels of interest IL_nnnn, IL_nnnn) This is needed for the lowering of the pattern switch expression, which produces a state machine that may contain backward branches. Due to the fact that it is an expression, it may appear where the stack is not empty. A BoundSwitchDispatch statement (used inside of a BoundSequence containing the state machine) permits us to (cause the verifier to) classify all of the labels as forward labels by producing a dummy inoperable forward jump to them. --> <Node Name="BoundSwitchDispatch" Base="BoundStatement"> <Field Name="Expression" Type="BoundExpression" Null="disallow" /> <Field Name="Cases" Type="ImmutableArray&lt;(ConstantValue value, LabelSymbol label)&gt;" /> <Field Name="DefaultLabel" Type="LabelSymbol" Null="disallow" /> <!-- Equality method to be used when dispatching on a non-integral type such as string. --> <Field Name="EqualityMethod" Type="MethodSymbol?" /> </Node> <Node Name="BoundIfStatement" Base="BoundStatement"> <Field Name="Condition" Type="BoundExpression"/> <Field Name="Consequence" Type="BoundStatement"/> <Field Name="AlternativeOpt" Type="BoundStatement?"/> </Node> <AbstractNode Name="BoundLoopStatement" Base="BoundStatement"> <Field Name="BreakLabel" Type="GeneratedLabelSymbol"/> <Field Name="ContinueLabel" Type="GeneratedLabelSymbol"/> </AbstractNode> <AbstractNode Name="BoundConditionalLoopStatement" Base="BoundLoopStatement"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="Condition" Type="BoundExpression"/> <Field Name="Body" Type="BoundStatement"/> </AbstractNode> <Node Name="BoundDoStatement" Base="BoundConditionalLoopStatement"> </Node> <Node Name="BoundWhileStatement" Base="BoundConditionalLoopStatement"> </Node> <Node Name="BoundForStatement" Base="BoundLoopStatement"> <!-- OuterLocals are the locals declared within the loop Initializer statement and are in scope throughout the whole loop statement --> <Field Name="OuterLocals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="Initializer" Type="BoundStatement?"/> <!-- InnerLocals are the locals declared within the loop Condition and are in scope throughout the Condition, Increment and Body. They are considered to be declared per iteration. --> <Field Name="InnerLocals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="Condition" Type="BoundExpression?"/> <Field Name="Increment" Type="BoundStatement?"/> <Field Name="Body" Type="BoundStatement"/> </Node> <Node Name="BoundForEachStatement" Base="BoundLoopStatement"> <!-- Extracted information --> <Field Name="EnumeratorInfoOpt" Type="ForEachEnumeratorInfo?"/> <Field Name="ElementConversion" Type="Conversion"/> <!-- Pieces corresponding to the syntax --> <!-- This is so the binding API can find produce semantic info if the type is "var". --> <!-- If there is a deconstruction, there will be no iteration variable (but we'll still have a type for it). --> <Field Name="IterationVariableType" Type="BoundTypeExpression"/> <Field Name="IterationVariables" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <!-- In error scenarios where the iteration variable is some arbitrary expression, we stick the error recovery in this node. This will always be null in valid code. --> <Field Name="IterationErrorExpressionOpt" Type="BoundExpression?"/> <!-- If this node does not have errors, then this is the foreach expression wrapped in a conversion to the collection type used by the foreach loop. The conversion is here so that the binding API can return the correct ConvertedType in semantic info. It will be stripped off in the rewriter if it is redundant or causes extra boxing. If this node has errors, then the conversion may not be present.--> <Field Name="Expression" Type="BoundExpression"/> <Field Name="DeconstructionOpt" Type="BoundForEachDeconstructStep?"/> <Field Name="AwaitOpt" Type="BoundAwaitableInfo?"/> <Field Name="Body" Type="BoundStatement"/> <Field Name="Checked" Type="bool"/> </Node> <!-- All the information need to apply a deconstruction at each iteration of a foreach loop involving a deconstruction-declaration. --> <Node Name="BoundForEachDeconstructStep" Base="BoundNode"> <Field Name="DeconstructionAssignment" Type="BoundDeconstructionAssignmentOperator" Null="disallow"/> <Field Name="TargetPlaceholder" Type="BoundDeconstructValuePlaceholder" Null="disallow"/> </Node> <Node Name="BoundUsingStatement" Base="BoundStatement"> <!-- DeclarationsOpt and ExpressionOpt cannot both be non-null. --> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="DeclarationsOpt" Type="BoundMultipleLocalDeclarations?"/> <Field Name="ExpressionOpt" Type="BoundExpression?"/> <Field Name="IDisposableConversion" Type="Conversion" /> <Field Name="Body" Type="BoundStatement"/> <Field Name="AwaitOpt" Type="BoundAwaitableInfo?"/> <Field Name="PatternDisposeInfoOpt" Type="MethodArgumentInfo?"/> </Node> <Node Name="BoundFixedStatement" Base="BoundStatement"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="Declarations" Type="BoundMultipleLocalDeclarations"/> <Field Name="Body" Type="BoundStatement"/> </Node> <Node Name="BoundLockStatement" Base="BoundStatement"> <Field Name="Argument" Type="BoundExpression"/> <Field Name="Body" Type="BoundStatement"/> </Node> <Node Name="BoundTryStatement" Base="BoundStatement"> <Field Name="TryBlock" Type="BoundBlock"/> <Field Name="CatchBlocks" Type="ImmutableArray&lt;BoundCatchBlock&gt;"/> <Field Name="FinallyBlockOpt" Type="BoundBlock?"/> <!-- When lowering trys, we sometimes extract the finally clause out of the try. For example, `try { } finally { await expr; }` becomes something like `try { } catch { ... } finallyLabel: { await expr; ... }`. We need to save the label for the finally so that async-iterator rewriting can implement proper disposal. --> <Field Name="FinallyLabelOpt" Type="LabelSymbol?"/> <!-- PreferFaultHandler is a hint to the codegen to emit Finally in the following shape - try { } fault { finallyBlock } finallyBlock This pattern preserves semantics of Finally while not using finally handler. As a result any kind of analysis can continue treating Finally blocks as Finally blocks. NOTE!! When Fault emit is used - 1) The code is emitted twice 2) The second copy is outside of a handler block. 3) Branches out of the try will NOT be intercepted by the surrogate finally. User of this flag must ensure that the above caveats are acceptable. For example when this flag is used in Iterator rewrite, the second copy is always unreachable and not intercepting the return is intended behavior since the only branch out of Iterator body is "goto exitLabel". --> <Field Name="PreferFaultHandler" Type="bool"/> </Node> <Node Name="BoundCatchBlock" Base="BoundNode"> <!-- Local symbols owned by the catch block. Empty if the catch syntax doesn't declare a local variable. In the initial bound tree the first variable is the exception variable (if present). After the node is lowered the exception variable might become a field and will be removed from the array, otherwise it will stay at the first position. --> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <!-- Refers to the location where the exception object is stored. The expression is a local or a BoundSequence, whose last expression refers to the location of the exception object and the sideeffects initialize its storage (e.g. if the catch identifier is lifted into a closure the sideeffects initialize the closure). Null if the exception object is not referred to. --> <Field Name="ExceptionSourceOpt" Type="BoundExpression?"/> <Field Name="ExceptionTypeOpt" Type="TypeSymbol?"/> <Field Name="ExceptionFilterPrologueOpt" Type="BoundStatementList?"/> <Field Name="ExceptionFilterOpt" Type="BoundExpression?"/> <Field Name="Body" Type="BoundBlock"/> <Field Name="IsSynthesizedAsyncCatchAll" Type="bool" /> </Node> <Node Name="BoundLiteral" Base="BoundExpression"> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> </Node> <Node Name="BoundThisReference" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- Note that "this" is classified as a variable in some scenarios. We'll treat it as a value generally and special-case those cases. --> </Node> <Node Name="BoundPreviousSubmissionReference" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <Node Name="BoundHostObjectMemberReference" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <Node Name="BoundBaseReference" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" /> </Node> <Node Name="BoundLocal" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="LocalSymbol" Type="LocalSymbol"/> <Field Name="DeclarationKind" Type="BoundLocalDeclarationKind" Null="NotApplicable"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <!-- True if LocalSymbol.Type.IsNullable could not be inferred. --> <Field Name="IsNullableUnknown" Type="bool"/> </Node> <Node Name="BoundPseudoVariable" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="LocalSymbol" Type="LocalSymbol" Null="disallow"/> <Field Name="EmitExpressions" Type ="PseudoVariableExpressions" Null="disallow"/> </Node> <Node Name="BoundRangeVariable" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="RangeVariableSymbol" Type="RangeVariableSymbol"/> <Field Name="Value" Type="BoundExpression"/> </Node> <Node Name="BoundParameter" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ParameterSymbol" Type="ParameterSymbol"/> </Node> <Node Name="BoundLabelStatement" Base="BoundStatement"> <!-- A label is not actually a statement but it is convenient to model it as one because then you can do rewrites without having to know "what comes next". For example suppose you have statement list A(); if(B()) C(); else D(); E(); If you are rewriting the "if" then it is convenient to be able to rewrite it as GotoIfFalse B() LabElse C(); Goto LabDone LabElse D(); LabDone without having to rewrite E(); as a labeled statement. Note that this statement represents the label itself as a "stand-alone" statement, unattached to any other statement. Rewriting will remove this statement and replace it with a LabeledStatement, that references both this LabelSymbol and the specific other statement it actually labels. --> <Field Name="Label" Type="LabelSymbol"/> </Node> <Node Name="BoundGotoStatement" Base="BoundStatement"> <Field Name="Label" Type="LabelSymbol"/> <Field Name="CaseExpressionOpt" Type="BoundExpression?"/> <Field Name="LabelExpressionOpt" Type="BoundLabel?"/> </Node> <!-- This represents a statement which has been labeled. This allows us to recursively bind the labeled expression during binding. --> <Node Name="BoundLabeledStatement" Base="BoundStatement"> <Field Name="Label" Type="LabelSymbol"/> <Field Name="Body" Type="BoundStatement"/> </Node> <!-- This represents the bound form of a label reference (i.e. in a goto). It is only used for the SemanticModel API. --> <Node Name="BoundLabel" Base="BoundExpression"> <Field Name="Label" Type="LabelSymbol"/> </Node> <Node Name="BoundStatementList" Base="BoundStatement"> <!-- A statement list is produced by a rewrite that turns one statement into multiple statements. It does not have the semantics of a block. --> <Field Name="Statements" Type="ImmutableArray&lt;BoundStatement&gt;"/> </Node> <Node Name="BoundConditionalGoto" Base="BoundStatement"> <!-- A compiler-generated conditional goto - jumps if condition == JumpIfTrue --> <Field Name="Condition" Type="BoundExpression"/> <Field Name="JumpIfTrue" Type="bool"/> <Field Name="Label" Type="LabelSymbol"/> </Node> <AbstractNode Name="BoundSwitchExpression" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> <Field Name="SwitchArms" Type="ImmutableArray&lt;BoundSwitchExpressionArm&gt;"/> <Field Name="DecisionDag" Type="BoundDecisionDag" Null="disallow" SkipInVisitor="true"/> <Field Name="DefaultLabel" Type="LabelSymbol?"/> <Field Name="ReportedNotExhaustive" Type="bool"/> </AbstractNode> <Node Name="BoundSwitchExpressionArm" Base="BoundNode"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="Pattern" Type="BoundPattern" Null="disallow"/> <Field Name="WhenClause" Type="BoundExpression?"/> <Field Name="Value" Type="BoundExpression" Null="disallow"/> <Field Name="Label" Type="LabelSymbol" Null="disallow"/> </Node> <Node Name="BoundUnconvertedSwitchExpression" Base="BoundSwitchExpression"> </Node> <!-- Switch expressions can convert to the target type. Once converted to a target type, they cannot be target-typed again. The Converted switch expression is one which has been already converted to a target type. Converted switch expressions always have a type. --> <Node Name="BoundConvertedSwitchExpression" Base="BoundSwitchExpression"> <!-- Converted switch expression must have a type, even if that's an error type. --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- Natural type is preserved for the purpose of semantic model. Can be `null`. --> <Field Name="NaturalTypeOpt" Type="TypeSymbol?" Null="allow"/> <Field Name="WasTargetTyped" Type="bool" /> <!-- The conversion to Type. Either a switch expression conversion or an identity conversion --> <Field Name="Conversion" Type="Conversion"/> </Node> <Node Name="BoundDecisionDag" Base="BoundNode"> <Field Name="RootNode" Type="BoundDecisionDagNode" Null="disallow"/> </Node> <AbstractNode Name="BoundDecisionDagNode" Base="BoundNode"> </AbstractNode> <!-- This node is used to indicate a point in the decision dag where an evaluation is performed, such as invoking Deconstruct. --> <Node Name="BoundEvaluationDecisionDagNode" Base="BoundDecisionDagNode"> <Field Name="Evaluation" Type="BoundDagEvaluation" Null="disallow"/> <Field Name="Next" Type="BoundDecisionDagNode" Null="disallow"/> </Node> <!-- This node is used to indicate a point in the decision dag where a test may change the path of the decision dag. --> <Node Name="BoundTestDecisionDagNode" Base="BoundDecisionDagNode"> <Field Name="Test" Type="BoundDagTest" Null="disallow"/> <Field Name="WhenTrue" Type="BoundDecisionDagNode" Null="disallow"/> <Field Name="WhenFalse" Type="BoundDecisionDagNode" Null="disallow"/> </Node> <Node Name="BoundWhenDecisionDagNode" Base="BoundDecisionDagNode"> <Field Name="Bindings" Type="ImmutableArray&lt;BoundPatternBinding&gt;" Null="disallow"/> <!-- WhenExpression is null when there was no when clause in source but there are bindings. In that case WhenFalse is null. --> <Field Name="WhenExpression" Type="BoundExpression?"/> <Field Name="WhenTrue" Type="BoundDecisionDagNode" Null="disallow"/> <Field Name="WhenFalse" Type="BoundDecisionDagNode?"/> </Node> <!-- This node is used to indicate a point in the decision dag where the decision has been completed. --> <Node Name="BoundLeafDecisionDagNode" Base="BoundDecisionDagNode"> <Field Name="Label" Type="LabelSymbol"/> </Node> <AbstractNode Name="BoundDagTest" Base="BoundNode"> Input is the input to the decision point. <Field Name="Input" Type="BoundDagTemp"/> </AbstractNode> <Node Name="BoundDagTemp" Base="BoundNode"> <Field Name="Type" Type="TypeSymbol" Null="disallow"/> <Field Name="Source" Type="BoundDagEvaluation?"/> <Field Name="Index" Type="int"/> </Node> <Node Name="BoundDagTypeTest" Base="BoundDagTest"> <!--Check that the input is of the given type. Null check is separate.--> <Field Name="Type" Type="TypeSymbol" Null="disallow"/> </Node> <Node Name="BoundDagNonNullTest" Base="BoundDagTest"> <!--Check that the input is not null. Used as part of a type test.--> <Field Name="IsExplicitTest" Type="bool"/> </Node> <Node Name="BoundDagExplicitNullTest" Base="BoundDagTest"> <!--Check that the input is null. Used when an explicit null test appears in source.--> </Node> <Node Name="BoundDagValueTest" Base="BoundDagTest"> <!--Check that the input is the same as the given constant value (other than null).--> <Field Name="Value" Type="ConstantValue" Null="disallow"/> </Node> <Node Name="BoundDagRelationalTest" Base="BoundDagTest"> <!--Check that the input is related to (equal, not equal, less, less or equal, greater, greater or equal) the given constant value (other than null).--> <Field Name="OperatorKind" Type="BinaryOperatorKind"/> <Field Name="Value" Type="ConstantValue" Null="disallow"/> </Node> <!-- As a decision, an evaluation is considered to always succeed. --> <AbstractNode Name="BoundDagEvaluation" Base="BoundDagTest"> </AbstractNode> <Node Name="BoundDagDeconstructEvaluation" Base="BoundDagEvaluation"> <Field Name="DeconstructMethod" Type="MethodSymbol" Null="disallow"/> </Node> <Node Name="BoundDagTypeEvaluation" Base="BoundDagEvaluation"> <!--Cast to the given type, assumed to be used after a successful type check.--> <Field Name="Type" Type="TypeSymbol" Null="disallow"/> </Node> <Node Name="BoundDagFieldEvaluation" Base="BoundDagEvaluation"> <Field Name="Field" Type="FieldSymbol" Null="disallow"/> </Node> <Node Name="BoundDagPropertyEvaluation" Base="BoundDagEvaluation"> <Field Name="Property" Type="PropertySymbol" Null="disallow"/> </Node> <Node Name="BoundDagIndexEvaluation" Base="BoundDagEvaluation"> <Field Name="Property" Type="PropertySymbol" Null="disallow"/> <Field Name="Index" Type="int"/> </Node> <Node Name="BoundSwitchSection" Base="BoundStatementList"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="SwitchLabels" Type="ImmutableArray&lt;BoundSwitchLabel&gt;"/> </Node> <Node Name="BoundSwitchLabel" Base="BoundNode"> <Field Name="Label" Type="LabelSymbol"/> <Field Name="Pattern" Type="BoundPattern"/> <Field Name="WhenClause" Type="BoundExpression?"/> </Node> <AbstractNode Name="BoundMethodOrPropertyGroup" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <!--We wish to keep the left-hand-side of the member access in the method group even if the *instance* expression ought to be null. For example, if we have System.Console.WriteLine then we want to keep the System.Console type expression as the receiver, even though the spec says that the instance expression is null in this case. We'll add a helper property that gets the instance expression from the receiver should we need it. --> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> </AbstractNode> <!-- Use this in the event that the sequence point must be applied to expression.--> <Node Name="BoundSequencePointExpression" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> </Node> <!-- A node specially to represent the idea of "compute this side effects while discarding results, and then compute this value" The node may also declare locals (temporaries). The sequence node is both SCOPE and EXTENT of these locals. As a result non-intersecting sequences can reuse variable slots. --> <Node Name="BoundSequence" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="SideEffects" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="Value" Type="BoundExpression"/> </Node> <!-- Like BoundSequence, but the side-effects are statements. This node is produced during initial lowering for the `await` expression and for the switch expression. A separate pass removes these nodes by moving the statements to the top level (i.e. to a statement list that is not in a BoundSpillSequence). It is called a spill sequence because the process of moving it to the top level causes values that would be on the stack during its evaluation to be spilled to temporary variables. --> <Node Name="BoundSpillSequence" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="SideEffects" Type="ImmutableArray&lt;BoundStatement&gt;"/> <Field Name="Value" Type="BoundExpression"/> </Node> <Node Name="BoundDynamicMemberAccess" Base="BoundExpression"> <!--Non-null type is required, and will always be "dynamic". --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Receiver" Type="BoundExpression"/> <Field Name="TypeArgumentsOpt" Type="ImmutableArray&lt;TypeWithAnnotations&gt;" Null="allow"/> <Field Name="Name" Type="string" Null="disallow"/> <!-- TODO (tomat): do we really need these flags here? it should be possible to infer them from the context --> <Field Name="Invoked" Type="bool"/> <Field Name="Indexed" Type="bool"/> </Node> <AbstractNode Name="BoundDynamicInvocableBase" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> </AbstractNode> <Node Name="BoundDynamicInvocation" Base="BoundDynamicInvocableBase"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <!-- If the receiver is statically typed the set of applicable methods that may be invoked at runtime. Empty otherwise. --> <Field Name="ApplicableMethods" Type="ImmutableArray&lt;MethodSymbol&gt;" /> </Node> <Node Name="BoundConditionalAccess" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Receiver" Type="BoundExpression"/> <Field Name="AccessExpression" Type="BoundExpression"/> </Node> <Node Name="BoundLoweredConditionalAccess" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Receiver" Type="BoundExpression"/> <Field Name="HasValueMethodOpt" Type="MethodSymbol?"/> <Field Name="WhenNotNull" Type="BoundExpression"/> <Field Name="WhenNullOpt" Type="BoundExpression?"/> <!-- Async rewriter needs to replace receivers with their spilled values and for that it needs to match receivers and the containing conditional expressions. To be able to do that, during lowering, we will assign BoundLoweredConditionalAccess and corresponding BoundConditionalReceiver matching Id that are integers unique for the containing method body. --> <Field Name="Id" Type="int"/> </Node> <!-- represents the receiver of a conditional access expression --> <Node Name="BoundConditionalReceiver" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- See the comment in BoundLoweredConditionalAccess --> <Field Name="Id" Type="int"/> </Node> <!-- This node represents a complex receiver for a conditional access. At runtime, when its type is a value type, ValueTypeReceiver should be used as a receiver. Otherwise, ReferenceTypeReceiver should be used. This kind of receiver is created only by Async rewriter. --> <Node Name="BoundComplexConditionalReceiver" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ValueTypeReceiver" Type="BoundExpression" Null="disallow"/> <Field Name="ReferenceTypeReceiver" Type="BoundExpression" Null="disallow"/> </Node> <Node Name="BoundMethodGroup" Base="BoundMethodOrPropertyGroup"> <!-- SPEC: A method group is a set of overloaded methods resulting from a member lookup. SPEC: A method group may have an associated instance expression and SPEC: an associated type argument list. --> <Field Name="TypeArgumentsOpt" Type="ImmutableArray&lt;TypeWithAnnotations&gt;" Null="allow"/> <Field Name="Name" Type="string" Null="disallow"/> <Field Name="Methods" Type="ImmutableArray&lt;MethodSymbol&gt;" /> <Field Name="LookupSymbolOpt" Type="Symbol?"/> <Field Name="LookupError" Type="DiagnosticInfo?"/> <Field Name="Flags" Type="BoundMethodGroupFlags?"/> </Node> <Node Name="BoundPropertyGroup" Base="BoundMethodOrPropertyGroup"> <Field Name="Properties" Type="ImmutableArray&lt;PropertySymbol&gt;" /> </Node> <Node Name="BoundCall" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="Method" Type="MethodSymbol"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="IsDelegateCall" Type="bool"/> <Field Name="Expanded" Type="bool"/> <Field Name="InvokedAsExtensionMethod" Type="bool"/> <Field Name="ArgsToParamsOpt" Type="ImmutableArray&lt;int&gt;" Null="allow"/> <Field Name="DefaultArguments" Type="BitVector" /> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!--The set of method symbols from which this call's method was chosen. Only kept in the tree if the call was an error and overload resolution was unable to choose a best method.--> <Field Name="OriginalMethodsOpt" Type="ImmutableArray&lt;MethodSymbol&gt;" Null="Allow" SkipInNullabilityRewriter="true"/> </Node> <Node Name="BoundEventAssignmentOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Event" Type="EventSymbol"/> <Field Name="IsAddition" Type="bool"/> <Field Name="IsDynamic" Type="bool"/> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="Argument" Type="BoundExpression"/> </Node> <Node Name="BoundAttribute" Base="BoundExpression"> <!-- Type is required for this node type; may not be null --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Constructor" Type="MethodSymbol?"/> <Field Name="ConstructorArguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ConstructorArgumentNamesOpt" Type="ImmutableArray&lt;string?&gt;" Null="allow"/> <Field Name="ConstructorArgumentsToParamsOpt" Type="ImmutableArray&lt;int&gt;" Null="allow"/> <Field Name="ConstructorExpanded" Type="bool" /> <Field Name="NamedArguments" Type ="ImmutableArray&lt;BoundAssignmentOperator&gt;"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> </Node> <!-- This node is used to represent a target-typed object creation expression It does not survive past initial binding. --> <Node Name="BoundUnconvertedObjectCreationExpression" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;(string Name, Location Location)?&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="InitializerOpt" Type="InitializerExpressionSyntax?" Null="allow"/> </Node> <!-- Constructor is optional because value types can be created without calling any constructor - int x = new int(); --> <Node Name="BoundObjectCreationExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Constructor" Type="MethodSymbol"/> <!-- These symbols will be returned from the GetSemanticInfo API if it examines this bound node. --> <Field Name="ConstructorsGroup" Type="ImmutableArray&lt;MethodSymbol&gt;"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="Expanded" Type="bool"/> <Field Name="ArgsToParamsOpt" Type="ImmutableArray&lt;int&gt;" Null="allow"/> <Field Name="DefaultArguments" Type="BitVector" /> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <Field Name="InitializerExpressionOpt" Type="BoundObjectInitializerExpressionBase?"/> <Field Name="WasTargetTyped" Type="bool"/> </Node> <!-- Tuple literals can exist in two forms - literal and converted literal. This is the base node for both forms. --> <AbstractNode Name="BoundTupleExpression" Base="BoundExpression"> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string?&gt;" Null="allow"/> <!-- Which argument names were inferred (as opposed to explicitly provided)? --> <Field Name="InferredNamesOpt" Type="ImmutableArray&lt;bool&gt;" Null="allow"/> </AbstractNode> <!-- Tuple literals can convert to the target type. Once converted to a target type, they cannot be target-typed again. The tuple literal is one which has not been converted to a target type. --> <Node Name="BoundTupleLiteral" Base="BoundTupleExpression"> <!-- It is possible for a tuple to not have a type in a literal form Ex: (a:=1, b:= (c:=1, d:=Nothing)) does not have a natural type, because "Nothing" does not have one --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="allow"/> </Node> <!-- Tuple literals can convert to the target type. Once converted to a target type, they cannot be target-typed again. The Converted tuple literal is one which has already been converted to a target type. Converted tuple literal always has a type. --> <Node Name="BoundConvertedTupleLiteral" Base="BoundTupleExpression"> <!-- Original tuple is preserved for the purpose of semantic model. When tuples are created as part of lowering, this could be null. --> <Field Name="SourceTuple" Type="BoundTupleLiteral?" Null="allow" SkipInVisitor="ExceptNullabilityRewriter" /> <Field Name="WasTargetTyped" Type="bool" /> </Node> <Node Name="BoundDynamicObjectCreationExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Name" Type="string" Null="disallow"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="InitializerExpressionOpt" Type="BoundObjectInitializerExpressionBase?"/> <Field Name="ApplicableMethods" Type="ImmutableArray&lt;MethodSymbol&gt;" /> </Node> <Node Name="BoundNoPiaObjectCreationExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="GuidString" Type="string?"/> <Field Name="InitializerExpressionOpt" Type="BoundObjectInitializerExpressionBase?"/> </Node> <AbstractNode Name="BoundObjectInitializerExpressionBase" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- An expression placeholder value representing the initialized object or collection. --> <Field Name="Placeholder" Type="BoundObjectOrCollectionValuePlaceholder" Null="disallow" /> <Field Name="Initializers" Type="ImmutableArray&lt;BoundExpression&gt;"/> </AbstractNode> <Node Name="BoundObjectInitializerExpression" Base="BoundObjectInitializerExpressionBase"> </Node> <Node Name="BoundObjectInitializerMember" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="MemberSymbol" Type="Symbol?"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="Expanded" Type="bool"/> <Field Name="ArgsToParamsOpt" Type="ImmutableArray&lt;int&gt;" Null="allow"/> <Field Name="DefaultArguments" Type="BitVector" /> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <!-- Used by IOperation to reconstruct the receiver for this expression. --> <Field Name="ReceiverType" Type="TypeSymbol" Null="disallow"/> </Node> <Node Name="BoundDynamicObjectInitializerMember" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="MemberName" Type="string" Null="disallow"/> <Field Name="ReceiverType" Type="TypeSymbol" Null="disallow" /> </Node> <Node Name="BoundCollectionInitializerExpression" Base="BoundObjectInitializerExpressionBase"> </Node> <Node Name="BoundCollectionElementInitializer" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- We don't hold on BoundCall directly since dynamic invocation isn't specified explicitly in the source. --> <Field Name="AddMethod" Type="MethodSymbol"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <!-- Used for IOperation to enable translating the initializer to a IDynamicInvocationOperation --> <Field Name="ImplicitReceiverOpt" Type="BoundExpression?" /> <Field Name="Expanded" Type="bool"/> <Field Name="ArgsToParamsOpt" Type="ImmutableArray&lt;int&gt;" Null="allow"/> <Field Name="DefaultArguments" Type="BitVector" /> <Field Name="InvokedAsExtensionMethod" Type="bool"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> </Node> <Node Name="BoundDynamicCollectionElementInitializer" Base="BoundDynamicInvocableBase"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- We don't hold on DynamicMethodInvocation directly since dynamic invocation isn't specified explicitly in the source. --> <!-- The set of applicable Add methods that may be invoked at runtime. Empty otherwise. --> <Field Name="ApplicableMethods" Type="ImmutableArray&lt;MethodSymbol&gt;" /> </Node> <Node Name="BoundImplicitReceiver" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <Node Name="BoundAnonymousObjectCreationExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Constructor" Type="MethodSymbol" Null="disallow"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <!-- collection of BoundAnonymousPropertyDeclaration nodes representing bound identifiers for explicitly named field initializers, discarded during rewrite NOTE: 'Declarations' collection contain one node for each explicitly named field and does not have any for implicitly named ones, thus it may be empty in case there are no explicitly named fields --> <Field Name="Declarations" Type="ImmutableArray&lt;BoundAnonymousPropertyDeclaration&gt;"/> </Node> <Node Name="BoundAnonymousPropertyDeclaration" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Property" Type="PropertySymbol" Null="disallow"/> </Node> <Node Name="BoundNewT" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="InitializerExpressionOpt" Type="BoundObjectInitializerExpressionBase?"/> </Node> <Node Name="BoundDelegateCreationExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- Argument is one of the following: 1. A method group (before local lowering only). If the method is nonstatic or converted as an extension method, the method group contains a receiver expression (mg.ReceiverOpt) for the created delegate; or 2. A value of type dynamic (before local lowering only); or 3. A bound lambda (before lambda lowering only); or 4. A value of a delegate type with MethodOpt == null; or 5. The receiver of the method being converted to a delegate (after local lowering). It may be a BoundTypeExpression if the method is static and not converted as an extension method. --> <Field Name="Argument" Type="BoundExpression"/> <Field Name="MethodOpt" Type="MethodSymbol?"/> <Field Name="IsExtensionMethod" Type="bool"/> </Node> <Node Name="BoundArrayCreation" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Bounds" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="InitializerOpt" Type="BoundArrayInitialization?"/> </Node> <Node Name="BoundArrayInitialization" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <Field Name="Initializers" Type="ImmutableArray&lt;BoundExpression&gt;"/> </Node> <AbstractNode Name="BoundStackAllocArrayCreationBase" Base="BoundExpression"> <Field Name="ElementType" Type="TypeSymbol" Null="disallow"/> <Field Name="Count" Type="BoundExpression" Null="disallow" /> <Field Name="InitializerOpt" Type="BoundArrayInitialization?"/> </AbstractNode> <Node Name="BoundStackAllocArrayCreation" Base="BoundStackAllocArrayCreationBase"> <!-- A BoundStackAllocArrayCreation is given a null type when it is in a syntactic context where it could be either a pointer or a span, and in that case it requires conversion to one or the other. In the special case that it is the direct initializer of a local variable whose type is inferred, we treat it as a pointer. --> </Node> <Node Name="BoundConvertedStackAllocExpression" Base="BoundStackAllocArrayCreationBase"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> </Node> <Node Name="BoundFieldAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="FieldSymbol" Type="FieldSymbol"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> <Field Name="IsByValue" Type="bool"/> <Field Name="IsDeclaration" Type="bool" /> </Node> <!-- Used as a placeholder for synthesized fields in the expressions that are used to replace hoisted locals. When the local access expression is used, these placeholders are rewritten as field accesses on the appropriate frame object. --> <Node Name="BoundHoistedFieldAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="FieldSymbol" Type="FieldSymbol"/> </Node> <Node Name="BoundPropertyAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="PropertySymbol" Type="PropertySymbol"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> </Node> <Node Name="BoundEventAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="EventSymbol" Type="EventSymbol"/> <Field Name="IsUsableAsField" Type="bool"/> <Field Name="ResultKind" PropertyOverrides="true" Type="LookupResultKind"/> </Node> <Node Name="BoundIndexerAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="ReceiverOpt" Type="BoundExpression?"/> <Field Name="Indexer" Type="PropertySymbol"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <Field Name="Expanded" Type="bool"/> <Field Name="ArgsToParamsOpt" Type="ImmutableArray&lt;int&gt;" Null="allow"/> <Field Name="DefaultArguments" Type="BitVector" /> <!--The set of indexer symbols from which this call's indexer was chosen. Only kept in the tree if the call was an error and overload resolution was unable to choose a best indexer.--> <Field Name="OriginalIndexersOpt" Type="ImmutableArray&lt;PropertySymbol&gt;" Null="allow" SkipInNullabilityRewriter="true"/> </Node> <Node Name="BoundIndexOrRangePatternIndexerAccess" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow" /> <Field Name="Receiver" Type="BoundExpression" Null="disallow" /> <Field Name="LengthOrCountProperty" Type="PropertySymbol" Null="disallow" /> <Field Name="PatternSymbol" Type="Symbol" Null="disallow" /> <Field Name="Argument" Type="BoundExpression" Null="disallow" /> </Node> <Node Name="BoundDynamicIndexerAccess" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Receiver" Type="BoundExpression"/> <Field Name="Arguments" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ArgumentNamesOpt" Type="ImmutableArray&lt;string&gt;" Null="allow"/> <Field Name="ArgumentRefKindsOpt" Type="ImmutableArray&lt;RefKind&gt;" Null="allow"/> <!-- If the receiver is statically typed the set of applicable methods that may be invoked at runtime. Empty otherwise. --> <Field Name="ApplicableIndexers" Type="ImmutableArray&lt;PropertySymbol&gt;" /> </Node> <Node Name="BoundLambda" Base="BoundExpression"> <Field Name="UnboundLambda" Type="UnboundLambda" Null="disallow" SkipInVisitor="true"/> <!-- LambdaSymbol may differ from Binder.MemberSymbol after rewriting. --> <Field Name="Symbol" Type="LambdaSymbol" Null="disallow"/> <Field Name="Type" Type="TypeSymbol?" Override="true"/> <Field Name="Body" Type="BoundBlock"/> <Field Name="Diagnostics" Type="ImmutableBindingDiagnostic&lt;AssemblySymbol&gt;"/> <Field Name="Binder" Type="Binder" Null="disallow" /> </Node> <Node Name="UnboundLambda" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <Field Name="Data" Type="UnboundLambdaState" Null="disallow"/> <!-- Track dependencies while binding body, etc. --> <Field Name="WithDependencies" Type="Boolean"/> </Node> <Node Name="BoundQueryClause" Base="BoundExpression"> <!-- Equal to Value.Type. --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <!-- The value computed for this query clause. --> <Field Name="Value" Type="BoundExpression" Null="disallow"/> <!-- The query variable introduced by this query clause, if any. --> <Field Name="DefinedSymbol" Type="RangeVariableSymbol?"/> <!-- The bound expression that invokes the operation of the query clause. --> <Field Name="Operation" Type="BoundExpression?" SkipInVisitor="true"/> <!-- The bound expression that is the invocation of a "Cast" method specified by the query translation. --> <Field Name="Cast" Type="BoundExpression?" SkipInVisitor="true"/> <!-- The enclosing binder in which the query clause was evaluated. --> <Field Name="Binder" Type="Binder" Null="disallow" /> <!-- The bound expression that is the query expression in "unoptimized" form. Specifically, a final ".Select" invocation that is omitted by the specification is included here. --> <Field Name="UnoptimizedForm" Type="BoundExpression?" SkipInVisitor="true"/> </Node> <!-- Special node to encapsulate initializers added into a constructor. Helps to do special optimizations in lowering, doesn't survive the lowering. --> <Node Name="BoundTypeOrInstanceInitializers" Base="BoundStatementList"> </Node> <Node Name="BoundNameOfOperator" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Argument" Type="BoundExpression" Null="disallow"/> <Field Name="ConstantValueOpt" Type="ConstantValue" Null="disallow"/> </Node> <AbstractNode Name="BoundInterpolatedStringBase" Base="BoundExpression"> <!-- The sequence of parts of an interpolated string. The even numbered positions (starting with 0) are from the literal parts of the input. The odd numbered positions are the string inserts. If the interpolated string has been bound using the builder pattern, literals are replaced with calls. --> <Field Name="Parts" Type="ImmutableArray&lt;BoundExpression&gt;"/> <Field Name="ConstantValueOpt" Type="ConstantValue?"/> </AbstractNode> <Node Name="BoundUnconvertedInterpolatedString" Base="BoundInterpolatedStringBase"> </Node> <Node Name="BoundInterpolatedString" Base="BoundInterpolatedStringBase"> <Field Name="InterpolationData" Type="InterpolatedStringHandlerData?"/> </Node> <Node Name="BoundInterpolatedStringHandlerPlaceholder" Base="BoundValuePlaceholderBase"/> <!-- A typed expression placeholder for the arguments to the constructor call for an interpolated string handler conversion. We intentionally use a placeholder for overload resolution here to ensure that no conversion from expression can occur. This node is only used for intermediate binding and does not survive local rewriting. --> <Node Name="BoundInterpolatedStringArgumentPlaceholder" Base="BoundValuePlaceholderBase"> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow" /> <!-- The index in the containing member of the argument this is the placeholder for. Should be a positive number or one of the constants in the other part of the partial class. --> <Field Name="ArgumentIndex" Type="int" /> <Field Name="ValSafeToEscape" Type="uint" /> </Node> <Node Name="BoundStringInsert" Base="BoundExpression"> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <Field Name="Value" Type="BoundExpression" Null="disallow"/> <Field Name="Alignment" Type="BoundExpression?"/> <Field Name="Format" Type="BoundLiteral?"/> <Field Name="IsInterpolatedStringHandlerAppendCall" Type="bool"/> </Node> <!-- An 'is pattern'. The fields DecisionDag, WhenTrueLabel, and WhenFalseLabel represent the inner pattern after removing any outer 'not's, so consumers (such as lowering and definite assignment of the local in 'is not Type t') will need to compensate for negated patterns. IsNegated is set if Pattern is the negated form of the inner pattern represented by DecisionDag. --> <Node Name="BoundIsPatternExpression" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> <Field Name="Pattern" Type="BoundPattern" Null="disallow"/> <Field Name="IsNegated" Type="bool"/> <Field Name="DecisionDag" Type="BoundDecisionDag" Null="disallow" SkipInVisitor="true"/> <Field Name="WhenTrueLabel" Type="LabelSymbol" Null="disallow"/> <Field Name="WhenFalseLabel" Type="LabelSymbol" Null="disallow"/> </Node> <AbstractNode Name="BoundPattern" Base="BoundNode"> <Field Name="InputType" Type="TypeSymbol" Null="disallow"/> <Field Name="NarrowedType" Type="TypeSymbol" Null="disallow"/> </AbstractNode> <Node Name="BoundConstantPattern" Base="BoundPattern"> <Field Name="Value" Type="BoundExpression"/> <Field Name="ConstantValue" Type="ConstantValue" Null="disallow"/> </Node> <Node Name="BoundDiscardPattern" Base="BoundPattern"> </Node> <Node Name="BoundDeclarationPattern" Base="BoundPattern"> <!-- Variable is a local symbol, or in the case of top-level code in scripts and interactive, a field that is a member of the script class. Variable is null if `_` is used. --> <Field Name="Variable" Type="Symbol?"/> <!-- VariableAccess is an access to the declared variable, suitable for use in the lowered form in either an lvalue or rvalue position. We maintain it separately from the Symbol to facilitate lowerings in which the variable is no longer a simple variable access (e.g. in the expression evaluator). It is expected to be logically side-effect free. The necessity of this member is a consequence of a design issue documented in https://github.com/dotnet/roslyn/issues/13960 . When that is fixed this field can be removed. --> <Field Name="VariableAccess" Type="BoundExpression?"/> <Field Name="DeclaredType" Type="BoundTypeExpression" Null="disallow"/> <Field Name="IsVar" Type="bool"/> </Node> <Node Name="BoundRecursivePattern" Base="BoundPattern"> <Field Name="DeclaredType" Type="BoundTypeExpression?"/> <Field Name="DeconstructMethod" Type="MethodSymbol?"/> <Field Name="Deconstruction" Type="ImmutableArray&lt;BoundPositionalSubpattern&gt;" Null="allow"/> <Field Name="Properties" Type="ImmutableArray&lt;BoundPropertySubpattern&gt;" Null="allow"/> <!-- Variable is a local symbol, or in the case of top-level code in scripts and interactive, a field that is a member of the script class. Variable is null if `_` is used or if the identifier is omitted. --> <Field Name="Variable" Type="Symbol?"/> <!-- VariableAccess is an access to the declared variable, suitable for use in the lowered form in either an lvalue or rvalue position. We maintain it separately from the Symbol to facilitate lowerings in which the variable is no longer a simple variable access (e.g. in the expression evaluator). It is expected to be logically side-effect free. The necessity of this member is a consequence of a design issue documented in https://github.com/dotnet/roslyn/issues/13960 . When that is fixed this field can be removed. --> <Field Name="VariableAccess" Type="BoundExpression?"/> <Field Name="IsExplicitNotNullTest" Type="bool"/> </Node> <Node Name="BoundITuplePattern" Base="BoundPattern"> <Field Name="GetLengthMethod" Type="MethodSymbol" Null="disallow"/> <Field Name="GetItemMethod" Type="MethodSymbol" Null="disallow"/> <Field Name="Subpatterns" Type="ImmutableArray&lt;BoundPositionalSubpattern&gt;" Null="disallow"/> </Node> <AbstractNode Name="BoundSubpattern" Base="BoundNode"> <Field Name="Pattern" Type="BoundPattern"/> </AbstractNode> <Node Name="BoundPositionalSubpattern" Base="BoundSubpattern"> <!-- The tuple element or parameter in a positional pattern. --> <Field Name="Symbol" Type="Symbol?"/> </Node> <Node Name="BoundPropertySubpattern" Base="BoundSubpattern"> <!-- The property or field access in a property pattern. --> <Field Name="Member" Type="BoundPropertySubpatternMember?"/> </Node> <Node Name="BoundPropertySubpatternMember" Base="BoundNode"> <Field Name="Receiver" Type="BoundPropertySubpatternMember?"/> <Field Name="Symbol" Type="Symbol?"/> <Field Name="Type" Type="TypeSymbol"/> </Node> <Node Name="BoundTypePattern" Base="BoundPattern"> <Field Name="DeclaredType" Type="BoundTypeExpression"/> <Field Name="IsExplicitNotNullTest" Type="bool"/> </Node> <Node Name="BoundBinaryPattern" Base="BoundPattern"> <Field Name="Disjunction" Type="bool"/> <Field Name="Left" Type="BoundPattern"/> <Field Name="Right" Type="BoundPattern"/> </Node> <Node Name="BoundNegatedPattern" Base="BoundPattern"> <Field Name="Negated" Type="BoundPattern"/> </Node> <Node Name="BoundRelationalPattern" Base="BoundPattern"> <Field Name="Relation" Type="BinaryOperatorKind"/> <Field Name="Value" Type="BoundExpression"/> <Field Name="ConstantValue" Type="ConstantValue" Null="disallow"/> </Node> <Node Name="BoundDiscardExpression" Base="BoundExpression"> <!-- A discarded value, when a designator uses `_`. When the type is given as `var, its Type is null before type inference, and it is replaced by a BoundDiscardExpression with a non-null type after inference. --> <Field Name="Type" Type="TypeSymbol?" Override="true"/> </Node> <Node Name="BoundThrowExpression" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> </Node> <AbstractNode Name="VariablePendingInference" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> <!-- A local symbol or a field symbol representing the variable --> <Field Name="VariableSymbol" Type="Symbol"/> <!-- A field receiver when VariableSymbol is a field --> <Field Name="ReceiverOpt" Type="BoundExpression?"/> </AbstractNode> <!-- The node is transformed into BoundLocal or BoundFieldAccess after inference --> <Node Name="OutVariablePendingInference" Base="VariablePendingInference" /> <!-- The node is transformed into BoundLocal or BoundFieldAccess after inference --> <Node Name="DeconstructionVariablePendingInference" Base="VariablePendingInference" /> <!-- The node is transformed into BoundDeconstructValuePlaceholder after inference --> <Node Name="OutDeconstructVarPendingInference" Base="BoundExpression"> <!-- Type is not significant for this node type; always null --> <Field Name="Type" Type="TypeSymbol?" Override="true" Null="always"/> </Node> <AbstractNode Name="BoundMethodBodyBase" Base="BoundNode"> <Field Name="BlockBody" Type="BoundBlock?"/> <Field Name="ExpressionBody" Type="BoundBlock?"/> </AbstractNode> <Node Name="BoundNonConstructorMethodBody" Base="BoundMethodBodyBase"> </Node> <Node Name="BoundConstructorMethodBody" Base="BoundMethodBodyBase"> <Field Name="Locals" Type="ImmutableArray&lt;LocalSymbol&gt;"/> <Field Name="Initializer" Type="BoundStatement?"/> </Node> <!-- Node only used during nullability flow analysis to represent an expression with an updated nullability --> <Node Name="BoundExpressionWithNullability" Base="BoundExpression"> <Field Name="Expression" Type="BoundExpression" Null="disallow"/> <Field Name="Type" Type="TypeSymbol?" Override="true"/> <!-- We use null Type for placeholders representing out vars --> <Field Name="NullableAnnotation" Type="NullableAnnotation"/> </Node> <Node Name="BoundWithExpression" Base="BoundExpression"> <!-- Non-null type is required for this node kind --> <Field Name="Type" Type="TypeSymbol" Override="true" Null="disallow"/> <Field Name="Receiver" Type="BoundExpression" /> <!-- CloneMethod may be null in error scenarios--> <Field Name="CloneMethod" Type="MethodSymbol?" /> <!-- Members and expressions passed as arguments to the With expression. --> <Field Name="InitializerExpression" Type="BoundObjectInitializerExpressionBase" /> </Node> </Tree>
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./.vscode/launch.json
{ // Use IntelliSense to find out which attributes exist for C# debugging // Use hover for the description of the existing attributes // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md "version": "0.2.0", "configurations": [ { "name": "Launch BuildValidator.dll", "type": "coreclr", "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. "program": "${workspaceFolder}/artifacts/bin/BuildValidator/Debug/netcoreapp3.1/BuildValidator.dll", "args": [ "--assembliesPath", "./artifacts/obj/csc/Debug/netcoreapp3.1", "--referencesPath", "./artifacts/bin", "--referencesPath", "C:/Program Files/dotnet/packs/Microsoft.AspNetCore.App.Ref", "--referencesPath", "C:/Program Files/dotnet/packs/Microsoft.NETCore.App.Ref", "--debugPath", "./artifacts/BuildValidator", "--sourcePath", "." ], "cwd": "${workspaceFolder}", "stopAtEntry": false, "console": "internalConsole" }, { "name": "Launch RunTests.dll", "type": "coreclr", "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. "program": "${workspaceFolder}/artifacts/bin/RunTests/Debug/netcoreapp3.1/RunTests.dll", "args": ["--tfm", "netcoreapp3.1", "--sequential", "--html"], "cwd": "${workspaceFolder}/artifacts/bin/RunTests", "stopAtEntry": false, "console": "internalConsole" }, { "name": "Launch PrepareTests.dll", "type": "coreclr", "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. "program": "${workspaceFolder}/artifacts/bin/PrepareTests/Debug/net5.0/PrepareTests.dll", "args": [ "--source", "${workspaceFolder}", "--destination", "${workspaceFolder}/artifacts/testPayload" ], "cwd": "${workspaceFolder}/artifacts/bin/PrepareTests", "stopAtEntry": false, "console": "internalConsole" }, { "name": ".NET Core Launch (console)", "type": "coreclr", "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. "program": "${workspaceFolder}/src/Compilers/CSharp/csc/bin/Debug/netcoreapp2.1/csc.dll", "args": [], "cwd": "${workspaceFolder}/src/Compilers/CSharp/csc", // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console "console": "internalConsole", "stopAtEntry": false }, { "name": ".NET Core Attach", "type": "coreclr", "request": "attach", "processId": "${command:pickProcess}" } ] }
{ // Use IntelliSense to find out which attributes exist for C# debugging // Use hover for the description of the existing attributes // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md "version": "0.2.0", "configurations": [ { "name": "Launch BuildValidator.dll", "type": "coreclr", "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. "program": "${workspaceFolder}/artifacts/bin/BuildValidator/Debug/netcoreapp3.1/BuildValidator.dll", "args": [ "--assembliesPath", "./artifacts/obj/csc/Debug/netcoreapp3.1", "--referencesPath", "./artifacts/bin", "--referencesPath", "C:/Program Files/dotnet/packs/Microsoft.AspNetCore.App.Ref", "--referencesPath", "C:/Program Files/dotnet/packs/Microsoft.NETCore.App.Ref", "--debugPath", "./artifacts/BuildValidator", "--sourcePath", "." ], "cwd": "${workspaceFolder}", "stopAtEntry": false, "console": "internalConsole" }, { "name": "Launch RunTests.dll", "type": "coreclr", "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. "program": "${workspaceFolder}/artifacts/bin/RunTests/Debug/netcoreapp3.1/RunTests.dll", "args": ["--tfm", "netcoreapp3.1", "--sequential", "--html"], "cwd": "${workspaceFolder}/artifacts/bin/RunTests", "stopAtEntry": false, "console": "internalConsole" }, { "name": "Launch PrepareTests.dll", "type": "coreclr", "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. "program": "${workspaceFolder}/artifacts/bin/PrepareTests/Debug/net5.0/PrepareTests.dll", "args": [ "--source", "${workspaceFolder}", "--destination", "${workspaceFolder}/artifacts/testPayload" ], "cwd": "${workspaceFolder}/artifacts/bin/PrepareTests", "stopAtEntry": false, "console": "internalConsole" }, { "name": ".NET Core Launch (console)", "type": "coreclr", "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. "program": "${workspaceFolder}/src/Compilers/CSharp/csc/bin/Debug/netcoreapp2.1/csc.dll", "args": [], "cwd": "${workspaceFolder}/src/Compilers/CSharp/csc", // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console "console": "internalConsole", "stopAtEntry": false }, { "name": ".NET Core Attach", "type": "coreclr", "request": "attach", "processId": "${command:pickProcess}" } ] }
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/ProjectReference.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProjectGuid>{3DA47258-9CAB-4FB9-9C04-1F367A2C2700}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject_ProjectToProjectReference</RootNamespace> <AssemblyName>CSharpProject_ProjectToProjectReference</AssemblyName> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> <Reference Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpConsole.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="CSharpProject.csproj"> <Project>{686dd036-86aa-443e-8a10-ddb43266a8c4}</Project> <Name>CSharpProject</Name> <Aliases>ProjAlias</Aliases> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProjectGuid>{3DA47258-9CAB-4FB9-9C04-1F367A2C2700}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject_ProjectToProjectReference</RootNamespace> <AssemblyName>CSharpProject_ProjectToProjectReference</AssemblyName> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> <Reference Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpConsole.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="CSharpProject.csproj"> <Project>{686dd036-86aa-443e-8a10-ddb43266a8c4}</Project> <Name>CSharpProject</Name> <Aliases>ProjAlias</Aliases> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/NuGet/Microsoft.Net.Compilers.Toolset/Microsoft.Net.Compilers.Toolset.Package.csproj
<!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> <IsPackable>true</IsPackable> <NuspecPackageId>Microsoft.Net.Compilers.Toolset</NuspecPackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <DevelopmentDependency>true</DevelopmentDependency> <PackageDescription> .NET Compilers Toolset Package. Referencing this package will cause the project to be built using the C# and Visual Basic compilers contained in the package, as opposed to the version installed with MSBuild. This package is primarily intended as a method for rapidly shipping hotfixes to customers. Using it as a long term solution for providing newer compilers on older MSBuild installations is explicitly not supported. That can and will break on a regular basis. The supported mechanism for providing new compilers in a build enviroment is updating to the newer .NET SDK or Visual Studio Build Tools SKU. This package requires either MSBuild 16.3 and .NET Desktop 4.7.2+ or .NET Core 2.1+ $(RoslynPackageDescriptionDetails) </PackageDescription> <TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_GetFilesToPackage</TargetsForTfmSpecificContentInPackage> <!-- Remove NU5128 once https://github.com/NuGet/Home/issues/8583 is fixed --> <NoWarn>$(NoWarn);NU5100;NU5128</NoWarn> <_DependsOn Condition="'$(TargetFramework)' == 'net472'">InitializeDesktopCompilerArtifacts</_DependsOn> <_DependsOn Condition="'$(TargetFramework)' == 'netcoreapp3.1'">InitializeCoreClrCompilerArtifacts</_DependsOn> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\CSharp\csc\csc.csproj" PrivateAssets="All"/> <ProjectReference Include="..\..\Compilers\VisualBasic\vbc\vbc.csproj" PrivateAssets="All"/> <ProjectReference Include="..\..\Interactive\csi\csi.csproj" PrivateAssets="All"/> <ProjectReference Include="..\..\Compilers\Core\MSBuildTask\Microsoft.Build.Tasks.CodeAnalysis.csproj" PrivateAssets="All"/> <ProjectReference Include="..\..\Compilers\Server\VBCSCompiler\VBCSCompiler.csproj" PrivateAssets="All"/> <ProjectReference Update="@(ProjectReference)" Targets="Publish" ReferenceOutputAssembly="false" SkipGetTargetFrameworkProperties="true" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" SetTargetFramework="TargetFramework=netcoreapp3.1" /> </ItemGroup> <Target Name="_GetFilesToPackage" DependsOnTargets="$(_DependsOn)"> <ItemGroup> <_File Include="@(DesktopCompilerArtifact)" TargetDir="tasks/net472"/> <_File Include="@(DesktopCompilerResourceArtifact)" TargetDir="tasks/net472"/> <_File Include="@(CoreClrCompilerBuildArtifact)" TargetDir="tasks/netcoreapp3.1"/> <_File Include="@(CoreClrCompilerToolsArtifact)" TargetDir="tasks/netcoreapp3.1"/> <_File Include="@(CoreClrCompilerBinArtifact)" TargetDir="tasks/netcoreapp3.1/bincore"/> <_File Include="@(CoreClrCompilerBinRuntimesArtifact)" TargetDir="tasks/netcoreapp3.1/bincore/runtimes"/> <_File Include="$(MSBuildProjectDirectory)\build\**\*.*" Condition="'$(TargetFramework)' == 'net472'" TargetDir="build" /> <TfmSpecificPackageFile Include="@(_File)" PackagePath="%(_File.TargetDir)/%(_File.RecursiveDir)%(_File.FileName)%(_File.Extension)" /> </ItemGroup> </Target> <Import Project="DesktopCompilerArtifacts.targets" Condition="'$(TargetFramework)' == 'net472'" /> <Import Project="CoreClrCompilerArtifacts.targets" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" /> </Project>
<!-- 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. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> <IsPackable>true</IsPackable> <NuspecPackageId>Microsoft.Net.Compilers.Toolset</NuspecPackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <DevelopmentDependency>true</DevelopmentDependency> <PackageDescription> .NET Compilers Toolset Package. Referencing this package will cause the project to be built using the C# and Visual Basic compilers contained in the package, as opposed to the version installed with MSBuild. This package is primarily intended as a method for rapidly shipping hotfixes to customers. Using it as a long term solution for providing newer compilers on older MSBuild installations is explicitly not supported. That can and will break on a regular basis. The supported mechanism for providing new compilers in a build enviroment is updating to the newer .NET SDK or Visual Studio Build Tools SKU. This package requires either MSBuild 16.3 and .NET Desktop 4.7.2+ or .NET Core 2.1+ $(RoslynPackageDescriptionDetails) </PackageDescription> <TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_GetFilesToPackage</TargetsForTfmSpecificContentInPackage> <!-- Remove NU5128 once https://github.com/NuGet/Home/issues/8583 is fixed --> <NoWarn>$(NoWarn);NU5100;NU5128</NoWarn> <_DependsOn Condition="'$(TargetFramework)' == 'net472'">InitializeDesktopCompilerArtifacts</_DependsOn> <_DependsOn Condition="'$(TargetFramework)' == 'netcoreapp3.1'">InitializeCoreClrCompilerArtifacts</_DependsOn> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\CSharp\csc\csc.csproj" PrivateAssets="All"/> <ProjectReference Include="..\..\Compilers\VisualBasic\vbc\vbc.csproj" PrivateAssets="All"/> <ProjectReference Include="..\..\Interactive\csi\csi.csproj" PrivateAssets="All"/> <ProjectReference Include="..\..\Compilers\Core\MSBuildTask\Microsoft.Build.Tasks.CodeAnalysis.csproj" PrivateAssets="All"/> <ProjectReference Include="..\..\Compilers\Server\VBCSCompiler\VBCSCompiler.csproj" PrivateAssets="All"/> <ProjectReference Update="@(ProjectReference)" Targets="Publish" ReferenceOutputAssembly="false" SkipGetTargetFrameworkProperties="true" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" SetTargetFramework="TargetFramework=netcoreapp3.1" /> </ItemGroup> <Target Name="_GetFilesToPackage" DependsOnTargets="$(_DependsOn)"> <ItemGroup> <_File Include="@(DesktopCompilerArtifact)" TargetDir="tasks/net472"/> <_File Include="@(DesktopCompilerResourceArtifact)" TargetDir="tasks/net472"/> <_File Include="@(CoreClrCompilerBuildArtifact)" TargetDir="tasks/netcoreapp3.1"/> <_File Include="@(CoreClrCompilerToolsArtifact)" TargetDir="tasks/netcoreapp3.1"/> <_File Include="@(CoreClrCompilerBinArtifact)" TargetDir="tasks/netcoreapp3.1/bincore"/> <_File Include="@(CoreClrCompilerBinRuntimesArtifact)" TargetDir="tasks/netcoreapp3.1/bincore/runtimes"/> <_File Include="$(MSBuildProjectDirectory)\build\**\*.*" Condition="'$(TargetFramework)' == 'net472'" TargetDir="build" /> <TfmSpecificPackageFile Include="@(_File)" PackagePath="%(_File.TargetDir)/%(_File.RecursiveDir)%(_File.FileName)%(_File.Extension)" /> </ItemGroup> </Target> <Import Project="DesktopCompilerArtifacts.targets" Condition="'$(TargetFramework)' == 'net472'" /> <Import Project="CoreClrCompilerArtifacts.targets" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" /> </Project>
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/IProjectFileLoader.cs
// 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.MSBuild.Build; namespace Microsoft.CodeAnalysis.MSBuild { internal interface IProjectFileLoader : ILanguageService { string Language { get; } Task<IProjectFile> LoadProjectFileAsync( string path, ProjectBuildManager buildManager, CancellationToken cancellationToken); } }
// 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.MSBuild.Build; namespace Microsoft.CodeAnalysis.MSBuild { internal interface IProjectFileLoader : ILanguageService { string Language { get; } Task<IProjectFile> LoadProjectFileAsync( string path, ProjectBuildManager buildManager, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/CSharpTest/BlockCommentEditing/BlockCommentEditingTests.cs
// 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. #nullable disable using Microsoft.CodeAnalysis.Editor.CSharp.BlockCommentEditing; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.BlockCommentEditing { public class BlockCommentEditingTests : AbstractTypingCommandHandlerTest<ReturnKeyCommandArgs> { [WorkItem(11057, "https://github.com/dotnet/roslyn/issues/11057")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EdgeCase0() { var code = @" $$/**/ "; var expected = @" $$/**/ "; Verify(code, expected); } [WorkItem(11057, "https://github.com/dotnet/roslyn/issues/11057")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EdgeCase1() { var code = @" /**/$$ "; var expected = @" /**/ $$ "; Verify(code, expected); } [WorkItem(11056, "https://github.com/dotnet/roslyn/issues/11056")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EdgeCase2() { var code = @" $$/* */ "; var expected = @" $$/* */ "; Verify(code, expected); } [WorkItem(11056, "https://github.com/dotnet/roslyn/issues/11056")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EdgeCase3() { var code = @" /* */$$ "; var expected = @" /* */ $$ "; Verify(code, expected); } [WorkItem(16128, "https://github.com/dotnet/roslyn/issues/16128")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EofCase0() { var code = @" /* */$$"; var expected = @" /* */ $$"; Verify(code, expected); } [WorkItem(16128, "https://github.com/dotnet/roslyn/issues/16128")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EofCase1() { var code = @" /*$$"; var expected = @" /* * $$"; Verify(code, expected); } [WorkItem(16128, "https://github.com/dotnet/roslyn/issues/16128")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EofCase2() { var code = @" /***$$"; var expected = @" /*** * $$"; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine0() { var code = @" /*$$ "; var expected = @" /* * $$ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine1() { var code = @" /*$$*/ "; var expected = @" /* $$*/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine2() { var code = @" /*$$ */ "; var expected = @" /* * $$*/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine3() { var code = @" /* $$ 1. */ "; var expected = @" /* * $$1. */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine4() { var code = @" /* 1.$$ */ "; var expected = @" /* 1. * $$ */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine5() { var code = @" /********$$ "; var expected = @" /******** * $$ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine6() { var code = @" /**$$ "; var expected = @" /** * $$ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine7() { var code = @" /* $$ "; var expected = @" /* * $$ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void NotInsertOnStartLine0() { var code = @" /$$* */ "; var expected = @" / $$* */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine0() { var code = @" /* *$$ "; var expected = @" /* * *$$ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine1() { var code = @" /* *$$*/ "; var expected = @" /* * $$*/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine2() { var code = @" /* *$$ */ "; var expected = @" /* * *$$*/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine3() { var code = @" /* * $$ 1. */ "; var expected = @" /* * * $$1. */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine4() { var code = @" /* * 1.$$ */ "; var expected = @" /* * 1. * $$ */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine5() { var code = @" /* * 1. * $$ */ "; var expected = @" /* * 1. * * $$ */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine6() { var code = @" /* $$ * */ "; var expected = @" /* $$* */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine7() { var code = @" /* *************$$ */ "; var expected = @" /* ************* *$$ */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine8() { var code = @" /** *$$ */ "; var expected = @" /** * *$$ */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine9() { var code = @" /** *$$ "; var expected = @" /** * *$$ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnEndLine0() { var code = @" /* *$$/ "; var expected = @" /* * *$$/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnEndLine1() { var code = @" /** *$$/ "; var expected = @" /** * *$$/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnEndLine2() { var code = @" /** * *$$/ "; var expected = @" /** * * *$$/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnEndLine3() { var code = @" /* $$ */ "; var expected = @" /* $$*/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnEndLine4() { var code = @" /* $$*/ "; var expected = @" /* $$*/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void NotInsertInVerbatimString0() { var code = @" var code = @"" /*$$ ""; "; var expected = @" var code = @"" /* $$ ""; "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void NotInsertInVerbatimString1() { var code = @" var code = @"" /* *$$ ""; "; var expected = @" var code = @"" /* * $$ ""; "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void BoundCheckInsertOnStartLine0() { var code = @" /$$*"; var expected = @" / $$*"; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void BoundCheckInsertOnStartLine1() { var code = @" /*$$ "; var expected = @" /* * $$"; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void BoundCheckInsertOnMiddleLine() { var code = @" /* *$$ "; var expected = @" /* * *$$"; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void BoundCheckInsertOnEndLine() { var code = @" /* *$$/"; var expected = @" /* * *$$/"; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine2_Tab() { var code = @" /*$$<tab>*/ "; var expected = @" /* * $$*/ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine3_Tab() { var code = @" /*<tab>$$<tab>1. */ "; var expected = @" /*<tab> *<tab>$$1. */ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine4_Tab() { var code = @" /* <tab>1.$$ */ "; var expected = @" /* <tab>1. * <tab>$$ */ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine6_Tab() { var code = @" /*<tab>$$ "; var expected = @" /*<tab> *<tab>$$ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine2_Tab() { var code = @" /* *$$<tab>*/ "; var expected = @" /* * *$$*/ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine3_Tab() { var code = @" /* * $$<tab>1. */ "; var expected = @" /* * * $$1. */ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine4_Tab() { var code = @" /* * <tab>1.$$ */ "; var expected = @" /* * <tab>1. * <tab>$$ */ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine5_Tab() { var code = @" /* *<tab> 1. *<tab> $$ */ "; var expected = @" /* *<tab> 1. *<tab> *<tab> $$ */ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InLanguageConstructTrailingTrivia() { var code = @" class C { int i; /*$$ } "; var expected = @" class C { int i; /* * $$ } "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InLanguageConstructTrailingTrivia_Tabs() { var code = @" class C { <tab>int i; /*$$ } "; var expected = @" class C { <tab>int i; /* <tab> * $$ } "; VerifyTabs(code, expected); } protected override TestWorkspace CreateTestWorkspace(string initialMarkup) => TestWorkspace.CreateCSharp(initialMarkup); protected override (ReturnKeyCommandArgs, string insertionText) CreateCommandArgs(ITextView textView, ITextBuffer textBuffer) => (new ReturnKeyCommandArgs(textView, textBuffer), "\r\n"); internal override ICommandHandler<ReturnKeyCommandArgs> GetCommandHandler(TestWorkspace workspace) => Assert.IsType<BlockCommentEditingCommandHandler>(workspace.GetService<ICommandHandler>(ContentTypeNames.CSharpContentType, nameof(BlockCommentEditingCommandHandler))); } }
// 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. #nullable disable using Microsoft.CodeAnalysis.Editor.CSharp.BlockCommentEditing; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.BlockCommentEditing { public class BlockCommentEditingTests : AbstractTypingCommandHandlerTest<ReturnKeyCommandArgs> { [WorkItem(11057, "https://github.com/dotnet/roslyn/issues/11057")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EdgeCase0() { var code = @" $$/**/ "; var expected = @" $$/**/ "; Verify(code, expected); } [WorkItem(11057, "https://github.com/dotnet/roslyn/issues/11057")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EdgeCase1() { var code = @" /**/$$ "; var expected = @" /**/ $$ "; Verify(code, expected); } [WorkItem(11056, "https://github.com/dotnet/roslyn/issues/11056")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EdgeCase2() { var code = @" $$/* */ "; var expected = @" $$/* */ "; Verify(code, expected); } [WorkItem(11056, "https://github.com/dotnet/roslyn/issues/11056")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EdgeCase3() { var code = @" /* */$$ "; var expected = @" /* */ $$ "; Verify(code, expected); } [WorkItem(16128, "https://github.com/dotnet/roslyn/issues/16128")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EofCase0() { var code = @" /* */$$"; var expected = @" /* */ $$"; Verify(code, expected); } [WorkItem(16128, "https://github.com/dotnet/roslyn/issues/16128")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EofCase1() { var code = @" /*$$"; var expected = @" /* * $$"; Verify(code, expected); } [WorkItem(16128, "https://github.com/dotnet/roslyn/issues/16128")] [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void EofCase2() { var code = @" /***$$"; var expected = @" /*** * $$"; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine0() { var code = @" /*$$ "; var expected = @" /* * $$ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine1() { var code = @" /*$$*/ "; var expected = @" /* $$*/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine2() { var code = @" /*$$ */ "; var expected = @" /* * $$*/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine3() { var code = @" /* $$ 1. */ "; var expected = @" /* * $$1. */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine4() { var code = @" /* 1.$$ */ "; var expected = @" /* 1. * $$ */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine5() { var code = @" /********$$ "; var expected = @" /******** * $$ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine6() { var code = @" /**$$ "; var expected = @" /** * $$ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine7() { var code = @" /* $$ "; var expected = @" /* * $$ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void NotInsertOnStartLine0() { var code = @" /$$* */ "; var expected = @" / $$* */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine0() { var code = @" /* *$$ "; var expected = @" /* * *$$ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine1() { var code = @" /* *$$*/ "; var expected = @" /* * $$*/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine2() { var code = @" /* *$$ */ "; var expected = @" /* * *$$*/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine3() { var code = @" /* * $$ 1. */ "; var expected = @" /* * * $$1. */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine4() { var code = @" /* * 1.$$ */ "; var expected = @" /* * 1. * $$ */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine5() { var code = @" /* * 1. * $$ */ "; var expected = @" /* * 1. * * $$ */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine6() { var code = @" /* $$ * */ "; var expected = @" /* $$* */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine7() { var code = @" /* *************$$ */ "; var expected = @" /* ************* *$$ */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine8() { var code = @" /** *$$ */ "; var expected = @" /** * *$$ */ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine9() { var code = @" /** *$$ "; var expected = @" /** * *$$ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnEndLine0() { var code = @" /* *$$/ "; var expected = @" /* * *$$/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnEndLine1() { var code = @" /** *$$/ "; var expected = @" /** * *$$/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnEndLine2() { var code = @" /** * *$$/ "; var expected = @" /** * * *$$/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnEndLine3() { var code = @" /* $$ */ "; var expected = @" /* $$*/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnEndLine4() { var code = @" /* $$*/ "; var expected = @" /* $$*/ "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void NotInsertInVerbatimString0() { var code = @" var code = @"" /*$$ ""; "; var expected = @" var code = @"" /* $$ ""; "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void NotInsertInVerbatimString1() { var code = @" var code = @"" /* *$$ ""; "; var expected = @" var code = @"" /* * $$ ""; "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void BoundCheckInsertOnStartLine0() { var code = @" /$$*"; var expected = @" / $$*"; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void BoundCheckInsertOnStartLine1() { var code = @" /*$$ "; var expected = @" /* * $$"; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void BoundCheckInsertOnMiddleLine() { var code = @" /* *$$ "; var expected = @" /* * *$$"; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void BoundCheckInsertOnEndLine() { var code = @" /* *$$/"; var expected = @" /* * *$$/"; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine2_Tab() { var code = @" /*$$<tab>*/ "; var expected = @" /* * $$*/ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine3_Tab() { var code = @" /*<tab>$$<tab>1. */ "; var expected = @" /*<tab> *<tab>$$1. */ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine4_Tab() { var code = @" /* <tab>1.$$ */ "; var expected = @" /* <tab>1. * <tab>$$ */ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnStartLine6_Tab() { var code = @" /*<tab>$$ "; var expected = @" /*<tab> *<tab>$$ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine2_Tab() { var code = @" /* *$$<tab>*/ "; var expected = @" /* * *$$*/ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine3_Tab() { var code = @" /* * $$<tab>1. */ "; var expected = @" /* * * $$1. */ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine4_Tab() { var code = @" /* * <tab>1.$$ */ "; var expected = @" /* * <tab>1. * <tab>$$ */ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InsertOnMiddleLine5_Tab() { var code = @" /* *<tab> 1. *<tab> $$ */ "; var expected = @" /* *<tab> 1. *<tab> *<tab> $$ */ "; VerifyTabs(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InLanguageConstructTrailingTrivia() { var code = @" class C { int i; /*$$ } "; var expected = @" class C { int i; /* * $$ } "; Verify(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BlockCommentEditing)] public void InLanguageConstructTrailingTrivia_Tabs() { var code = @" class C { <tab>int i; /*$$ } "; var expected = @" class C { <tab>int i; /* <tab> * $$ } "; VerifyTabs(code, expected); } protected override TestWorkspace CreateTestWorkspace(string initialMarkup) => TestWorkspace.CreateCSharp(initialMarkup); protected override (ReturnKeyCommandArgs, string insertionText) CreateCommandArgs(ITextView textView, ITextBuffer textBuffer) => (new ReturnKeyCommandArgs(textView, textBuffer), "\r\n"); internal override ICommandHandler<ReturnKeyCommandArgs> GetCommandHandler(TestWorkspace workspace) => Assert.IsType<BlockCommentEditingCommandHandler>(workspace.GetService<ICommandHandler>(ContentTypeNames.CSharpContentType, nameof(BlockCommentEditingCommandHandler))); } }
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/CSharp/Test/Semantic/Semantics/StackAllocSpanExpressionsTests.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class StackAllocSpanExpressionsTests : CompilingTestBase { [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Implicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method() { Test obj1 = stackalloc int[10]; var obj2 = stackalloc int[10]; Span<int> obj3 = stackalloc int[10]; int* obj4 = stackalloc int[10]; double* obj5 = stackalloc int[10]; } public static implicit operator Test(int* value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[10]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[10]").WithArguments("int", "double*").WithLocation(11, 24)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(5, variables.Count()); var obj1 = variables.ElementAt(0); Assert.Equal("obj1", obj1.Identifier.Text); var obj1Value = model.GetSemanticInfoSummary(obj1.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj1Value.Type).PointedAtType.SpecialType); Assert.Equal("Test", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.ImplicitUserDefined, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Explicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method() { Test obj1 = (Test)stackalloc int[10]; var obj2 = stackalloc int[10]; Span<int> obj3 = stackalloc int[10]; int* obj4 = stackalloc int[10]; double* obj5 = stackalloc int[10]; } public static explicit operator Test(Span<int> value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[10]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[10]").WithArguments("int", "double*").WithLocation(11, 24)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(5, variables.Count()); var obj1 = variables.ElementAt(0); Assert.Equal("obj1", obj1.Identifier.Text); Assert.Equal(SyntaxKind.CastExpression, obj1.Initializer.Value.Kind()); var obj1Value = model.GetSemanticInfoSummary(((CastExpressionSyntax)obj1.Initializer.Value).Expression); Assert.Equal("Span", obj1Value.Type.Name); Assert.Equal("Span", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } [Fact] public void ConversionError() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { double x = stackalloc int[10]; // implicit short y = (short)stackalloc int[10]; // explicit } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[10]; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[10]").WithArguments("int", "double").WithLocation(6, 20), // (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[10]; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[10]").WithArguments("int", "short").WithLocation(7, 19)); } [Fact] public void MissingSpanType() { CreateCompilation(@" class Test { void M() { Span<int> a = stackalloc int [10]; } }").VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a = stackalloc int [10]; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(6, 9), // (6,23): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a = stackalloc int [10]; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [10]").WithArguments("System.Span`1").WithLocation(6, 23)); } [Fact] public void MissingSpanConstructor() { CreateCompilation(@" namespace System { ref struct Span<T> { } class Test { void M() { Span<int> a = stackalloc int [10]; } } }").VerifyEmitDiagnostics( // (11,27): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a = stackalloc int [10]; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [10]").WithArguments("System.Span`1", ".ctor").WithLocation(11, 27)); } [Fact] public void ConditionalExpressionOnSpan_BothStackallocSpans() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { var x = true ? stackalloc int [10] : stackalloc int [5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_Convertible() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x = true ? stackalloc int [10] : (Span<int>)stackalloc int [5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_NoCast() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x = true ? stackalloc int [10] : (Span<int>)stackalloc short [5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,46): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x = true ? stackalloc int [10] : (Span<int>)stackalloc short [5]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [5]").WithArguments("short", "System.Span<int>").WithLocation(7, 46)); } [Fact] public void ConditionalExpressionOnSpan_CompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> a = stackalloc int [10]; var x = true ? stackalloc int [10] : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_IncompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<short> a = stackalloc short [10]; var x = true ? stackalloc int [10] : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,17): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x = true ? stackalloc int [10] : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [10] : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(8, 17) ); } [Fact] public void ConditionalExpressionOnSpan_Nested() { CreateCompilationWithMscorlibAndSpan(@" class Test { bool N() => true; void M() { var x = N() ? N() ? stackalloc int [1] : stackalloc int [2] : N() ? stackalloc int[3] : N() ? stackalloc int[4] : stackalloc int[5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void BooleanOperatorOnSpan_NoTargetTyping() { var source = @" class Test { void M() { if(stackalloc int[10] == stackalloc int[10]) { } } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,12): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // if(stackalloc int[10] == stackalloc int[10]) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 12), // (6,34): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // if(stackalloc int[10] == stackalloc int[10]) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 34) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,12): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if(stackalloc int[10] == stackalloc int[10]) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[10] == stackalloc int[10]").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(6, 12) ); } [Fact] public void NewStackAllocSpanSyntaxProducesErrorsOnEarlierVersions_Statements() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> x = stackalloc int[10]; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,23): error CS8107: Feature 'ref structs' is not available in C# 7. Please use language version 7.2 or greater. // Span<int> x = stackalloc int[10]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc int[10]").WithArguments("ref structs", "7.2").WithLocation(7, 23)); } [Fact] public void NewStackAllocSpanSyntaxProducesErrorsOnEarlierVersions_Expressions() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" class Test { void M(bool condition) { var x = condition ? stackalloc int[10] : stackalloc int[100]; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,15): error CS8107: Feature 'ref structs' is not available in C# 7.0. Please use language version 7.2 or greater. // ? stackalloc int[10] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc int[10]").WithArguments("ref structs", "7.2").WithLocation(7, 15), // (8,15): error CS8107: Feature 'ref structs' is not available in C# 7.0. Please use language version 7.2 or greater. // : stackalloc int[100]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc int[100]").WithArguments("ref structs", "7.2").WithLocation(8, 15)); } [Fact] public void StackAllocSyntaxProducesUnsafeErrorInSafeCode() { CreateCompilation(@" class Test { void M() { var x = stackalloc int[10]; } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x = stackalloc int[10]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[10]").WithLocation(6, 17)); } [Fact] public void StackAllocInUsing1() { var test = @" public class Test { unsafe public static void Main() { using (var v = stackalloc int[1]) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v = stackalloc int[1]) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v = stackalloc int[1]").WithArguments("System.Span<int>").WithLocation(6, 16) ); } [Fact] public void StackAllocInUsing2() { var test = @" public class Test { unsafe public static void Main() { using (System.IDisposable v = stackalloc int[1]) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,39): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v = stackalloc int[1]) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[1]").WithArguments("int", "System.IDisposable").WithLocation(6, 39)); } [Fact] public void ConstStackAllocExpression() { var test = @" unsafe public class Test { void M() { const int* p = stackalloc int[1]; } } "; CreateCompilation(test, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0283: The type 'int*' cannot be declared const // const int* p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(6, 15)); } [Fact] public void RefStackAllocAssignment_ValueToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p = stackalloc int[1]; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p = stackalloc int[1]").WithLocation(7, 23), // (7,27): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int[1]").WithLocation(7, 27)); } [Fact] public void RefStackAllocAssignment_RefToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p = ref stackalloc int[1]; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,31): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // ref Span<int> p = ref stackalloc int[1]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 31) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,31): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p = ref stackalloc int[1]; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int[1]").WithLocation(7, 31) ); } [Fact] public void InvalidPositionForStackAllocSpan() { var test = @" using System; public class Test { void M() { N(stackalloc int[1]); } void N(Span<int> span) { } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int[1]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 11) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void CannotDotIntoStackAllocExpression() { var test = @" public class Test { void M() { int length = (stackalloc int [10]).Length; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length = (stackalloc int [10]).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 23) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void OverloadResolution_Fail() { var test = @" using System; unsafe public class Test { static void Main() { Invoke(stackalloc int [10]); } static void Invoke(Span<short> shortSpan) => Console.WriteLine(""shortSpan""); static void Invoke(Span<bool> boolSpan) => Console.WriteLine(""boolSpan""); static void Invoke(int* intPointer) => Console.WriteLine(""intPointer""); static void Invoke(void* voidPointer) => Console.WriteLine(""voidPointer""); } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [10]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 16) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (7,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [10]); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [10]").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(7, 16) ); } [Fact] public void StackAllocWithDynamic() { CreateCompilation(@" class Program { static void Main() { var d = stackalloc dynamic[10]; } }").VerifyDiagnostics( // (6,33): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d = stackalloc dynamic[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(6, 28)); } [Fact] public void StackAllocWithDynamicSpan() { CreateCompilationWithMscorlibAndSpan(@" using System; class Program { static void Main() { Span<dynamic> d = stackalloc dynamic[10]; } }").VerifyDiagnostics( // (7,38): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d = stackalloc dynamic[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(7, 38)); } [Fact] public void StackAllocAsArgument() { var source = @" class Program { static void N(object p) { } static void Main() { N(stackalloc int[10]); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int[10]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11) ); CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int[10]); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int[10]").WithArguments("1", "System.Span<int>", "object").WithLocation(8, 11) ); } [Fact] public void StackAllocInParenthesis() { var source = @" class Program { static void Main() { var x = (stackalloc int[10]); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x = (stackalloc int[10]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 18) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( ); } [Fact] public void StackAllocInNullConditionalOperator() { var source = @" class Program { static void Main() { var x = stackalloc int[1] ?? stackalloc int[2]; } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,17): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x = stackalloc int[1] ?? stackalloc int[2]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 17), // (6,38): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x = stackalloc int[1] ?? stackalloc int[2]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 38) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (6,17): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x = stackalloc int[1] ?? stackalloc int[2]; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[1] ?? stackalloc int[2]").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(6, 17) ); } [Fact] public void StackAllocInCastAndConditionalOperator() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public void Method() { Test value = true ? new Test() : (Test)stackalloc int[10]; } public static explicit operator Test(Span<int> value) { return new Test(); } }", TestOptions.ReleaseDll).VerifyDiagnostics(); } [Fact] [WorkItem(25038, "https://github.com/dotnet/roslyn/issues/25038")] public void StackAllocToSpanWithRefStructType() { CreateCompilationWithMscorlibAndSpan(@" using System; ref struct S {} class Test { void M() { Span<S> explicitError = default; var implicitError = explicitError.Length > 0 ? stackalloc S[10] : stackalloc S[100]; } }").VerifyDiagnostics( // (8,14): error CS0306: The type 'S' may not be used as a type argument // Span<S> explicitError = default; Diagnostic(ErrorCode.ERR_BadTypeArgument, "S").WithArguments("S").WithLocation(8, 14), // (9,67): error CS0306: The type 'S' may not be used as a type argument // var implicitError = explicitError.Length > 0 ? stackalloc S[10] : stackalloc S[100]; Diagnostic(ErrorCode.ERR_BadTypeArgument, "S[10]").WithArguments("S").WithLocation(9, 67), // (9,86): error CS0306: The type 'S' may not be used as a type argument // var implicitError = explicitError.Length > 0 ? stackalloc S[10] : stackalloc S[100]; Diagnostic(ErrorCode.ERR_BadTypeArgument, "S[100]").WithArguments("S").WithLocation(9, 86) ); } [Fact] [WorkItem(25086, "https://github.com/dotnet/roslyn/issues/25086")] public void StaackAllocToSpanWithCustomSpanAndConstraints() { var code = @" using System; namespace System { public unsafe readonly ref struct Span<T> where T : IComparable { public Span(void* ptr, int length) { Length = length; } public int Length { get; } } } struct NonComparable { } class Test { void M() { Span<NonComparable> explicitError = default; var implicitError = explicitError.Length > 0 ? stackalloc NonComparable[10] : stackalloc NonComparable[100]; } }"; var references = new List<MetadataReference>() { MscorlibRef_v4_0_30316_17626, SystemCoreRef, CSharpRef }; CreateEmptyCompilation(code, references, TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (19,14): error CS0315: The type 'NonComparable' cannot be used as type parameter 'T' in the generic type or method 'Span<T>'. There is no boxing conversion from 'NonComparable' to 'System.IComparable'. // Span<NonComparable> explicitError = default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "NonComparable").WithArguments("System.Span<T>", "System.IComparable", "T", "NonComparable").WithLocation(19, 14), // (20,67): error CS0315: The type 'NonComparable' cannot be used as type parameter 'T' in the generic type or method 'Span<T>'. There is no boxing conversion from 'NonComparable' to 'System.IComparable'. // var implicitError = explicitError.Length > 0 ? stackalloc NonComparable[10] : stackalloc NonComparable[100]; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "NonComparable[10]").WithArguments("System.Span<T>", "System.IComparable", "T", "NonComparable").WithLocation(20, 67), // (20,98): error CS0315: The type 'NonComparable' cannot be used as type parameter 'T' in the generic type or method 'Span<T>'. There is no boxing conversion from 'NonComparable' to 'System.IComparable'. // var implicitError = explicitError.Length > 0 ? stackalloc NonComparable[10] : stackalloc NonComparable[100]; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "NonComparable[100]").WithArguments("System.Span<T>", "System.IComparable", "T", "NonComparable").WithLocation(20, 98)); } [Fact] [WorkItem(26195, "https://github.com/dotnet/roslyn/issues/26195")] public void StackAllocImplicitConversion_TwpStep_ToPointer() { var code = @" class Test2 { } unsafe class Test { public void Method() { Test obj1 = stackalloc int[2]; } public static implicit operator Test2(int* value) => default; }"; CreateCompilationWithMscorlibAndSpan(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,34): error CS0556: User-defined conversion must convert to or from the enclosing type // public static implicit operator Test2(int* value) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "Test2").WithLocation(11, 34), // (9,15): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'Test' is not possible. // Test obj1 = stackalloc int[2]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[2]").WithArguments("int", "Test").WithLocation(9, 15)); } [Fact] [WorkItem(26195, "https://github.com/dotnet/roslyn/issues/26195")] public void StackAllocImplicitConversion_TwpStep_ToSpan() { var code = @" class Test2 { } unsafe class Test { public void Method() { Test obj1 = stackalloc int[2]; } public static implicit operator Test2(System.Span<int> value) => default; }"; CreateCompilationWithMscorlibAndSpan(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,34): error CS0556: User-defined conversion must convert to or from the enclosing type // public static implicit operator Test2(System.Span<int> value) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "Test2").WithLocation(11, 34), // (9,15): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'Test' is not possible. // Test obj1 = stackalloc int[2]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[2]").WithArguments("int", "Test").WithLocation(9, 15)); } } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class StackAllocSpanExpressionsTests : CompilingTestBase { [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Implicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method() { Test obj1 = stackalloc int[10]; var obj2 = stackalloc int[10]; Span<int> obj3 = stackalloc int[10]; int* obj4 = stackalloc int[10]; double* obj5 = stackalloc int[10]; } public static implicit operator Test(int* value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[10]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[10]").WithArguments("int", "double*").WithLocation(11, 24)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(5, variables.Count()); var obj1 = variables.ElementAt(0); Assert.Equal("obj1", obj1.Identifier.Text); var obj1Value = model.GetSemanticInfoSummary(obj1.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj1Value.Type).PointedAtType.SpecialType); Assert.Equal("Test", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.ImplicitUserDefined, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Explicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method() { Test obj1 = (Test)stackalloc int[10]; var obj2 = stackalloc int[10]; Span<int> obj3 = stackalloc int[10]; int* obj4 = stackalloc int[10]; double* obj5 = stackalloc int[10]; } public static explicit operator Test(Span<int> value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[10]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[10]").WithArguments("int", "double*").WithLocation(11, 24)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(5, variables.Count()); var obj1 = variables.ElementAt(0); Assert.Equal("obj1", obj1.Identifier.Text); Assert.Equal(SyntaxKind.CastExpression, obj1.Initializer.Value.Kind()); var obj1Value = model.GetSemanticInfoSummary(((CastExpressionSyntax)obj1.Initializer.Value).Expression); Assert.Equal("Span", obj1Value.Type.Name); Assert.Equal("Span", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } [Fact] public void ConversionError() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { double x = stackalloc int[10]; // implicit short y = (short)stackalloc int[10]; // explicit } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[10]; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[10]").WithArguments("int", "double").WithLocation(6, 20), // (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[10]; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[10]").WithArguments("int", "short").WithLocation(7, 19)); } [Fact] public void MissingSpanType() { CreateCompilation(@" class Test { void M() { Span<int> a = stackalloc int [10]; } }").VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a = stackalloc int [10]; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(6, 9), // (6,23): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a = stackalloc int [10]; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [10]").WithArguments("System.Span`1").WithLocation(6, 23)); } [Fact] public void MissingSpanConstructor() { CreateCompilation(@" namespace System { ref struct Span<T> { } class Test { void M() { Span<int> a = stackalloc int [10]; } } }").VerifyEmitDiagnostics( // (11,27): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a = stackalloc int [10]; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [10]").WithArguments("System.Span`1", ".ctor").WithLocation(11, 27)); } [Fact] public void ConditionalExpressionOnSpan_BothStackallocSpans() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { var x = true ? stackalloc int [10] : stackalloc int [5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_Convertible() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x = true ? stackalloc int [10] : (Span<int>)stackalloc int [5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_NoCast() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x = true ? stackalloc int [10] : (Span<int>)stackalloc short [5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,46): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x = true ? stackalloc int [10] : (Span<int>)stackalloc short [5]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [5]").WithArguments("short", "System.Span<int>").WithLocation(7, 46)); } [Fact] public void ConditionalExpressionOnSpan_CompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> a = stackalloc int [10]; var x = true ? stackalloc int [10] : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_IncompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<short> a = stackalloc short [10]; var x = true ? stackalloc int [10] : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,17): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x = true ? stackalloc int [10] : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [10] : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(8, 17) ); } [Fact] public void ConditionalExpressionOnSpan_Nested() { CreateCompilationWithMscorlibAndSpan(@" class Test { bool N() => true; void M() { var x = N() ? N() ? stackalloc int [1] : stackalloc int [2] : N() ? stackalloc int[3] : N() ? stackalloc int[4] : stackalloc int[5]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void BooleanOperatorOnSpan_NoTargetTyping() { var source = @" class Test { void M() { if(stackalloc int[10] == stackalloc int[10]) { } } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,12): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // if(stackalloc int[10] == stackalloc int[10]) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 12), // (6,34): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // if(stackalloc int[10] == stackalloc int[10]) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 34) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,12): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if(stackalloc int[10] == stackalloc int[10]) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[10] == stackalloc int[10]").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(6, 12) ); } [Fact] public void NewStackAllocSpanSyntaxProducesErrorsOnEarlierVersions_Statements() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> x = stackalloc int[10]; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,23): error CS8107: Feature 'ref structs' is not available in C# 7. Please use language version 7.2 or greater. // Span<int> x = stackalloc int[10]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc int[10]").WithArguments("ref structs", "7.2").WithLocation(7, 23)); } [Fact] public void NewStackAllocSpanSyntaxProducesErrorsOnEarlierVersions_Expressions() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" class Test { void M(bool condition) { var x = condition ? stackalloc int[10] : stackalloc int[100]; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,15): error CS8107: Feature 'ref structs' is not available in C# 7.0. Please use language version 7.2 or greater. // ? stackalloc int[10] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc int[10]").WithArguments("ref structs", "7.2").WithLocation(7, 15), // (8,15): error CS8107: Feature 'ref structs' is not available in C# 7.0. Please use language version 7.2 or greater. // : stackalloc int[100]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc int[100]").WithArguments("ref structs", "7.2").WithLocation(8, 15)); } [Fact] public void StackAllocSyntaxProducesUnsafeErrorInSafeCode() { CreateCompilation(@" class Test { void M() { var x = stackalloc int[10]; } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x = stackalloc int[10]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[10]").WithLocation(6, 17)); } [Fact] public void StackAllocInUsing1() { var test = @" public class Test { unsafe public static void Main() { using (var v = stackalloc int[1]) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v = stackalloc int[1]) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v = stackalloc int[1]").WithArguments("System.Span<int>").WithLocation(6, 16) ); } [Fact] public void StackAllocInUsing2() { var test = @" public class Test { unsafe public static void Main() { using (System.IDisposable v = stackalloc int[1]) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,39): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v = stackalloc int[1]) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[1]").WithArguments("int", "System.IDisposable").WithLocation(6, 39)); } [Fact] public void ConstStackAllocExpression() { var test = @" unsafe public class Test { void M() { const int* p = stackalloc int[1]; } } "; CreateCompilation(test, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0283: The type 'int*' cannot be declared const // const int* p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(6, 15)); } [Fact] public void RefStackAllocAssignment_ValueToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p = stackalloc int[1]; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p = stackalloc int[1]").WithLocation(7, 23), // (7,27): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int[1]").WithLocation(7, 27)); } [Fact] public void RefStackAllocAssignment_RefToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p = ref stackalloc int[1]; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,31): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // ref Span<int> p = ref stackalloc int[1]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 31) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,31): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p = ref stackalloc int[1]; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int[1]").WithLocation(7, 31) ); } [Fact] public void InvalidPositionForStackAllocSpan() { var test = @" using System; public class Test { void M() { N(stackalloc int[1]); } void N(Span<int> span) { } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int[1]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 11) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void CannotDotIntoStackAllocExpression() { var test = @" public class Test { void M() { int length = (stackalloc int [10]).Length; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length = (stackalloc int [10]).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 23) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void OverloadResolution_Fail() { var test = @" using System; unsafe public class Test { static void Main() { Invoke(stackalloc int [10]); } static void Invoke(Span<short> shortSpan) => Console.WriteLine(""shortSpan""); static void Invoke(Span<bool> boolSpan) => Console.WriteLine(""boolSpan""); static void Invoke(int* intPointer) => Console.WriteLine(""intPointer""); static void Invoke(void* voidPointer) => Console.WriteLine(""voidPointer""); } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [10]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 16) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (7,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [10]); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [10]").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(7, 16) ); } [Fact] public void StackAllocWithDynamic() { CreateCompilation(@" class Program { static void Main() { var d = stackalloc dynamic[10]; } }").VerifyDiagnostics( // (6,33): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d = stackalloc dynamic[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(6, 28)); } [Fact] public void StackAllocWithDynamicSpan() { CreateCompilationWithMscorlibAndSpan(@" using System; class Program { static void Main() { Span<dynamic> d = stackalloc dynamic[10]; } }").VerifyDiagnostics( // (7,38): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d = stackalloc dynamic[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(7, 38)); } [Fact] public void StackAllocAsArgument() { var source = @" class Program { static void N(object p) { } static void Main() { N(stackalloc int[10]); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int[10]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11) ); CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int[10]); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int[10]").WithArguments("1", "System.Span<int>", "object").WithLocation(8, 11) ); } [Fact] public void StackAllocInParenthesis() { var source = @" class Program { static void Main() { var x = (stackalloc int[10]); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x = (stackalloc int[10]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 18) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( ); } [Fact] public void StackAllocInNullConditionalOperator() { var source = @" class Program { static void Main() { var x = stackalloc int[1] ?? stackalloc int[2]; } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,17): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x = stackalloc int[1] ?? stackalloc int[2]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 17), // (6,38): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x = stackalloc int[1] ?? stackalloc int[2]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 38) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (6,17): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x = stackalloc int[1] ?? stackalloc int[2]; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[1] ?? stackalloc int[2]").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(6, 17) ); } [Fact] public void StackAllocInCastAndConditionalOperator() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public void Method() { Test value = true ? new Test() : (Test)stackalloc int[10]; } public static explicit operator Test(Span<int> value) { return new Test(); } }", TestOptions.ReleaseDll).VerifyDiagnostics(); } [Fact] [WorkItem(25038, "https://github.com/dotnet/roslyn/issues/25038")] public void StackAllocToSpanWithRefStructType() { CreateCompilationWithMscorlibAndSpan(@" using System; ref struct S {} class Test { void M() { Span<S> explicitError = default; var implicitError = explicitError.Length > 0 ? stackalloc S[10] : stackalloc S[100]; } }").VerifyDiagnostics( // (8,14): error CS0306: The type 'S' may not be used as a type argument // Span<S> explicitError = default; Diagnostic(ErrorCode.ERR_BadTypeArgument, "S").WithArguments("S").WithLocation(8, 14), // (9,67): error CS0306: The type 'S' may not be used as a type argument // var implicitError = explicitError.Length > 0 ? stackalloc S[10] : stackalloc S[100]; Diagnostic(ErrorCode.ERR_BadTypeArgument, "S[10]").WithArguments("S").WithLocation(9, 67), // (9,86): error CS0306: The type 'S' may not be used as a type argument // var implicitError = explicitError.Length > 0 ? stackalloc S[10] : stackalloc S[100]; Diagnostic(ErrorCode.ERR_BadTypeArgument, "S[100]").WithArguments("S").WithLocation(9, 86) ); } [Fact] [WorkItem(25086, "https://github.com/dotnet/roslyn/issues/25086")] public void StaackAllocToSpanWithCustomSpanAndConstraints() { var code = @" using System; namespace System { public unsafe readonly ref struct Span<T> where T : IComparable { public Span(void* ptr, int length) { Length = length; } public int Length { get; } } } struct NonComparable { } class Test { void M() { Span<NonComparable> explicitError = default; var implicitError = explicitError.Length > 0 ? stackalloc NonComparable[10] : stackalloc NonComparable[100]; } }"; var references = new List<MetadataReference>() { MscorlibRef_v4_0_30316_17626, SystemCoreRef, CSharpRef }; CreateEmptyCompilation(code, references, TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (19,14): error CS0315: The type 'NonComparable' cannot be used as type parameter 'T' in the generic type or method 'Span<T>'. There is no boxing conversion from 'NonComparable' to 'System.IComparable'. // Span<NonComparable> explicitError = default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "NonComparable").WithArguments("System.Span<T>", "System.IComparable", "T", "NonComparable").WithLocation(19, 14), // (20,67): error CS0315: The type 'NonComparable' cannot be used as type parameter 'T' in the generic type or method 'Span<T>'. There is no boxing conversion from 'NonComparable' to 'System.IComparable'. // var implicitError = explicitError.Length > 0 ? stackalloc NonComparable[10] : stackalloc NonComparable[100]; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "NonComparable[10]").WithArguments("System.Span<T>", "System.IComparable", "T", "NonComparable").WithLocation(20, 67), // (20,98): error CS0315: The type 'NonComparable' cannot be used as type parameter 'T' in the generic type or method 'Span<T>'. There is no boxing conversion from 'NonComparable' to 'System.IComparable'. // var implicitError = explicitError.Length > 0 ? stackalloc NonComparable[10] : stackalloc NonComparable[100]; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "NonComparable[100]").WithArguments("System.Span<T>", "System.IComparable", "T", "NonComparable").WithLocation(20, 98)); } [Fact] [WorkItem(26195, "https://github.com/dotnet/roslyn/issues/26195")] public void StackAllocImplicitConversion_TwpStep_ToPointer() { var code = @" class Test2 { } unsafe class Test { public void Method() { Test obj1 = stackalloc int[2]; } public static implicit operator Test2(int* value) => default; }"; CreateCompilationWithMscorlibAndSpan(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,34): error CS0556: User-defined conversion must convert to or from the enclosing type // public static implicit operator Test2(int* value) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "Test2").WithLocation(11, 34), // (9,15): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'Test' is not possible. // Test obj1 = stackalloc int[2]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[2]").WithArguments("int", "Test").WithLocation(9, 15)); } [Fact] [WorkItem(26195, "https://github.com/dotnet/roslyn/issues/26195")] public void StackAllocImplicitConversion_TwpStep_ToSpan() { var code = @" class Test2 { } unsafe class Test { public void Method() { Test obj1 = stackalloc int[2]; } public static implicit operator Test2(System.Span<int> value) => default; }"; CreateCompilationWithMscorlibAndSpan(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,34): error CS0556: User-defined conversion must convert to or from the enclosing type // public static implicit operator Test2(System.Span<int> value) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "Test2").WithLocation(11, 34), // (9,15): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'Test' is not possible. // Test obj1 = stackalloc int[2]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[2]").WithArguments("int", "Test").WithLocation(9, 15)); } } }
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/Remote/ServiceHub/Services/Host/RemoteHostTestData.cs
// 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 System; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Test hook used to pass test data to remote services. /// </summary> internal sealed class RemoteHostTestData { public readonly RemoteWorkspaceManager WorkspaceManager; public readonly bool IsInProc; public RemoteHostTestData(RemoteWorkspaceManager workspaceManager, bool isInProc) { WorkspaceManager = workspaceManager; IsInProc = isInProc; } } }
// 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 System; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Test hook used to pass test data to remote services. /// </summary> internal sealed class RemoteHostTestData { public readonly RemoteWorkspaceManager WorkspaceManager; public readonly bool IsInProc; public RemoteHostTestData(RemoteWorkspaceManager workspaceManager, bool isInProc) { WorkspaceManager = workspaceManager; IsInProc = isInProc; } } }
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/Test2/Peek/PeekTests.vb
' 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. Imports System.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.Implementation.Peek Imports Microsoft.CodeAnalysis.Editor.Peek Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.VisualStudio.Imaging.Interop Imports Microsoft.VisualStudio.Language.Intellisense Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Utilities Imports Moq Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Peek <[UseExportProvider]> Public Class PeekTests <WpfFact, WorkItem(820706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820706"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestInvokeInEmptyFile() Dim result = GetPeekResultCollection(<Workspace> <Project Language="C#" CommonReferences="true"> <Document>$$}</Document> </Project> </Workspace>) Assert.Null(result) End Sub <WpfFact, WorkItem(827025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827025"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestWorksAcrossLanguages() Using workspace = CreateTestWorkspace(<Workspace> <Project Language="C#" AssemblyName="Reference" CommonReferences="true"> <Document>public class {|Identifier:TestClass|} { }</Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>Reference</ProjectReference> <Document> Public Class Blah : Inherits $$TestClass : End Class </Document> </Project> </Workspace>) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) result.AssertNavigatesToIdentifier(index:=0, name:="Identifier") End Using End Sub <WpfFact, WorkItem(824336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824336"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestPeekDefinitionWhenInvokedOnLiteral() Using workspace = CreateTestWorkspace(<Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { string s = $$"Goo"; }</Document> </Project> </Workspace>) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) Assert.Equal($"String [{FeaturesResources.from_metadata}]", result(0).DisplayInfo.Label) Assert.Equal($"String [{FeaturesResources.from_metadata}]", result(0).DisplayInfo.Title) Assert.True(result.GetRemainingIdentifierLineTextOnDisk(index:=0).StartsWith("String", StringComparison.Ordinal)) End Using End Sub <WpfFact, WorkItem(824331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824331"), WorkItem(820289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820289"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestPeekDefinitionWhenExtensionMethodFromMetadata() Using workspace = CreateTestWorkspace(<Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class C { void M() { int[] a; a.$$Distinct(); }</Document> </Project> </Workspace>) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) Assert.Equal($"Enumerable [{FeaturesResources.from_metadata}]", result(0).DisplayInfo.Label) Assert.Equal($"Enumerable [{FeaturesResources.from_metadata}]", result(0).DisplayInfo.Title) Assert.True(result.GetRemainingIdentifierLineTextOnDisk(index:=0).StartsWith("Distinct", StringComparison.Ordinal)) End Using End Sub <WpfFact, WorkItem(819660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819660"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestPeekDefinitionFromVisualBasicMetadataAsSource() Using workspace = CreateTestWorkspace(<Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[<System.$$Serializable()> Class AA End Class </Document> ]]></Document> </Project> </Workspace>) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) Assert.Equal($"SerializableAttribute [{FeaturesResources.from_metadata}]", result(0).DisplayInfo.Label) Assert.Equal($"SerializableAttribute [{FeaturesResources.from_metadata}]", result(0).DisplayInfo.Title) Assert.True(result.GetRemainingIdentifierLineTextOnDisk(index:=0).StartsWith("New()", StringComparison.Ordinal)) ' Navigates to constructor End Using End Sub <WpfFact, WorkItem(819602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819602"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestPeekDefinitionOnParamNameXmlDocComment() Using workspace = CreateTestWorkspace(<Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class C ''' <param name="$$exePath"></param> Public Sub ddd(ByVal {|Identifier:exePath|} As String) End Sub End Class ]]></Document> </Project> </Workspace>) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) result.AssertNavigatesToIdentifier(0, "Identifier") End Using End Sub <WpfFact, WorkItem(820363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820363"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestPeekDefinitionOnLinqVariable() Using workspace = CreateTestWorkspace(<Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Module M Sub S() Dim arr = {3, 4, 5} Dim q = From i In arr Select {|Identifier:$$d|} = i.GetType End Sub End Module ]]></Document> </Project> </Workspace>) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) result.AssertNavigatesToIdentifier(0, "Identifier") End Using End Sub <WpfFact> <WorkItem(1091211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091211")> Public Sub TestPeekAcrossProjectsInvolvingPortableReferences() Dim workspaceDefinition = <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferencesPortable="true"> <Document> namespace N { public class CSClass { public void {|Identifier:M|}(int i) { } } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document> Imports N Public Class VBClass Sub Test() Dim x As New CSClass() x.M$$(5) End Sub End Class </Document> </Project> </Workspace> Using workspace = CreateTestWorkspace(workspaceDefinition) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) result.AssertNavigatesToIdentifier(0, "Identifier") End Using End Sub Private Shared Function CreateTestWorkspace(element As XElement) As TestWorkspace Return TestWorkspace.Create(element, composition:=EditorTestCompositions.EditorFeaturesWpf) End Function Private Shared Function GetPeekResultCollection(element As XElement) As PeekResultCollection Using workspace = CreateTestWorkspace(element) Return GetPeekResultCollection(workspace) End Using End Function Private Shared Function GetPeekResultCollection(workspace As TestWorkspace) As PeekResultCollection Dim document = workspace.Documents.FirstOrDefault(Function(d) d.CursorPosition.HasValue) If document Is Nothing Then AssertEx.Fail("The test is missing a $$ in the workspace.") End If Dim textBuffer = document.GetTextBuffer() Dim textView = document.GetTextView() Dim peekableItemSource As New PeekableItemSource(textBuffer, workspace.GetService(Of IPeekableItemFactory), New MockPeekResultFactory(workspace.GetService(Of IPersistentSpanFactory)), workspace.GetService(Of IUIThreadOperationExecutor)) Dim peekableSession As New Mock(Of IPeekSession)(MockBehavior.Strict) Dim triggerPoint = New SnapshotPoint(document.GetTextBuffer().CurrentSnapshot, document.CursorPosition.Value) peekableSession.Setup(Function(s) s.GetTriggerPoint(It.IsAny(Of ITextSnapshot))).Returns(triggerPoint) peekableSession.SetupGet(Function(s) s.RelationshipName).Returns("IsDefinedBy") Dim items As New List(Of IPeekableItem) peekableItemSource.AugmentPeekSession(peekableSession.Object, items) If Not items.Any Then Return Nothing End If Dim peekResult As New PeekResultCollection(workspace) Dim item = items.SingleOrDefault() If item IsNot Nothing Then Dim callbackMock = New Mock(Of IFindPeekResultsCallback)(MockBehavior.Strict) callbackMock.Setup(Sub(s) s.ReportProgress(It.IsAny(Of Integer))) Dim resultSource = item.GetOrCreateResultSource(PredefinedPeekRelationships.Definitions.Name) resultSource.FindResults(PredefinedPeekRelationships.Definitions.Name, peekResult, CancellationToken.None, callbackMock.Object) End If Return peekResult End Function Private Class MockPeekResultFactory Implements IPeekResultFactory Private ReadOnly _persistentSpanFactory As IPersistentSpanFactory Public Sub New(persistentSpanFactory As IPersistentSpanFactory) _persistentSpanFactory = persistentSpanFactory End Sub Public Function Create(displayInfo As IPeekResultDisplayInfo, browseAction As Action) As IExternallyBrowsablePeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function Public Function Create(displayInfo As IPeekResultDisplayInfo, filePath As String, eoiSpan As Span, idPosition As Integer, isReadOnly As Boolean) As IDocumentPeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function Public Function Create(displayInfo As IPeekResultDisplayInfo, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idLine As Integer, idIndex As Integer) As IDocumentPeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function Public Function Create(displayInfo As IPeekResultDisplayInfo, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idLine As Integer, idIndex As Integer, isReadOnly As Boolean) As IDocumentPeekResult Implements IPeekResultFactory.Create Dim documentResult As New Mock(Of IDocumentPeekResult)(MockBehavior.Strict) documentResult.SetupGet(Function(d) d.DisplayInfo).Returns(displayInfo) documentResult.SetupGet(Function(d) d.FilePath).Returns(filePath) documentResult.SetupGet(Function(d) d.IdentifyingSpan).Returns(_persistentSpanFactory.Create(filePath, idLine, idIndex, idLine, idIndex, SpanTrackingMode.EdgeInclusive)) documentResult.SetupGet(Function(d) d.Span).Returns(_persistentSpanFactory.Create(filePath, idLine, idIndex, idLine, idIndex, SpanTrackingMode.EdgeInclusive)) documentResult.SetupGet(Function(d) d.IsReadOnly).Returns(isReadOnly) Return documentResult.Object End Function Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer) As IDocumentPeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer, isReadOnly As Boolean) As IDocumentPeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer, isReadOnly As Boolean, editorDestination As Guid) As IDocumentPeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer, isReadOnly As Boolean, editorDestination As Guid, postNavigationCallback As Action(Of IPeekResult, Object, Object)) As IDocumentPeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function End Class Private Class PeekResultCollection Implements IPeekResultCollection Public ReadOnly Items As New List(Of IPeekResult) Private ReadOnly _workspace As TestWorkspace Public Sub New(workspace As TestWorkspace) _workspace = workspace End Sub Private ReadOnly Property Count As Integer Implements IPeekResultCollection.Count Get Return Items.Count End Get End Property Default Public Property Item(index As Integer) As IPeekResult Implements IPeekResultCollection.Item Get Return Items(index) End Get Set(value As IPeekResult) Throw New NotImplementedException() End Set End Property Private Sub Add(peekResult As IPeekResult) Implements IPeekResultCollection.Add Items.Add(peekResult) End Sub Private Sub Clear() Implements IPeekResultCollection.Clear Throw New NotImplementedException() End Sub Private Sub Insert(index As Integer, peekResult As IPeekResult) Implements IPeekResultCollection.Insert Throw New NotImplementedException() End Sub Private Sub Move(oldIndex As Integer, newIndex As Integer) Implements IPeekResultCollection.Move Throw New NotImplementedException() End Sub Private Sub RemoveAt(index As Integer) Implements IPeekResultCollection.RemoveAt Throw New NotImplementedException() End Sub Private Function Contains(peekResult As IPeekResult) As Boolean Implements IPeekResultCollection.Contains Throw New NotImplementedException() End Function Private Function IndexOf(peekResult As IPeekResult, startAt As Integer) As Integer Implements IPeekResultCollection.IndexOf Throw New NotImplementedException() End Function Private Function Remove(item As IPeekResult) As Boolean Implements IPeekResultCollection.Remove Throw New NotImplementedException() End Function ''' <summary> ''' Returns the text of the identifier line, starting at the identifier and ending at end of the line. ''' </summary> ''' <param name="index"></param> ''' <returns></returns> Friend Function GetRemainingIdentifierLineTextOnDisk(index As Integer) As String Dim documentResult = DirectCast(Items(index), IDocumentPeekResult) Dim textBufferService = _workspace.GetService(Of ITextBufferFactoryService) Dim buffer = textBufferService.CreateTextBuffer(New StreamReader(documentResult.FilePath), textBufferService.InertContentType) Dim startLine As Integer Dim startIndex As Integer Assert.True(documentResult.IdentifyingSpan.TryGetStartLineIndex(startLine, startIndex), "Unable to get span for metadata file.") Dim line = buffer.CurrentSnapshot.GetLineFromLineNumber(startLine) Return buffer.CurrentSnapshot.GetText(line.Start + startIndex, line.Length - startIndex) End Function Friend Sub AssertNavigatesToIdentifier(index As Integer, name As String) Dim documentResult = DirectCast(Items(index), IDocumentPeekResult) Dim document = _workspace.Documents.FirstOrDefault(Function(d) d.FilePath = documentResult.FilePath) AssertEx.NotNull(document, "Peek didn't navigate to a document in source. Navigated to " + documentResult.FilePath + " instead.") Dim startLine As Integer Dim startIndex As Integer Assert.True(documentResult.IdentifyingSpan.TryGetStartLineIndex(startLine, startIndex), "Unable to get span for source file.") Dim snapshot = document.GetTextBuffer().CurrentSnapshot Dim expectedPosition = New SnapshotPoint(snapshot, document.AnnotatedSpans(name).Single().Start) Dim actualPosition = snapshot.GetLineFromLineNumber(startLine).Start + startIndex Assert.Equal(expectedPosition, actualPosition) End Sub End Class End Class End Namespace
' 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. Imports System.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.Implementation.Peek Imports Microsoft.CodeAnalysis.Editor.Peek Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.VisualStudio.Imaging.Interop Imports Microsoft.VisualStudio.Language.Intellisense Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Utilities Imports Moq Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Peek <[UseExportProvider]> Public Class PeekTests <WpfFact, WorkItem(820706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820706"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestInvokeInEmptyFile() Dim result = GetPeekResultCollection(<Workspace> <Project Language="C#" CommonReferences="true"> <Document>$$}</Document> </Project> </Workspace>) Assert.Null(result) End Sub <WpfFact, WorkItem(827025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827025"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestWorksAcrossLanguages() Using workspace = CreateTestWorkspace(<Workspace> <Project Language="C#" AssemblyName="Reference" CommonReferences="true"> <Document>public class {|Identifier:TestClass|} { }</Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>Reference</ProjectReference> <Document> Public Class Blah : Inherits $$TestClass : End Class </Document> </Project> </Workspace>) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) result.AssertNavigatesToIdentifier(index:=0, name:="Identifier") End Using End Sub <WpfFact, WorkItem(824336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824336"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestPeekDefinitionWhenInvokedOnLiteral() Using workspace = CreateTestWorkspace(<Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { string s = $$"Goo"; }</Document> </Project> </Workspace>) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) Assert.Equal($"String [{FeaturesResources.from_metadata}]", result(0).DisplayInfo.Label) Assert.Equal($"String [{FeaturesResources.from_metadata}]", result(0).DisplayInfo.Title) Assert.True(result.GetRemainingIdentifierLineTextOnDisk(index:=0).StartsWith("String", StringComparison.Ordinal)) End Using End Sub <WpfFact, WorkItem(824331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824331"), WorkItem(820289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820289"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestPeekDefinitionWhenExtensionMethodFromMetadata() Using workspace = CreateTestWorkspace(<Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class C { void M() { int[] a; a.$$Distinct(); }</Document> </Project> </Workspace>) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) Assert.Equal($"Enumerable [{FeaturesResources.from_metadata}]", result(0).DisplayInfo.Label) Assert.Equal($"Enumerable [{FeaturesResources.from_metadata}]", result(0).DisplayInfo.Title) Assert.True(result.GetRemainingIdentifierLineTextOnDisk(index:=0).StartsWith("Distinct", StringComparison.Ordinal)) End Using End Sub <WpfFact, WorkItem(819660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819660"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestPeekDefinitionFromVisualBasicMetadataAsSource() Using workspace = CreateTestWorkspace(<Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[<System.$$Serializable()> Class AA End Class </Document> ]]></Document> </Project> </Workspace>) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) Assert.Equal($"SerializableAttribute [{FeaturesResources.from_metadata}]", result(0).DisplayInfo.Label) Assert.Equal($"SerializableAttribute [{FeaturesResources.from_metadata}]", result(0).DisplayInfo.Title) Assert.True(result.GetRemainingIdentifierLineTextOnDisk(index:=0).StartsWith("New()", StringComparison.Ordinal)) ' Navigates to constructor End Using End Sub <WpfFact, WorkItem(819602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819602"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestPeekDefinitionOnParamNameXmlDocComment() Using workspace = CreateTestWorkspace(<Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class C ''' <param name="$$exePath"></param> Public Sub ddd(ByVal {|Identifier:exePath|} As String) End Sub End Class ]]></Document> </Project> </Workspace>) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) result.AssertNavigatesToIdentifier(0, "Identifier") End Using End Sub <WpfFact, WorkItem(820363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820363"), Trait(Traits.Feature, Traits.Features.Peek)> Public Sub TestPeekDefinitionOnLinqVariable() Using workspace = CreateTestWorkspace(<Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Module M Sub S() Dim arr = {3, 4, 5} Dim q = From i In arr Select {|Identifier:$$d|} = i.GetType End Sub End Module ]]></Document> </Project> </Workspace>) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) result.AssertNavigatesToIdentifier(0, "Identifier") End Using End Sub <WpfFact> <WorkItem(1091211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091211")> Public Sub TestPeekAcrossProjectsInvolvingPortableReferences() Dim workspaceDefinition = <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferencesPortable="true"> <Document> namespace N { public class CSClass { public void {|Identifier:M|}(int i) { } } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document> Imports N Public Class VBClass Sub Test() Dim x As New CSClass() x.M$$(5) End Sub End Class </Document> </Project> </Workspace> Using workspace = CreateTestWorkspace(workspaceDefinition) Dim result = GetPeekResultCollection(workspace) Assert.Equal(1, result.Items.Count) result.AssertNavigatesToIdentifier(0, "Identifier") End Using End Sub Private Shared Function CreateTestWorkspace(element As XElement) As TestWorkspace Return TestWorkspace.Create(element, composition:=EditorTestCompositions.EditorFeaturesWpf) End Function Private Shared Function GetPeekResultCollection(element As XElement) As PeekResultCollection Using workspace = CreateTestWorkspace(element) Return GetPeekResultCollection(workspace) End Using End Function Private Shared Function GetPeekResultCollection(workspace As TestWorkspace) As PeekResultCollection Dim document = workspace.Documents.FirstOrDefault(Function(d) d.CursorPosition.HasValue) If document Is Nothing Then AssertEx.Fail("The test is missing a $$ in the workspace.") End If Dim textBuffer = document.GetTextBuffer() Dim textView = document.GetTextView() Dim peekableItemSource As New PeekableItemSource(textBuffer, workspace.GetService(Of IPeekableItemFactory), New MockPeekResultFactory(workspace.GetService(Of IPersistentSpanFactory)), workspace.GetService(Of IUIThreadOperationExecutor)) Dim peekableSession As New Mock(Of IPeekSession)(MockBehavior.Strict) Dim triggerPoint = New SnapshotPoint(document.GetTextBuffer().CurrentSnapshot, document.CursorPosition.Value) peekableSession.Setup(Function(s) s.GetTriggerPoint(It.IsAny(Of ITextSnapshot))).Returns(triggerPoint) peekableSession.SetupGet(Function(s) s.RelationshipName).Returns("IsDefinedBy") Dim items As New List(Of IPeekableItem) peekableItemSource.AugmentPeekSession(peekableSession.Object, items) If Not items.Any Then Return Nothing End If Dim peekResult As New PeekResultCollection(workspace) Dim item = items.SingleOrDefault() If item IsNot Nothing Then Dim callbackMock = New Mock(Of IFindPeekResultsCallback)(MockBehavior.Strict) callbackMock.Setup(Sub(s) s.ReportProgress(It.IsAny(Of Integer))) Dim resultSource = item.GetOrCreateResultSource(PredefinedPeekRelationships.Definitions.Name) resultSource.FindResults(PredefinedPeekRelationships.Definitions.Name, peekResult, CancellationToken.None, callbackMock.Object) End If Return peekResult End Function Private Class MockPeekResultFactory Implements IPeekResultFactory Private ReadOnly _persistentSpanFactory As IPersistentSpanFactory Public Sub New(persistentSpanFactory As IPersistentSpanFactory) _persistentSpanFactory = persistentSpanFactory End Sub Public Function Create(displayInfo As IPeekResultDisplayInfo, browseAction As Action) As IExternallyBrowsablePeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function Public Function Create(displayInfo As IPeekResultDisplayInfo, filePath As String, eoiSpan As Span, idPosition As Integer, isReadOnly As Boolean) As IDocumentPeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function Public Function Create(displayInfo As IPeekResultDisplayInfo, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idLine As Integer, idIndex As Integer) As IDocumentPeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function Public Function Create(displayInfo As IPeekResultDisplayInfo, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idLine As Integer, idIndex As Integer, isReadOnly As Boolean) As IDocumentPeekResult Implements IPeekResultFactory.Create Dim documentResult As New Mock(Of IDocumentPeekResult)(MockBehavior.Strict) documentResult.SetupGet(Function(d) d.DisplayInfo).Returns(displayInfo) documentResult.SetupGet(Function(d) d.FilePath).Returns(filePath) documentResult.SetupGet(Function(d) d.IdentifyingSpan).Returns(_persistentSpanFactory.Create(filePath, idLine, idIndex, idLine, idIndex, SpanTrackingMode.EdgeInclusive)) documentResult.SetupGet(Function(d) d.Span).Returns(_persistentSpanFactory.Create(filePath, idLine, idIndex, idLine, idIndex, SpanTrackingMode.EdgeInclusive)) documentResult.SetupGet(Function(d) d.IsReadOnly).Returns(isReadOnly) Return documentResult.Object End Function Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer) As IDocumentPeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer, isReadOnly As Boolean) As IDocumentPeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer, isReadOnly As Boolean, editorDestination As Guid) As IDocumentPeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer, isReadOnly As Boolean, editorDestination As Guid, postNavigationCallback As Action(Of IPeekResult, Object, Object)) As IDocumentPeekResult Implements IPeekResultFactory.Create Throw New NotImplementedException() End Function End Class Private Class PeekResultCollection Implements IPeekResultCollection Public ReadOnly Items As New List(Of IPeekResult) Private ReadOnly _workspace As TestWorkspace Public Sub New(workspace As TestWorkspace) _workspace = workspace End Sub Private ReadOnly Property Count As Integer Implements IPeekResultCollection.Count Get Return Items.Count End Get End Property Default Public Property Item(index As Integer) As IPeekResult Implements IPeekResultCollection.Item Get Return Items(index) End Get Set(value As IPeekResult) Throw New NotImplementedException() End Set End Property Private Sub Add(peekResult As IPeekResult) Implements IPeekResultCollection.Add Items.Add(peekResult) End Sub Private Sub Clear() Implements IPeekResultCollection.Clear Throw New NotImplementedException() End Sub Private Sub Insert(index As Integer, peekResult As IPeekResult) Implements IPeekResultCollection.Insert Throw New NotImplementedException() End Sub Private Sub Move(oldIndex As Integer, newIndex As Integer) Implements IPeekResultCollection.Move Throw New NotImplementedException() End Sub Private Sub RemoveAt(index As Integer) Implements IPeekResultCollection.RemoveAt Throw New NotImplementedException() End Sub Private Function Contains(peekResult As IPeekResult) As Boolean Implements IPeekResultCollection.Contains Throw New NotImplementedException() End Function Private Function IndexOf(peekResult As IPeekResult, startAt As Integer) As Integer Implements IPeekResultCollection.IndexOf Throw New NotImplementedException() End Function Private Function Remove(item As IPeekResult) As Boolean Implements IPeekResultCollection.Remove Throw New NotImplementedException() End Function ''' <summary> ''' Returns the text of the identifier line, starting at the identifier and ending at end of the line. ''' </summary> ''' <param name="index"></param> ''' <returns></returns> Friend Function GetRemainingIdentifierLineTextOnDisk(index As Integer) As String Dim documentResult = DirectCast(Items(index), IDocumentPeekResult) Dim textBufferService = _workspace.GetService(Of ITextBufferFactoryService) Dim buffer = textBufferService.CreateTextBuffer(New StreamReader(documentResult.FilePath), textBufferService.InertContentType) Dim startLine As Integer Dim startIndex As Integer Assert.True(documentResult.IdentifyingSpan.TryGetStartLineIndex(startLine, startIndex), "Unable to get span for metadata file.") Dim line = buffer.CurrentSnapshot.GetLineFromLineNumber(startLine) Return buffer.CurrentSnapshot.GetText(line.Start + startIndex, line.Length - startIndex) End Function Friend Sub AssertNavigatesToIdentifier(index As Integer, name As String) Dim documentResult = DirectCast(Items(index), IDocumentPeekResult) Dim document = _workspace.Documents.FirstOrDefault(Function(d) d.FilePath = documentResult.FilePath) AssertEx.NotNull(document, "Peek didn't navigate to a document in source. Navigated to " + documentResult.FilePath + " instead.") Dim startLine As Integer Dim startIndex As Integer Assert.True(documentResult.IdentifyingSpan.TryGetStartLineIndex(startLine, startIndex), "Unable to get span for source file.") Dim snapshot = document.GetTextBuffer().CurrentSnapshot Dim expectedPosition = New SnapshotPoint(snapshot, document.AnnotatedSpans(name).Single().Start) Dim actualPosition = snapshot.GetLineFromLineNumber(startLine).Start + startIndex Assert.Equal(expectedPosition, actualPosition) End Sub End Class End Class End Namespace
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/VisualBasicTest/Recommendations/Statements/CallKeywordRecommenderTests.vb
' 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements Public Class CallKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CallInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Call") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CallAfterStatementTest() VerifyRecommendationsContain(<MethodBody> Dim x |</MethodBody>, "Call") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CallMissingInClassBlockTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "Call") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CallInSingleLineLambdaTest() VerifyRecommendationsContain(<MethodBody>Dim x = Sub() |</MethodBody>, "Call") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CallNotInSingleLineFunctionLambdaTest() VerifyRecommendationsMissing(<MethodBody>Dim x = Function() |</MethodBody>, "Call") End Sub End Class End Namespace
' 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements Public Class CallKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CallInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Call") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CallAfterStatementTest() VerifyRecommendationsContain(<MethodBody> Dim x |</MethodBody>, "Call") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CallMissingInClassBlockTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "Call") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CallInSingleLineLambdaTest() VerifyRecommendationsContain(<MethodBody>Dim x = Sub() |</MethodBody>, "Call") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CallNotInSingleLineFunctionLambdaTest() VerifyRecommendationsMissing(<MethodBody>Dim x = Function() |</MethodBody>, "Call") End Sub End Class End Namespace
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/VisualStudio/VisualBasic/Impl/CodeModel/Interop/IVBCodeTypeLocation.vb
' 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. Imports System.Runtime.InteropServices Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop <ComImport> <InterfaceType(ComInterfaceType.InterfaceIsDual)> <Guid("69A529CD-84E3-4ee8-9918-A540CB827993")> Friend Interface IVBCodeTypeLocation ReadOnly Property ExternalLocation As String End Interface End Namespace
' 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. Imports System.Runtime.InteropServices Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop <ComImport> <InterfaceType(ComInterfaceType.InterfaceIsDual)> <Guid("69A529CD-84E3-4ee8-9918-A540CB827993")> Friend Interface IVBCodeTypeLocation ReadOnly Property ExternalLocation As String End Interface End Namespace
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/VisualBasic/Test/Semantic/Semantics/ConditionalExpressionsTests.vb
' 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. Imports System.IO Imports System.Xml Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class ConditionalExpressionsTests Inherits BasicTestBase <Fact> Public Sub TestTernaryConditionalSimple() TestCondition("if(True, 1, 2)", expectedType:="System.Int32") TestCondition("if(True, ""a""c, GetChar)", expectedType:="System.Char") TestCondition("if(False, GetString, ""abc"")", expectedType:="System.String") TestCondition("if(False, GetUserNonGeneric, New C())", expectedType:="C") TestCondition("if(True, ""a""c, GetString)", expectedType:="System.String") TestCondition("if(GetDouble > 1, GetInt, GetSingle)", expectedType:="System.Single") TestCondition("if(nothing, GetInt, GetObject)", expectedType:="System.Object") TestCondition("if(nothing, GetObject, ""1""c)", expectedType:="System.Object") TestCondition("if(True, GetByte, GetShort)", expectedType:="System.Int16") TestCondition("if(True, 1, GetShort)", expectedType:="System.Int32") TestCondition("if(True, 1.1, GetSingle)", expectedType:="System.Double") TestCondition("if(nothing, GetString, 1.234)", strict:=OptionStrict.On, errors:= <errors> BC36913: Cannot infer a common type because more than one type is possible. System.Console.WriteLine(if(nothing, GetString, 1.234)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(nothing, GetString, 1.234)", expectedType:="System.Object", strict:=OptionStrict.Custom, errors:= <errors> BC42021: Cannot infer a common type because more than one type is possible; 'Object' assumed. System.Console.WriteLine(if(nothing, GetString, 1.234)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(nothing, GetString, 1.234)", expectedType:="System.Object", strict:=OptionStrict.Off) End Sub <Fact> Public Sub TestBinaryConditionalSimple() TestCondition("if(Nothing, 2)", expectedType:="System.Int32") TestCondition("if(Nothing, GetIntOpt)", expectedType:="System.Nullable(Of System.Int32)") TestCondition("if(""string"", #1/1/1#)", expectedType:="System.String", strict:=OptionStrict.Off) TestCondition("if(CType(Nothing, String), ""str-123"")", expectedType:="System.String") TestCondition("if(CType(Nothing, String), Nothing)", expectedType:="System.String") TestCondition("if(Nothing, Nothing)", expectedType:="System.Object") TestCondition("if(CType(CType(Nothing, String), Object), GetIntOpt)", expectedType:="System.Object") TestCondition("if(CType(CType(Nothing, String), Object), GetInt)", expectedType:="System.Object") TestCondition("if(GetIntOpt, 2)", expectedType:="System.Int32") TestCondition("if(GetCharOpt(), ""a""c)", expectedType:="System.Char") TestCondition("if(GetString, ""abc"")", expectedType:="System.String") TestCondition("if(GetUserNonGeneric, New C())", expectedType:="C") TestCondition("if(GetString, ""a""c)", expectedType:="System.String") TestCondition("if(GetIntOpt, GetSingle)", expectedType:="System.Single") TestCondition("if(GetIntOpt, GetObject)", expectedType:="System.Object") TestCondition("if(GetObject, ""1""c)", expectedType:="System.Object") TestCondition("if(GetByteOpt(), GetShort)", expectedType:="System.Int16") TestCondition("if(GetShortOpt, 1)", expectedType:="System.Int32") TestCondition("if(GetSingleOpt, 1.1)", expectedType:="System.Double") TestCondition("if(GetString, 1.234)", strict:=OptionStrict.On, errors:= <errors> BC36913: Cannot infer a common type because more than one type is possible. System.Console.WriteLine(if(GetString, 1.234)) ~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(GetString, 1.234)", expectedType:="System.Object", strict:=OptionStrict.Custom) TestCondition("if(GetString, 1.234)", expectedType:="System.Object", strict:=OptionStrict.Off) End Sub <Fact> Public Sub TestTernaryConditionalGenerics() TestCondition("if(GetBoolean(), GetUserGeneric(Of T), GetUserGeneric(Of T))", expectedType:="D(Of T)") TestCondition("if(Nothing, GetTypeParameter(Of T), GetTypeParameter(Of T))", expectedType:="T") TestCondition("if(GetBoolean(), GetUserGeneric(Of T), GetUserGeneric(Of T))", expectedType:="D(Of T)") TestCondition("if(GetBoolean(), GetUserGeneric(Of T), Nothing)", expectedType:="D(Of T)") TestCondition("if(GetBoolean(), GetUserGeneric(Of T), ""abc"")", strict:=OptionStrict.On, errors:= <errors> BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. System.Console.WriteLine(if(GetBoolean(), GetUserGeneric(Of T), "abc")) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(GetBoolean(), GetUserGeneric(Of T), ""abc"")", expectedType:="System.Object", strict:=OptionStrict.Custom, errors:= <errors> BC42021: Cannot infer a common type; 'Object' assumed. System.Console.WriteLine(if(GetBoolean(), GetUserGeneric(Of T), "abc")) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(GetBoolean(), GetUserGeneric(Of T), ""abc"")", expectedType:="System.Object", strict:=OptionStrict.Off) End Sub <Fact> Public Sub TestBinaryConditionalGenerics() TestCondition("if(GetUserGeneric(Of T), GetUserGeneric(Of T))", expectedType:="D(Of T)") TestCondition("if(GetTypeParameter(Of T), GetTypeParameter(Of T))", expectedType:="T") TestCondition("if(GetUserGeneric(Of T), GetUserGeneric(Of T))", expectedType:="D(Of T)") TestCondition("if(GetUserGeneric(Of T), Nothing)", expectedType:="D(Of T)") TestCondition("if(Nothing, GetUserGeneric(Of T))", expectedType:="D(Of T)") TestCondition("if(GetUserGeneric(Of T), ""abc"")", strict:=OptionStrict.On, errors:= <errors> BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. System.Console.WriteLine(if(GetUserGeneric(Of T), "abc")) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(GetUserGeneric(Of T), ""abc"")", expectedType:="System.Object", strict:=OptionStrict.Custom, errors:= <errors> BC42021: Cannot infer a common type; 'Object' assumed. System.Console.WriteLine(if(GetUserGeneric(Of T), "abc")) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(GetUserGeneric(Of T), ""abc"")", expectedType:="System.Object", strict:=OptionStrict.Off) End Sub <Fact()> Public Sub TestTernaryConditionalVariantGenerics() TestCondition("if(Nothing, GetVariantInterface(Of String, Integer)(), GetVariantInterface(Of Object, Integer)())", expectedType:="I(Of System.String, System.Int32)") TestCondition("if(Nothing, GetVariantInterface(Of Integer, String)(), GetVariantInterface(Of Integer, Object)())", expectedType:="I(Of System.Int32, System.Object)") End Sub <Fact()> Public Sub TestBinaryConditionalVariantGenerics() TestCondition("if(GetVariantInterface(Of String, Integer)(), GetVariantInterface(Of Object, Integer)())", expectedType:="I(Of System.String, System.Int32)") TestCondition("if(GetVariantInterface(Of Integer, String)(), GetVariantInterface(Of Integer, Object)())", expectedType:="I(Of System.Int32, System.Object)") End Sub <Fact> Public Sub TestTernaryConditionalNothingAndNoType() TestCondition("if(True, New Object(), nothing)", expectedType:="System.Object") TestCondition("if(1 > 2, nothing, nothing)", expectedType:="System.Object") TestCondition("if(nothing, nothing, nothing)", expectedType:="System.Object", strict:=OptionStrict.Off) TestCondition("if(nothing, nothing, nothing)", expectedType:="System.Object", strict:=OptionStrict.Custom) TestCondition("if(nothing, nothing, nothing)", expectedType:="System.Object", strict:=OptionStrict.On) TestCondition("if(""yes"", nothing, nothing)", expectedType:="System.Object", strict:=OptionStrict.Off) TestCondition("if(""yes"", nothing, nothing)", expectedType:="System.Object", strict:=OptionStrict.Custom) TestCondition("if(""yes"", nothing, nothing)", strict:=OptionStrict.On, errors:= <errors> BC30512: Option Strict On disallows implicit conversions from 'String' to 'Boolean'. System.Console.WriteLine(if("yes", nothing, nothing)) ~~~~~ </errors>) TestCondition("if(1 > 2, nothing, 1)", expectedType:="System.Int32") TestCondition("if(1 > 2, nothing, 1.5)", expectedType:="System.Double") TestCondition("if(1 > 2, AddressOf Func1, 1.5)", errors:= <errors> BC30581: 'AddressOf' expression cannot be converted to 'Double' because 'Double' is not a delegate type. System.Console.WriteLine(if(1 > 2, AddressOf Func1, 1.5)) ~~~~~~~~~~~~~~~ </errors>) TestCondition("if(1 > 2, 1.5, AddressOf Func1)", errors:= <errors> BC30581: 'AddressOf' expression cannot be converted to 'Double' because 'Double' is not a delegate type. System.Console.WriteLine(if(1 > 2, 1.5, AddressOf Func1)) ~~~~~~~~~~~~~~~ </errors>) TestCondition("if(1 > 2, AddressOf Func1, AddressOf Func2)", strict:=OptionStrict.On, errors:= <errors> BC36911: Cannot infer a common type. System.Console.WriteLine(if(1 > 2, AddressOf Func1, AddressOf Func2)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TestBinaryConditionalNothingAndNoType() TestCondition("if(New Object(), nothing)", expectedType:="System.Object") TestCondition("if(nothing, nothing)", expectedType:="System.Object") TestCondition("if(GetIntOpt, nothing)", expectedType:="System.Nullable(Of System.Int32)") TestCondition("if(nothing, CByte(1))", expectedType:="System.Byte") TestCondition("if(nothing, 1.5)", expectedType:="System.Double") TestCondition("if(GetShortOpt(), GetByte)", expectedType:="System.Int16") TestCondition("if(GetShortOpt(), GetDouble)", expectedType:="System.Double") TestCondition("if(GetShortOpt(), GetSingleOpt())", expectedType:="System.Nullable(Of System.Single)") TestCondition("if(AddressOf Func1, 1.5)", errors:= <errors> BC30581: 'AddressOf' expression cannot be converted to 'Double' because 'Double' is not a delegate type. System.Console.WriteLine(if(AddressOf Func1, 1.5)) ~~~~~~~~~~~~~~~ </errors>) TestCondition("if(1.5, AddressOf Func1)", errors:= <errors> BC30581: 'AddressOf' expression cannot be converted to 'Double' because 'Double' is not a delegate type. System.Console.WriteLine(if(1.5, AddressOf Func1)) ~~~~~~~~~~~~~~~ </errors>) TestCondition("if(AddressOf Func1, AddressOf Func2)", strict:=OptionStrict.On, errors:= <errors> BC36911: Cannot infer a common type. System.Console.WriteLine(if(AddressOf Func1, AddressOf Func2)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub TestTernaryConditionalLambdas() TestCondition("if(1 > 2, Function() 1, Function() 1.2)", expectedType:="Function <generated method>() As System.Double") TestCondition("if(1 > 2, AddressOf Func1, Function(x As Integer) x)", expectedType:="Function <generated method>(x As System.Int32) As System.Int32") End Sub <Fact()> Public Sub TestBinaryConditionalLambdas() TestCondition("if(Function() 1, Function() 1.2)", expectedType:="Function <generated method>() As System.Double") TestCondition("if(AddressOf Func1, Function(x As Integer) x)", expectedType:="Function <generated method>(x As System.Int32) As System.Int32") End Sub Private Sub TestCondition(text As String, Optional errors As XElement = Nothing, Optional expectedType As String = Nothing, Optional strict As OptionStrict = OptionStrict.On) Dim source = <compilation name="TestInvalidNumberOfParametersInIfOperator"> <file name="a.vb"> Imports System Class C Sub Test(Of T, U)() Dim vT As T = Nothing Dim vU As U = Nothing System.Console.WriteLine({0}) End Sub Function GetBoolean() As Boolean Return True End Function Function GetInt() As Integer Return 1 End Function Function GetIntOpt() As Integer? Return Nothing End Function Function GetByte() As Byte Return 2 End Function Function GetByteOpt() As Byte? Return 2 End Function Function GetShort() As Short Return 3 End Function Function GetShortOpt() As Short? Return 3 End Function Function GetChar() As Char Return "C"c End Function Function GetCharOpt() As Char? Return "C"c End Function Function GetDouble() As Double Return 1.5 End Function Function GetDoubleOpt() As Double? Return 1.5 End Function Function GetSingle() As Single Return 1.6 End Function Function GetSingleOpt() As Single? Return 1.6 End Function Function GetString() As String Return "--str--" End Function Function GetObject() As Object Return New Object End Function Function GetUserNonGeneric() As C Return New C End Function Function GetUserGeneric(Of T)() As D(Of T) Return New D(Of T) End Function Function GetTypeParameter(Of T)() As T Return Nothing End Function Function GetVariantInterface(Of T, U)() As I(Of T, U) Return Nothing End Function Function Func1(p1 As Integer) As Integer Return Nothing End Function Function Func2(p1 As Integer, p2 As Integer) As Integer Return Nothing End Function End Class Class D(Of T) End Class Interface I(Of In T, Out U) End Interface </file> </compilation> source.<file>.Single().Value = String.Format(source.<file>.Single().Value, text) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(strict)) If errors IsNot Nothing Then CompilationUtils.AssertTheseDiagnostics(compilation, errors) Else CompilationUtils.AssertNoErrors(compilation) End If Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = tree.FindNodeOrTokenByKind(SyntaxKind.BinaryConditionalExpression).AsNode() If node Is Nothing Then node = tree.FindNodeOrTokenByKind(SyntaxKind.TernaryConditionalExpression).AsNode() Dim ifOp = DirectCast(node, TernaryConditionalExpressionSyntax) Assert.Equal("System.Boolean", CompilationUtils.GetSemanticInfoSummary(model, ifOp.Condition).ConvertedType.ToTestDisplayString()) If expectedType IsNot Nothing Then Assert.Equal(expectedType, CompilationUtils.GetSemanticInfoSummary(model, ifOp.WhenTrue).ConvertedType.ToTestDisplayString()) Assert.Equal(expectedType, CompilationUtils.GetSemanticInfoSummary(model, ifOp.WhenFalse).ConvertedType.ToTestDisplayString()) Assert.Equal(expectedType, CompilationUtils.GetSemanticInfoSummary(model, ifOp).Type.ToTestDisplayString()) End If Else If expectedType IsNot Nothing Then node = tree.FindNodeOrTokenByKind(SyntaxKind.BinaryConditionalExpression).AsNode() Dim ifOp = DirectCast(node, BinaryConditionalExpressionSyntax) ' not guaranteed :: Assert.Equal(expectedType, model.GetSemanticInfoInParent(ifOp.FirstExpression).Type.ToTestDisplayString()) ' not guaranteed :: Assert.Equal(expectedType, model.GetSemanticInfoInParent(ifOp.SecondExpression).Type.ToTestDisplayString()) Assert.Equal(expectedType, CompilationUtils.GetSemanticInfoSummary(model, ifOp).Type.ToTestDisplayString()) End If End If End Sub <Fact> Public Sub TestInvalidIfOperators() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TestInvalidNumberOfParametersInIfOperator"> <file name="a.vb"> Class CX Public F1 As Integer = If(True, 2, 3, 4, 5) Public F2 As Integer = If 1 Public F3 As Integer = If(1, Public F4 As Integer = If(True, 2 Public F5 As Integer = If(True, 2, 3, 4 Public F6 As Integer = If(True, 2, 3 4) Public F7 As Integer = If(True, 2 3 4) Public F8 As Integer = If(TestExpression:=True, TruePart:=1, FalsePart:=2) Public F9 As Integer = If(Nothing, FalsePart:=1) Public F10 As Integer = If(, 1) Public F10_ As Integer = If(1, ) Public F11 As Integer = If(True, , 1) Public F11_ As Integer = If(True, 1,) Public F12 As Integer = If(True, abc, 23) Public F13 As Integer = If(True, S, 23) Public F14 As Integer = If( Public F15 As Integer = If() Public F16 As Integer = If(True Public F17 As Integer = If(True) Public Sub S() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC33104: 'If' operator requires either two or three operands. Public F1 As Integer = If(True, 2, 3, 4, 5) ~~~~~~ BC30199: '(' expected. Public F2 As Integer = If 1 ~ BC30198: ')' expected. Public F3 As Integer = If(1, ~ BC30201: Expression expected. Public F3 As Integer = If(1, ~ BC30198: ')' expected. Public F4 As Integer = If(True, 2 ~ BC33104: 'If' operator requires either two or three operands. Public F5 As Integer = If(True, 2, 3, 4 ~~~ BC30198: ')' expected. Public F5 As Integer = If(True, 2, 3, 4 ~ BC32017: Comma, ')', or a valid expression continuation expected. Public F6 As Integer = If(True, 2, 3 4) ~ BC32017: Comma, ')', or a valid expression continuation expected. Public F7 As Integer = If(True, 2 3 4) ~~~ BC33105: 'If' operands cannot be named arguments. Public F8 As Integer = If(TestExpression:=True, TruePart:=1, FalsePart:=2) ~~~~~~~~~~~~~~~~ BC33105: 'If' operands cannot be named arguments. Public F8 As Integer = If(TestExpression:=True, TruePart:=1, FalsePart:=2) ~~~~~~~~~~ BC33105: 'If' operands cannot be named arguments. Public F8 As Integer = If(TestExpression:=True, TruePart:=1, FalsePart:=2) ~~~~~~~~~~~ BC33105: 'If' operands cannot be named arguments. Public F9 As Integer = If(Nothing, FalsePart:=1) ~~~~~~~~~~~ BC30201: Expression expected. Public F10 As Integer = If(, 1) ~ BC30201: Expression expected. Public F10_ As Integer = If(1, ) ~ BC30201: Expression expected. Public F11 As Integer = If(True, , 1) ~ BC30201: Expression expected. Public F11_ As Integer = If(True, 1,) ~ BC30451: 'abc' is not declared. It may be inaccessible due to its protection level. Public F12 As Integer = If(True, abc, 23) ~~~ BC30491: Expression does not produce a value. Public F13 As Integer = If(True, S, 23) ~ BC30198: ')' expected. Public F14 As Integer = If( ~ BC30201: Expression expected. Public F14 As Integer = If( ~ BC33104: 'If' operator requires either two or three operands. Public F14 As Integer = If( ~ BC33104: 'If' operator requires either two or three operands. Public F15 As Integer = If() ~ BC30198: ')' expected. Public F16 As Integer = If(True ~ BC33104: 'If' operator requires either two or three operands. Public F16 As Integer = If(True ~ BC33104: 'If' operator requires either two or three operands. Public F17 As Integer = If(True) ~ </expected>) End Sub Private Sub TestInvalidTernaryIfOperatorsStrict(strict As OptionStrict, errs As XElement) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TestInvalidIfOperatorsStrict"> <file name="a.vb"> Imports System Class CX Public F1 As Integer = If(True, "", 23) Public F2 As Integer = If("error", 1, 2) Public Sub S1() End Sub Public F3 As Integer = If(True, S1(), (Nothing)) Public Function FUNK1(x As Integer) As Integer Return 0 End Function Public Function FUNK2(x As Integer, Optional y As Integer = 0) As Integer Return 0 End Function Public F4 As Func(Of Integer, Integer) = If(True, Function(x As Integer) x, AddressOf FUNK1) Public F5 As Func(Of Integer, Integer) = If(True, Function(x As Integer) x, AddressOf FUNK2) Public F6 As Func(Of Integer, Integer) = If(True, AddressOf FUNK1, AddressOf FUNK2) Public G As CG(Of Boolean, DateTime, Integer, Short) = Nothing Public F7 As Object = If(G.P1, G.F2, G.P3) Public F8 As Object = If(G.F2, G.P3, G.F4) End Class Class CG(Of T1, T2, T3, T4) Public Sub TEST() Dim x1 As T1 = Nothing Dim x2 As T2 = Nothing Dim x3 As T3 = Nothing Dim v1 As T1 = If(x1, x2, x3) Dim v2 As T2 = If(True, x2, x3) Dim v3 As T3 = If(True, Nothing, x3) End Sub Public Property P1 As T1 Public Function F2() As T2 Return Nothing End Function Public Property P3 As T3 Public Function F4() As T4 Return Nothing End Function End Class </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(strict)) CompilationUtils.AssertTheseDiagnostics(compilation, errs) End Sub <Fact> Public Sub TestInvalidTernaryIfOperatorsStrictOn() TestInvalidTernaryIfOperatorsStrict(OptionStrict.On, <expected><![CDATA[ BC36913: Cannot infer a common type because more than one type is possible. Public F1 As Integer = If(True, "", 23) ~~~~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Boolean'. Public F2 As Integer = If("error", 1, 2) ~~~~~~~ BC30491: Expression does not produce a value. Public F3 As Integer = If(True, S1(), (Nothing)) ~~~~ BC36911: Cannot infer a common type. Public F6 As Func(Of Integer, Integer) = If(True, AddressOf FUNK1, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. Public F7 As Object = If(G.P1, G.F2, G.P3) ~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type 'Date' cannot be converted to 'Boolean'. Public F8 As Object = If(G.F2, G.P3, G.F4) ~~~~ BC30311: Value of type 'T1' cannot be converted to 'Boolean'. Dim v1 As T1 = If(x1, x2, x3) ~~ BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. Dim v2 As T2 = If(True, x2, x3) ~~~~~~~~~~~~~~~~ ]]> </expected>) End Sub <Fact> Public Sub TestInvalidTernaryIfOperatorsStrictCustom() TestInvalidTernaryIfOperatorsStrict(OptionStrict.Custom, <expected><![CDATA[ BC42016: Implicit conversion from 'Object' to 'Integer'. Public F1 As Integer = If(True, "", 23) ~~~~~~~~~~~~~~~~ BC42021: Cannot infer a common type because more than one type is possible; 'Object' assumed. Public F1 As Integer = If(True, "", 23) ~~~~~~~~~~~~~~~~ BC42016: Implicit conversion from 'String' to 'Boolean'. Public F2 As Integer = If("error", 1, 2) ~~~~~~~ BC30491: Expression does not produce a value. Public F3 As Integer = If(True, S1(), (Nothing)) ~~~~ BC36911: Cannot infer a common type. Public F6 As Func(Of Integer, Integer) = If(True, AddressOf FUNK1, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42021: Cannot infer a common type; 'Object' assumed. Public F7 As Object = If(G.P1, G.F2, G.P3) ~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type 'Date' cannot be converted to 'Boolean'. Public F8 As Object = If(G.F2, G.P3, G.F4) ~~~~ BC30311: Value of type 'T1' cannot be converted to 'Boolean'. Dim v1 As T1 = If(x1, x2, x3) ~~ BC42016: Implicit conversion from 'Object' to 'T2'. Dim v2 As T2 = If(True, x2, x3) ~~~~~~~~~~~~~~~~ BC42021: Cannot infer a common type; 'Object' assumed. Dim v2 As T2 = If(True, x2, x3) ~~~~~~~~~~~~~~~~ ]]> </expected>) End Sub <Fact> Public Sub TestInvalidTernaryIfOperatorsStrictOff() TestInvalidTernaryIfOperatorsStrict(OptionStrict.Off, <expected><![CDATA[ BC30491: Expression does not produce a value. Public F3 As Integer = If(True, S1(), (Nothing)) ~~~~ BC36911: Cannot infer a common type. Public F6 As Func(Of Integer, Integer) = If(True, AddressOf FUNK1, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type 'Date' cannot be converted to 'Boolean'. Public F8 As Object = If(G.F2, G.P3, G.F4) ~~~~ BC30311: Value of type 'T1' cannot be converted to 'Boolean'. Dim v1 As T1 = If(x1, x2, x3) ~~ ]]> </expected>) End Sub Private Sub TestInvalidBinaryIfOperatorsStrict(strict As OptionStrict, errs As XElement) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TestInvalidIfOperatorsStrict"> <file name="a.vb"> Imports System Class CX Public Sub S1() End Sub Public Function FUNK1(x As Integer) As Integer Return 0 End Function Public Function FUNK2(x As Integer, Optional y As Integer = 0) As Integer Return 0 End Function Public G As CG(Of Boolean, DateTime, Integer?, Short) = Nothing Sub TEST() Dim F1 As Object = If("", 23) Dim F2 As Object = If(23, "") Dim F3 As Object = If(S1(), (Nothing)) Dim F4 As Func(Of Integer, Integer) = If(Function(x As Integer) x, AddressOf FUNK1) Dim F5 As Func(Of Integer, Integer) = If(Function(x As Integer) x, AddressOf FUNK2) Dim F6 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) Dim F7 As Func(Of Integer, Integer) = If(AddressOf FUNK1, AddressOf FUNK2) Dim F8 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) Dim F9 As Object = If(G.P1, G.F2) Dim F9_ As Object = If(G.P1, Nothing) Dim F9__ As Object = If(Nothing, G.P1) Dim F10 As Object = If(G.F2, G.P3) Dim F11 As Object = If(G.P3, G.F4) Dim F12 As Object = If(G.F4, G.P3) Dim F13 As Func(Of Integer, Integer) = If(AddressOf FUNK1, Function(x As Integer) x) Dim F14 As Func(Of Integer, Integer) = If(AddressOf FUNK2, Function(x As Integer) x) End Sub End Class Class CG(Of T1, T2, T3, T4) Public Sub TEST() Dim x1 As T1 = Nothing Dim x2 As T2 = Nothing Dim v1 As T1 = If(x1, x2) End Sub Public Property P1 As T1 Public Function F2() As T2 Return Nothing End Function Public Property P3 As T3 Public Function F4() As T4 Return Nothing End Function End Class </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(strict)) CompilationUtils.AssertTheseDiagnostics(compilation, errs) End Sub <Fact> Public Sub TestInvalidBinaryIfOperatorsStrictOn() TestInvalidBinaryIfOperatorsStrict(OptionStrict.On, <expected><![CDATA[ BC36913: Cannot infer a common type because more than one type is possible. Dim F1 As Object = If("", 23) ~~~~~~~~~~ BC36913: Cannot infer a common type because more than one type is possible. Dim F2 As Object = If(23, "") ~~~~~~~~~~ BC30491: Expression does not produce a value. Dim F3 As Object = If(S1(), (Nothing)) ~~~~ BC36911: Cannot infer a common type. Dim F6 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36911: Cannot infer a common type. Dim F7 As Func(Of Integer, Integer) = If(AddressOf FUNK1, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36911: Cannot infer a common type. Dim F8 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. Dim F9 As Object = If(G.P1, G.F2) ~~~~~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F9_ As Object = If(G.P1, Nothing) ~~~~ BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. Dim F10 As Object = If(G.F2, G.P3) ~~~~~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F12 As Object = If(G.F4, G.P3) ~~~~ BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. Dim v1 As T1 = If(x1, x2) ~~~~~~~~~~ ]]> </expected>) End Sub <Fact> Public Sub TestInvalidBinaryIfOperatorsStrictCustom() TestInvalidBinaryIfOperatorsStrict(OptionStrict.Custom, <expected><![CDATA[ BC42021: Cannot infer a common type because more than one type is possible; 'Object' assumed. Dim F1 As Object = If("", 23) ~~~~~~~~~~ BC42021: Cannot infer a common type because more than one type is possible; 'Object' assumed. Dim F2 As Object = If(23, "") ~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F2 As Object = If(23, "") ~~ BC30491: Expression does not produce a value. Dim F3 As Object = If(S1(), (Nothing)) ~~~~ BC36911: Cannot infer a common type. Dim F6 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36911: Cannot infer a common type. Dim F7 As Func(Of Integer, Integer) = If(AddressOf FUNK1, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36911: Cannot infer a common type. Dim F8 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42021: Cannot infer a common type; 'Object' assumed. Dim F9 As Object = If(G.P1, G.F2) ~~~~~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F9 As Object = If(G.P1, G.F2) ~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F9_ As Object = If(G.P1, Nothing) ~~~~ BC42021: Cannot infer a common type; 'Object' assumed. Dim F10 As Object = If(G.F2, G.P3) ~~~~~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F10 As Object = If(G.F2, G.P3) ~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F12 As Object = If(G.F4, G.P3) ~~~~ BC42016: Implicit conversion from 'Object' to 'T1'. Dim v1 As T1 = If(x1, x2) ~~~~~~~~~~ BC42021: Cannot infer a common type; 'Object' assumed. Dim v1 As T1 = If(x1, x2) ~~~~~~~~~~ ]]> </expected>) End Sub '<Fact(skip:="Temp variables in property/field initializers are not supported")> <Fact> Public Sub TestInvalidBinaryIfOperatorsStrictOff() TestInvalidBinaryIfOperatorsStrict(OptionStrict.Off, <expected><![CDATA[ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F2 As Object = If(23, "") ~~ BC30491: Expression does not produce a value. Dim F3 As Object = If(S1(), (Nothing)) ~~~~ BC36911: Cannot infer a common type. Dim F6 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36911: Cannot infer a common type. Dim F7 As Func(Of Integer, Integer) = If(AddressOf FUNK1, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36911: Cannot infer a common type. Dim F8 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F9 As Object = If(G.P1, G.F2) ~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F9_ As Object = If(G.P1, Nothing) ~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F10 As Object = If(G.F2, G.P3) ~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F12 As Object = If(G.F4, G.P3) ~~~~ ]]> </expected>) End Sub <Fact, WorkItem(544983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544983")> Public Sub Bug13187() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Option Strict On Imports System Module Module1 Structure S End Structure Function Full() As S System.Console.WriteLine("Full") Return New S() End Function Function M(o As S?) As Integer Dim i = If(o, Full()) Return 1 End Function Sub Main() M(New S()) System.Console.WriteLine("----") Dim x = If(New S?(Nothing), New S()) System.Console.WriteLine("----") M(Nothing) End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseExe) Dim verifier = CompileAndVerify(comp, expectedOutput:= <![CDATA[ ---- ---- Full ]]>) End Sub <Fact, WorkItem(544983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544983")> Public Sub Bug13187_2() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main(args As String()) Test1() Test2() Test3() Test4() End Sub Function GetX() As Integer? Return 1 End Function Function GetY() As Integer? System.Console.WriteLine("GetY") Return Nothing End Function Function GetZ() As Long? System.Console.WriteLine("GetZ") Return Nothing End Function Sub Test1() System.Console.WriteLine(If(GetX, GetY)) End Sub Sub Test2() System.Console.WriteLine(If(GetX, GetZ)) End Sub Sub Test3() Dim x as Integer = 4 Dim z= If(New Integer?(x), GetY) System.Console.WriteLine(z) End Sub Sub Test4() Dim x as Integer = 5 Dim z = If(New Integer?(x), GetZ) System.Console.WriteLine(z) End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseExe) Dim verifier = CompileAndVerify(comp, expectedOutput:= <![CDATA[ 1 1 4 5 ]]>) verifier.VerifyIL("Module1.Test1", <![CDATA[ { // Code size 36 (0x24) .maxstack 2 .locals init (Integer? V_0, Integer? V_1) IL_0000: call "Function Module1.GetX() As Integer?" IL_0005: dup IL_0006: stloc.0 IL_0007: stloc.1 IL_0008: ldloca.s V_1 IL_000a: call "Function Integer?.get_HasValue() As Boolean" IL_000f: brtrue.s IL_0018 IL_0011: call "Function Module1.GetY() As Integer?" IL_0016: br.s IL_0019 IL_0018: ldloc.0 IL_0019: box "Integer?" IL_001e: call "Sub System.Console.WriteLine(Object)" IL_0023: ret } ]]>) verifier.VerifyIL("Module1.Test2", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 .locals init (Integer? V_0, Integer? V_1) IL_0000: call "Function Module1.GetX() As Integer?" IL_0005: dup IL_0006: stloc.0 IL_0007: stloc.1 IL_0008: ldloca.s V_1 IL_000a: call "Function Integer?.get_HasValue() As Boolean" IL_000f: brtrue.s IL_0018 IL_0011: call "Function Module1.GetZ() As Long?" IL_0016: br.s IL_0025 IL_0018: ldloca.s V_0 IL_001a: call "Function Integer?.GetValueOrDefault() As Integer" IL_001f: conv.i8 IL_0020: newobj "Sub Long?..ctor(Long)" IL_0025: box "Long?" IL_002a: call "Sub System.Console.WriteLine(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Module1.Test3", <![CDATA[ { // Code size 19 (0x13) .maxstack 1 .locals init (Integer V_0) //x IL_0000: ldc.i4.4 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: newobj "Sub Integer?..ctor(Integer)" IL_0008: box "Integer?" IL_000d: call "Sub System.Console.WriteLine(Object)" IL_0012: ret } ]]>) verifier.VerifyIL("Module1.Test4", <![CDATA[ { // Code size 20 (0x14) .maxstack 1 .locals init (Integer V_0) //x IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: conv.i8 IL_0004: newobj "Sub Long?..ctor(Long)" IL_0009: box "Long?" IL_000e: call "Sub System.Console.WriteLine(Object)" IL_0013: ret } ]]>) End Sub End Class End Namespace
' 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. Imports System.IO Imports System.Xml Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class ConditionalExpressionsTests Inherits BasicTestBase <Fact> Public Sub TestTernaryConditionalSimple() TestCondition("if(True, 1, 2)", expectedType:="System.Int32") TestCondition("if(True, ""a""c, GetChar)", expectedType:="System.Char") TestCondition("if(False, GetString, ""abc"")", expectedType:="System.String") TestCondition("if(False, GetUserNonGeneric, New C())", expectedType:="C") TestCondition("if(True, ""a""c, GetString)", expectedType:="System.String") TestCondition("if(GetDouble > 1, GetInt, GetSingle)", expectedType:="System.Single") TestCondition("if(nothing, GetInt, GetObject)", expectedType:="System.Object") TestCondition("if(nothing, GetObject, ""1""c)", expectedType:="System.Object") TestCondition("if(True, GetByte, GetShort)", expectedType:="System.Int16") TestCondition("if(True, 1, GetShort)", expectedType:="System.Int32") TestCondition("if(True, 1.1, GetSingle)", expectedType:="System.Double") TestCondition("if(nothing, GetString, 1.234)", strict:=OptionStrict.On, errors:= <errors> BC36913: Cannot infer a common type because more than one type is possible. System.Console.WriteLine(if(nothing, GetString, 1.234)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(nothing, GetString, 1.234)", expectedType:="System.Object", strict:=OptionStrict.Custom, errors:= <errors> BC42021: Cannot infer a common type because more than one type is possible; 'Object' assumed. System.Console.WriteLine(if(nothing, GetString, 1.234)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(nothing, GetString, 1.234)", expectedType:="System.Object", strict:=OptionStrict.Off) End Sub <Fact> Public Sub TestBinaryConditionalSimple() TestCondition("if(Nothing, 2)", expectedType:="System.Int32") TestCondition("if(Nothing, GetIntOpt)", expectedType:="System.Nullable(Of System.Int32)") TestCondition("if(""string"", #1/1/1#)", expectedType:="System.String", strict:=OptionStrict.Off) TestCondition("if(CType(Nothing, String), ""str-123"")", expectedType:="System.String") TestCondition("if(CType(Nothing, String), Nothing)", expectedType:="System.String") TestCondition("if(Nothing, Nothing)", expectedType:="System.Object") TestCondition("if(CType(CType(Nothing, String), Object), GetIntOpt)", expectedType:="System.Object") TestCondition("if(CType(CType(Nothing, String), Object), GetInt)", expectedType:="System.Object") TestCondition("if(GetIntOpt, 2)", expectedType:="System.Int32") TestCondition("if(GetCharOpt(), ""a""c)", expectedType:="System.Char") TestCondition("if(GetString, ""abc"")", expectedType:="System.String") TestCondition("if(GetUserNonGeneric, New C())", expectedType:="C") TestCondition("if(GetString, ""a""c)", expectedType:="System.String") TestCondition("if(GetIntOpt, GetSingle)", expectedType:="System.Single") TestCondition("if(GetIntOpt, GetObject)", expectedType:="System.Object") TestCondition("if(GetObject, ""1""c)", expectedType:="System.Object") TestCondition("if(GetByteOpt(), GetShort)", expectedType:="System.Int16") TestCondition("if(GetShortOpt, 1)", expectedType:="System.Int32") TestCondition("if(GetSingleOpt, 1.1)", expectedType:="System.Double") TestCondition("if(GetString, 1.234)", strict:=OptionStrict.On, errors:= <errors> BC36913: Cannot infer a common type because more than one type is possible. System.Console.WriteLine(if(GetString, 1.234)) ~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(GetString, 1.234)", expectedType:="System.Object", strict:=OptionStrict.Custom) TestCondition("if(GetString, 1.234)", expectedType:="System.Object", strict:=OptionStrict.Off) End Sub <Fact> Public Sub TestTernaryConditionalGenerics() TestCondition("if(GetBoolean(), GetUserGeneric(Of T), GetUserGeneric(Of T))", expectedType:="D(Of T)") TestCondition("if(Nothing, GetTypeParameter(Of T), GetTypeParameter(Of T))", expectedType:="T") TestCondition("if(GetBoolean(), GetUserGeneric(Of T), GetUserGeneric(Of T))", expectedType:="D(Of T)") TestCondition("if(GetBoolean(), GetUserGeneric(Of T), Nothing)", expectedType:="D(Of T)") TestCondition("if(GetBoolean(), GetUserGeneric(Of T), ""abc"")", strict:=OptionStrict.On, errors:= <errors> BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. System.Console.WriteLine(if(GetBoolean(), GetUserGeneric(Of T), "abc")) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(GetBoolean(), GetUserGeneric(Of T), ""abc"")", expectedType:="System.Object", strict:=OptionStrict.Custom, errors:= <errors> BC42021: Cannot infer a common type; 'Object' assumed. System.Console.WriteLine(if(GetBoolean(), GetUserGeneric(Of T), "abc")) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(GetBoolean(), GetUserGeneric(Of T), ""abc"")", expectedType:="System.Object", strict:=OptionStrict.Off) End Sub <Fact> Public Sub TestBinaryConditionalGenerics() TestCondition("if(GetUserGeneric(Of T), GetUserGeneric(Of T))", expectedType:="D(Of T)") TestCondition("if(GetTypeParameter(Of T), GetTypeParameter(Of T))", expectedType:="T") TestCondition("if(GetUserGeneric(Of T), GetUserGeneric(Of T))", expectedType:="D(Of T)") TestCondition("if(GetUserGeneric(Of T), Nothing)", expectedType:="D(Of T)") TestCondition("if(Nothing, GetUserGeneric(Of T))", expectedType:="D(Of T)") TestCondition("if(GetUserGeneric(Of T), ""abc"")", strict:=OptionStrict.On, errors:= <errors> BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. System.Console.WriteLine(if(GetUserGeneric(Of T), "abc")) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(GetUserGeneric(Of T), ""abc"")", expectedType:="System.Object", strict:=OptionStrict.Custom, errors:= <errors> BC42021: Cannot infer a common type; 'Object' assumed. System.Console.WriteLine(if(GetUserGeneric(Of T), "abc")) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) TestCondition("if(GetUserGeneric(Of T), ""abc"")", expectedType:="System.Object", strict:=OptionStrict.Off) End Sub <Fact()> Public Sub TestTernaryConditionalVariantGenerics() TestCondition("if(Nothing, GetVariantInterface(Of String, Integer)(), GetVariantInterface(Of Object, Integer)())", expectedType:="I(Of System.String, System.Int32)") TestCondition("if(Nothing, GetVariantInterface(Of Integer, String)(), GetVariantInterface(Of Integer, Object)())", expectedType:="I(Of System.Int32, System.Object)") End Sub <Fact()> Public Sub TestBinaryConditionalVariantGenerics() TestCondition("if(GetVariantInterface(Of String, Integer)(), GetVariantInterface(Of Object, Integer)())", expectedType:="I(Of System.String, System.Int32)") TestCondition("if(GetVariantInterface(Of Integer, String)(), GetVariantInterface(Of Integer, Object)())", expectedType:="I(Of System.Int32, System.Object)") End Sub <Fact> Public Sub TestTernaryConditionalNothingAndNoType() TestCondition("if(True, New Object(), nothing)", expectedType:="System.Object") TestCondition("if(1 > 2, nothing, nothing)", expectedType:="System.Object") TestCondition("if(nothing, nothing, nothing)", expectedType:="System.Object", strict:=OptionStrict.Off) TestCondition("if(nothing, nothing, nothing)", expectedType:="System.Object", strict:=OptionStrict.Custom) TestCondition("if(nothing, nothing, nothing)", expectedType:="System.Object", strict:=OptionStrict.On) TestCondition("if(""yes"", nothing, nothing)", expectedType:="System.Object", strict:=OptionStrict.Off) TestCondition("if(""yes"", nothing, nothing)", expectedType:="System.Object", strict:=OptionStrict.Custom) TestCondition("if(""yes"", nothing, nothing)", strict:=OptionStrict.On, errors:= <errors> BC30512: Option Strict On disallows implicit conversions from 'String' to 'Boolean'. System.Console.WriteLine(if("yes", nothing, nothing)) ~~~~~ </errors>) TestCondition("if(1 > 2, nothing, 1)", expectedType:="System.Int32") TestCondition("if(1 > 2, nothing, 1.5)", expectedType:="System.Double") TestCondition("if(1 > 2, AddressOf Func1, 1.5)", errors:= <errors> BC30581: 'AddressOf' expression cannot be converted to 'Double' because 'Double' is not a delegate type. System.Console.WriteLine(if(1 > 2, AddressOf Func1, 1.5)) ~~~~~~~~~~~~~~~ </errors>) TestCondition("if(1 > 2, 1.5, AddressOf Func1)", errors:= <errors> BC30581: 'AddressOf' expression cannot be converted to 'Double' because 'Double' is not a delegate type. System.Console.WriteLine(if(1 > 2, 1.5, AddressOf Func1)) ~~~~~~~~~~~~~~~ </errors>) TestCondition("if(1 > 2, AddressOf Func1, AddressOf Func2)", strict:=OptionStrict.On, errors:= <errors> BC36911: Cannot infer a common type. System.Console.WriteLine(if(1 > 2, AddressOf Func1, AddressOf Func2)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TestBinaryConditionalNothingAndNoType() TestCondition("if(New Object(), nothing)", expectedType:="System.Object") TestCondition("if(nothing, nothing)", expectedType:="System.Object") TestCondition("if(GetIntOpt, nothing)", expectedType:="System.Nullable(Of System.Int32)") TestCondition("if(nothing, CByte(1))", expectedType:="System.Byte") TestCondition("if(nothing, 1.5)", expectedType:="System.Double") TestCondition("if(GetShortOpt(), GetByte)", expectedType:="System.Int16") TestCondition("if(GetShortOpt(), GetDouble)", expectedType:="System.Double") TestCondition("if(GetShortOpt(), GetSingleOpt())", expectedType:="System.Nullable(Of System.Single)") TestCondition("if(AddressOf Func1, 1.5)", errors:= <errors> BC30581: 'AddressOf' expression cannot be converted to 'Double' because 'Double' is not a delegate type. System.Console.WriteLine(if(AddressOf Func1, 1.5)) ~~~~~~~~~~~~~~~ </errors>) TestCondition("if(1.5, AddressOf Func1)", errors:= <errors> BC30581: 'AddressOf' expression cannot be converted to 'Double' because 'Double' is not a delegate type. System.Console.WriteLine(if(1.5, AddressOf Func1)) ~~~~~~~~~~~~~~~ </errors>) TestCondition("if(AddressOf Func1, AddressOf Func2)", strict:=OptionStrict.On, errors:= <errors> BC36911: Cannot infer a common type. System.Console.WriteLine(if(AddressOf Func1, AddressOf Func2)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub TestTernaryConditionalLambdas() TestCondition("if(1 > 2, Function() 1, Function() 1.2)", expectedType:="Function <generated method>() As System.Double") TestCondition("if(1 > 2, AddressOf Func1, Function(x As Integer) x)", expectedType:="Function <generated method>(x As System.Int32) As System.Int32") End Sub <Fact()> Public Sub TestBinaryConditionalLambdas() TestCondition("if(Function() 1, Function() 1.2)", expectedType:="Function <generated method>() As System.Double") TestCondition("if(AddressOf Func1, Function(x As Integer) x)", expectedType:="Function <generated method>(x As System.Int32) As System.Int32") End Sub Private Sub TestCondition(text As String, Optional errors As XElement = Nothing, Optional expectedType As String = Nothing, Optional strict As OptionStrict = OptionStrict.On) Dim source = <compilation name="TestInvalidNumberOfParametersInIfOperator"> <file name="a.vb"> Imports System Class C Sub Test(Of T, U)() Dim vT As T = Nothing Dim vU As U = Nothing System.Console.WriteLine({0}) End Sub Function GetBoolean() As Boolean Return True End Function Function GetInt() As Integer Return 1 End Function Function GetIntOpt() As Integer? Return Nothing End Function Function GetByte() As Byte Return 2 End Function Function GetByteOpt() As Byte? Return 2 End Function Function GetShort() As Short Return 3 End Function Function GetShortOpt() As Short? Return 3 End Function Function GetChar() As Char Return "C"c End Function Function GetCharOpt() As Char? Return "C"c End Function Function GetDouble() As Double Return 1.5 End Function Function GetDoubleOpt() As Double? Return 1.5 End Function Function GetSingle() As Single Return 1.6 End Function Function GetSingleOpt() As Single? Return 1.6 End Function Function GetString() As String Return "--str--" End Function Function GetObject() As Object Return New Object End Function Function GetUserNonGeneric() As C Return New C End Function Function GetUserGeneric(Of T)() As D(Of T) Return New D(Of T) End Function Function GetTypeParameter(Of T)() As T Return Nothing End Function Function GetVariantInterface(Of T, U)() As I(Of T, U) Return Nothing End Function Function Func1(p1 As Integer) As Integer Return Nothing End Function Function Func2(p1 As Integer, p2 As Integer) As Integer Return Nothing End Function End Class Class D(Of T) End Class Interface I(Of In T, Out U) End Interface </file> </compilation> source.<file>.Single().Value = String.Format(source.<file>.Single().Value, text) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(strict)) If errors IsNot Nothing Then CompilationUtils.AssertTheseDiagnostics(compilation, errors) Else CompilationUtils.AssertNoErrors(compilation) End If Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = tree.FindNodeOrTokenByKind(SyntaxKind.BinaryConditionalExpression).AsNode() If node Is Nothing Then node = tree.FindNodeOrTokenByKind(SyntaxKind.TernaryConditionalExpression).AsNode() Dim ifOp = DirectCast(node, TernaryConditionalExpressionSyntax) Assert.Equal("System.Boolean", CompilationUtils.GetSemanticInfoSummary(model, ifOp.Condition).ConvertedType.ToTestDisplayString()) If expectedType IsNot Nothing Then Assert.Equal(expectedType, CompilationUtils.GetSemanticInfoSummary(model, ifOp.WhenTrue).ConvertedType.ToTestDisplayString()) Assert.Equal(expectedType, CompilationUtils.GetSemanticInfoSummary(model, ifOp.WhenFalse).ConvertedType.ToTestDisplayString()) Assert.Equal(expectedType, CompilationUtils.GetSemanticInfoSummary(model, ifOp).Type.ToTestDisplayString()) End If Else If expectedType IsNot Nothing Then node = tree.FindNodeOrTokenByKind(SyntaxKind.BinaryConditionalExpression).AsNode() Dim ifOp = DirectCast(node, BinaryConditionalExpressionSyntax) ' not guaranteed :: Assert.Equal(expectedType, model.GetSemanticInfoInParent(ifOp.FirstExpression).Type.ToTestDisplayString()) ' not guaranteed :: Assert.Equal(expectedType, model.GetSemanticInfoInParent(ifOp.SecondExpression).Type.ToTestDisplayString()) Assert.Equal(expectedType, CompilationUtils.GetSemanticInfoSummary(model, ifOp).Type.ToTestDisplayString()) End If End If End Sub <Fact> Public Sub TestInvalidIfOperators() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TestInvalidNumberOfParametersInIfOperator"> <file name="a.vb"> Class CX Public F1 As Integer = If(True, 2, 3, 4, 5) Public F2 As Integer = If 1 Public F3 As Integer = If(1, Public F4 As Integer = If(True, 2 Public F5 As Integer = If(True, 2, 3, 4 Public F6 As Integer = If(True, 2, 3 4) Public F7 As Integer = If(True, 2 3 4) Public F8 As Integer = If(TestExpression:=True, TruePart:=1, FalsePart:=2) Public F9 As Integer = If(Nothing, FalsePart:=1) Public F10 As Integer = If(, 1) Public F10_ As Integer = If(1, ) Public F11 As Integer = If(True, , 1) Public F11_ As Integer = If(True, 1,) Public F12 As Integer = If(True, abc, 23) Public F13 As Integer = If(True, S, 23) Public F14 As Integer = If( Public F15 As Integer = If() Public F16 As Integer = If(True Public F17 As Integer = If(True) Public Sub S() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC33104: 'If' operator requires either two or three operands. Public F1 As Integer = If(True, 2, 3, 4, 5) ~~~~~~ BC30199: '(' expected. Public F2 As Integer = If 1 ~ BC30198: ')' expected. Public F3 As Integer = If(1, ~ BC30201: Expression expected. Public F3 As Integer = If(1, ~ BC30198: ')' expected. Public F4 As Integer = If(True, 2 ~ BC33104: 'If' operator requires either two or three operands. Public F5 As Integer = If(True, 2, 3, 4 ~~~ BC30198: ')' expected. Public F5 As Integer = If(True, 2, 3, 4 ~ BC32017: Comma, ')', or a valid expression continuation expected. Public F6 As Integer = If(True, 2, 3 4) ~ BC32017: Comma, ')', or a valid expression continuation expected. Public F7 As Integer = If(True, 2 3 4) ~~~ BC33105: 'If' operands cannot be named arguments. Public F8 As Integer = If(TestExpression:=True, TruePart:=1, FalsePart:=2) ~~~~~~~~~~~~~~~~ BC33105: 'If' operands cannot be named arguments. Public F8 As Integer = If(TestExpression:=True, TruePart:=1, FalsePart:=2) ~~~~~~~~~~ BC33105: 'If' operands cannot be named arguments. Public F8 As Integer = If(TestExpression:=True, TruePart:=1, FalsePart:=2) ~~~~~~~~~~~ BC33105: 'If' operands cannot be named arguments. Public F9 As Integer = If(Nothing, FalsePart:=1) ~~~~~~~~~~~ BC30201: Expression expected. Public F10 As Integer = If(, 1) ~ BC30201: Expression expected. Public F10_ As Integer = If(1, ) ~ BC30201: Expression expected. Public F11 As Integer = If(True, , 1) ~ BC30201: Expression expected. Public F11_ As Integer = If(True, 1,) ~ BC30451: 'abc' is not declared. It may be inaccessible due to its protection level. Public F12 As Integer = If(True, abc, 23) ~~~ BC30491: Expression does not produce a value. Public F13 As Integer = If(True, S, 23) ~ BC30198: ')' expected. Public F14 As Integer = If( ~ BC30201: Expression expected. Public F14 As Integer = If( ~ BC33104: 'If' operator requires either two or three operands. Public F14 As Integer = If( ~ BC33104: 'If' operator requires either two or three operands. Public F15 As Integer = If() ~ BC30198: ')' expected. Public F16 As Integer = If(True ~ BC33104: 'If' operator requires either two or three operands. Public F16 As Integer = If(True ~ BC33104: 'If' operator requires either two or three operands. Public F17 As Integer = If(True) ~ </expected>) End Sub Private Sub TestInvalidTernaryIfOperatorsStrict(strict As OptionStrict, errs As XElement) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TestInvalidIfOperatorsStrict"> <file name="a.vb"> Imports System Class CX Public F1 As Integer = If(True, "", 23) Public F2 As Integer = If("error", 1, 2) Public Sub S1() End Sub Public F3 As Integer = If(True, S1(), (Nothing)) Public Function FUNK1(x As Integer) As Integer Return 0 End Function Public Function FUNK2(x As Integer, Optional y As Integer = 0) As Integer Return 0 End Function Public F4 As Func(Of Integer, Integer) = If(True, Function(x As Integer) x, AddressOf FUNK1) Public F5 As Func(Of Integer, Integer) = If(True, Function(x As Integer) x, AddressOf FUNK2) Public F6 As Func(Of Integer, Integer) = If(True, AddressOf FUNK1, AddressOf FUNK2) Public G As CG(Of Boolean, DateTime, Integer, Short) = Nothing Public F7 As Object = If(G.P1, G.F2, G.P3) Public F8 As Object = If(G.F2, G.P3, G.F4) End Class Class CG(Of T1, T2, T3, T4) Public Sub TEST() Dim x1 As T1 = Nothing Dim x2 As T2 = Nothing Dim x3 As T3 = Nothing Dim v1 As T1 = If(x1, x2, x3) Dim v2 As T2 = If(True, x2, x3) Dim v3 As T3 = If(True, Nothing, x3) End Sub Public Property P1 As T1 Public Function F2() As T2 Return Nothing End Function Public Property P3 As T3 Public Function F4() As T4 Return Nothing End Function End Class </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(strict)) CompilationUtils.AssertTheseDiagnostics(compilation, errs) End Sub <Fact> Public Sub TestInvalidTernaryIfOperatorsStrictOn() TestInvalidTernaryIfOperatorsStrict(OptionStrict.On, <expected><![CDATA[ BC36913: Cannot infer a common type because more than one type is possible. Public F1 As Integer = If(True, "", 23) ~~~~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Boolean'. Public F2 As Integer = If("error", 1, 2) ~~~~~~~ BC30491: Expression does not produce a value. Public F3 As Integer = If(True, S1(), (Nothing)) ~~~~ BC36911: Cannot infer a common type. Public F6 As Func(Of Integer, Integer) = If(True, AddressOf FUNK1, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. Public F7 As Object = If(G.P1, G.F2, G.P3) ~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type 'Date' cannot be converted to 'Boolean'. Public F8 As Object = If(G.F2, G.P3, G.F4) ~~~~ BC30311: Value of type 'T1' cannot be converted to 'Boolean'. Dim v1 As T1 = If(x1, x2, x3) ~~ BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. Dim v2 As T2 = If(True, x2, x3) ~~~~~~~~~~~~~~~~ ]]> </expected>) End Sub <Fact> Public Sub TestInvalidTernaryIfOperatorsStrictCustom() TestInvalidTernaryIfOperatorsStrict(OptionStrict.Custom, <expected><![CDATA[ BC42016: Implicit conversion from 'Object' to 'Integer'. Public F1 As Integer = If(True, "", 23) ~~~~~~~~~~~~~~~~ BC42021: Cannot infer a common type because more than one type is possible; 'Object' assumed. Public F1 As Integer = If(True, "", 23) ~~~~~~~~~~~~~~~~ BC42016: Implicit conversion from 'String' to 'Boolean'. Public F2 As Integer = If("error", 1, 2) ~~~~~~~ BC30491: Expression does not produce a value. Public F3 As Integer = If(True, S1(), (Nothing)) ~~~~ BC36911: Cannot infer a common type. Public F6 As Func(Of Integer, Integer) = If(True, AddressOf FUNK1, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42021: Cannot infer a common type; 'Object' assumed. Public F7 As Object = If(G.P1, G.F2, G.P3) ~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type 'Date' cannot be converted to 'Boolean'. Public F8 As Object = If(G.F2, G.P3, G.F4) ~~~~ BC30311: Value of type 'T1' cannot be converted to 'Boolean'. Dim v1 As T1 = If(x1, x2, x3) ~~ BC42016: Implicit conversion from 'Object' to 'T2'. Dim v2 As T2 = If(True, x2, x3) ~~~~~~~~~~~~~~~~ BC42021: Cannot infer a common type; 'Object' assumed. Dim v2 As T2 = If(True, x2, x3) ~~~~~~~~~~~~~~~~ ]]> </expected>) End Sub <Fact> Public Sub TestInvalidTernaryIfOperatorsStrictOff() TestInvalidTernaryIfOperatorsStrict(OptionStrict.Off, <expected><![CDATA[ BC30491: Expression does not produce a value. Public F3 As Integer = If(True, S1(), (Nothing)) ~~~~ BC36911: Cannot infer a common type. Public F6 As Func(Of Integer, Integer) = If(True, AddressOf FUNK1, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type 'Date' cannot be converted to 'Boolean'. Public F8 As Object = If(G.F2, G.P3, G.F4) ~~~~ BC30311: Value of type 'T1' cannot be converted to 'Boolean'. Dim v1 As T1 = If(x1, x2, x3) ~~ ]]> </expected>) End Sub Private Sub TestInvalidBinaryIfOperatorsStrict(strict As OptionStrict, errs As XElement) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="TestInvalidIfOperatorsStrict"> <file name="a.vb"> Imports System Class CX Public Sub S1() End Sub Public Function FUNK1(x As Integer) As Integer Return 0 End Function Public Function FUNK2(x As Integer, Optional y As Integer = 0) As Integer Return 0 End Function Public G As CG(Of Boolean, DateTime, Integer?, Short) = Nothing Sub TEST() Dim F1 As Object = If("", 23) Dim F2 As Object = If(23, "") Dim F3 As Object = If(S1(), (Nothing)) Dim F4 As Func(Of Integer, Integer) = If(Function(x As Integer) x, AddressOf FUNK1) Dim F5 As Func(Of Integer, Integer) = If(Function(x As Integer) x, AddressOf FUNK2) Dim F6 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) Dim F7 As Func(Of Integer, Integer) = If(AddressOf FUNK1, AddressOf FUNK2) Dim F8 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) Dim F9 As Object = If(G.P1, G.F2) Dim F9_ As Object = If(G.P1, Nothing) Dim F9__ As Object = If(Nothing, G.P1) Dim F10 As Object = If(G.F2, G.P3) Dim F11 As Object = If(G.P3, G.F4) Dim F12 As Object = If(G.F4, G.P3) Dim F13 As Func(Of Integer, Integer) = If(AddressOf FUNK1, Function(x As Integer) x) Dim F14 As Func(Of Integer, Integer) = If(AddressOf FUNK2, Function(x As Integer) x) End Sub End Class Class CG(Of T1, T2, T3, T4) Public Sub TEST() Dim x1 As T1 = Nothing Dim x2 As T2 = Nothing Dim v1 As T1 = If(x1, x2) End Sub Public Property P1 As T1 Public Function F2() As T2 Return Nothing End Function Public Property P3 As T3 Public Function F4() As T4 Return Nothing End Function End Class </file> </compilation>, TestOptions.ReleaseDll.WithOptionStrict(strict)) CompilationUtils.AssertTheseDiagnostics(compilation, errs) End Sub <Fact> Public Sub TestInvalidBinaryIfOperatorsStrictOn() TestInvalidBinaryIfOperatorsStrict(OptionStrict.On, <expected><![CDATA[ BC36913: Cannot infer a common type because more than one type is possible. Dim F1 As Object = If("", 23) ~~~~~~~~~~ BC36913: Cannot infer a common type because more than one type is possible. Dim F2 As Object = If(23, "") ~~~~~~~~~~ BC30491: Expression does not produce a value. Dim F3 As Object = If(S1(), (Nothing)) ~~~~ BC36911: Cannot infer a common type. Dim F6 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36911: Cannot infer a common type. Dim F7 As Func(Of Integer, Integer) = If(AddressOf FUNK1, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36911: Cannot infer a common type. Dim F8 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. Dim F9 As Object = If(G.P1, G.F2) ~~~~~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F9_ As Object = If(G.P1, Nothing) ~~~~ BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. Dim F10 As Object = If(G.F2, G.P3) ~~~~~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F12 As Object = If(G.F4, G.P3) ~~~~ BC36912: Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed. Dim v1 As T1 = If(x1, x2) ~~~~~~~~~~ ]]> </expected>) End Sub <Fact> Public Sub TestInvalidBinaryIfOperatorsStrictCustom() TestInvalidBinaryIfOperatorsStrict(OptionStrict.Custom, <expected><![CDATA[ BC42021: Cannot infer a common type because more than one type is possible; 'Object' assumed. Dim F1 As Object = If("", 23) ~~~~~~~~~~ BC42021: Cannot infer a common type because more than one type is possible; 'Object' assumed. Dim F2 As Object = If(23, "") ~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F2 As Object = If(23, "") ~~ BC30491: Expression does not produce a value. Dim F3 As Object = If(S1(), (Nothing)) ~~~~ BC36911: Cannot infer a common type. Dim F6 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36911: Cannot infer a common type. Dim F7 As Func(Of Integer, Integer) = If(AddressOf FUNK1, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36911: Cannot infer a common type. Dim F8 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC42021: Cannot infer a common type; 'Object' assumed. Dim F9 As Object = If(G.P1, G.F2) ~~~~~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F9 As Object = If(G.P1, G.F2) ~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F9_ As Object = If(G.P1, Nothing) ~~~~ BC42021: Cannot infer a common type; 'Object' assumed. Dim F10 As Object = If(G.F2, G.P3) ~~~~~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F10 As Object = If(G.F2, G.P3) ~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F12 As Object = If(G.F4, G.P3) ~~~~ BC42016: Implicit conversion from 'Object' to 'T1'. Dim v1 As T1 = If(x1, x2) ~~~~~~~~~~ BC42021: Cannot infer a common type; 'Object' assumed. Dim v1 As T1 = If(x1, x2) ~~~~~~~~~~ ]]> </expected>) End Sub '<Fact(skip:="Temp variables in property/field initializers are not supported")> <Fact> Public Sub TestInvalidBinaryIfOperatorsStrictOff() TestInvalidBinaryIfOperatorsStrict(OptionStrict.Off, <expected><![CDATA[ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F2 As Object = If(23, "") ~~ BC30491: Expression does not produce a value. Dim F3 As Object = If(S1(), (Nothing)) ~~~~ BC36911: Cannot infer a common type. Dim F6 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36911: Cannot infer a common type. Dim F7 As Func(Of Integer, Integer) = If(AddressOf FUNK1, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36911: Cannot infer a common type. Dim F8 As Func(Of Integer, Integer) = If(Nothing, AddressOf FUNK2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F9 As Object = If(G.P1, G.F2) ~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F9_ As Object = If(G.P1, Nothing) ~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F10 As Object = If(G.F2, G.P3) ~~~~ BC33107: First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type. Dim F12 As Object = If(G.F4, G.P3) ~~~~ ]]> </expected>) End Sub <Fact, WorkItem(544983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544983")> Public Sub Bug13187() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Option Strict On Imports System Module Module1 Structure S End Structure Function Full() As S System.Console.WriteLine("Full") Return New S() End Function Function M(o As S?) As Integer Dim i = If(o, Full()) Return 1 End Function Sub Main() M(New S()) System.Console.WriteLine("----") Dim x = If(New S?(Nothing), New S()) System.Console.WriteLine("----") M(Nothing) End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseExe) Dim verifier = CompileAndVerify(comp, expectedOutput:= <![CDATA[ ---- ---- Full ]]>) End Sub <Fact, WorkItem(544983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544983")> Public Sub Bug13187_2() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main(args As String()) Test1() Test2() Test3() Test4() End Sub Function GetX() As Integer? Return 1 End Function Function GetY() As Integer? System.Console.WriteLine("GetY") Return Nothing End Function Function GetZ() As Long? System.Console.WriteLine("GetZ") Return Nothing End Function Sub Test1() System.Console.WriteLine(If(GetX, GetY)) End Sub Sub Test2() System.Console.WriteLine(If(GetX, GetZ)) End Sub Sub Test3() Dim x as Integer = 4 Dim z= If(New Integer?(x), GetY) System.Console.WriteLine(z) End Sub Sub Test4() Dim x as Integer = 5 Dim z = If(New Integer?(x), GetZ) System.Console.WriteLine(z) End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseExe) Dim verifier = CompileAndVerify(comp, expectedOutput:= <![CDATA[ 1 1 4 5 ]]>) verifier.VerifyIL("Module1.Test1", <![CDATA[ { // Code size 36 (0x24) .maxstack 2 .locals init (Integer? V_0, Integer? V_1) IL_0000: call "Function Module1.GetX() As Integer?" IL_0005: dup IL_0006: stloc.0 IL_0007: stloc.1 IL_0008: ldloca.s V_1 IL_000a: call "Function Integer?.get_HasValue() As Boolean" IL_000f: brtrue.s IL_0018 IL_0011: call "Function Module1.GetY() As Integer?" IL_0016: br.s IL_0019 IL_0018: ldloc.0 IL_0019: box "Integer?" IL_001e: call "Sub System.Console.WriteLine(Object)" IL_0023: ret } ]]>) verifier.VerifyIL("Module1.Test2", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 .locals init (Integer? V_0, Integer? V_1) IL_0000: call "Function Module1.GetX() As Integer?" IL_0005: dup IL_0006: stloc.0 IL_0007: stloc.1 IL_0008: ldloca.s V_1 IL_000a: call "Function Integer?.get_HasValue() As Boolean" IL_000f: brtrue.s IL_0018 IL_0011: call "Function Module1.GetZ() As Long?" IL_0016: br.s IL_0025 IL_0018: ldloca.s V_0 IL_001a: call "Function Integer?.GetValueOrDefault() As Integer" IL_001f: conv.i8 IL_0020: newobj "Sub Long?..ctor(Long)" IL_0025: box "Long?" IL_002a: call "Sub System.Console.WriteLine(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Module1.Test3", <![CDATA[ { // Code size 19 (0x13) .maxstack 1 .locals init (Integer V_0) //x IL_0000: ldc.i4.4 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: newobj "Sub Integer?..ctor(Integer)" IL_0008: box "Integer?" IL_000d: call "Sub System.Console.WriteLine(Object)" IL_0012: ret } ]]>) verifier.VerifyIL("Module1.Test4", <![CDATA[ { // Code size 20 (0x14) .maxstack 1 .locals init (Integer V_0) //x IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: conv.i8 IL_0004: newobj "Sub Long?..ctor(Long)" IL_0009: box "Long?" IL_000e: call "Sub System.Console.WriteLine(Object)" IL_0013: ret } ]]>) End Sub End Class End Namespace
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/CoreTest/UtilityTest/SerializableBytesTests.cs
// 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. #nullable disable using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class SerializableBytesTests { [Fact] public async Task ReadableStreamTestReadAByteAtATime() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = await SerializableBytes.CreateReadableStreamAsync(expected, CancellationToken.None); Assert.Equal(expected.Length, stream.Length); expected.Position = 0; stream.Position = 0; for (var i = 0; i < expected.Length; i++) { Assert.Equal(expected.ReadByte(), stream.ReadByte()); } } [Fact] public async Task ReadableStreamTestReadChunks() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = await SerializableBytes.CreateReadableStreamAsync(expected, CancellationToken.None); Assert.Equal(expected.Length, stream.Length); stream.Position = 0; var index = 0; int count; var bytes = new byte[1000]; while ((count = stream.Read(bytes, 0, bytes.Length)) > 0) { for (var i = 0; i < count; i++) { Assert.Equal((byte)(index % byte.MaxValue), bytes[i]); index++; } } Assert.Equal(index, stream.Length); } [Fact] public async Task ReadableStreamTestReadRandomBytes() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = await SerializableBytes.CreateReadableStreamAsync(expected, CancellationToken.None); Assert.Equal(expected.Length, stream.Length); var random = new Random(0); for (var i = 0; i < 100; i++) { var position = random.Next((int)expected.Length); expected.Position = position; stream.Position = position; Assert.Equal(expected.ReadByte(), stream.ReadByte()); } } [Fact] public void WritableStreamTest1() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = SerializableBytes.CreateWritableStream(); for (var i = 0; i < 10000; i++) { stream.WriteByte((byte)(i % byte.MaxValue)); } StreamEqual(expected, stream); } [Fact] public void WritableStreamTest2() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = SerializableBytes.CreateWritableStream(); for (var i = 0; i < 10000; i++) { stream.WriteByte((byte)(i % byte.MaxValue)); } Assert.Equal(expected.Length, stream.Length); stream.Position = 0; var index = 0; int count; var bytes = new byte[1000]; while ((count = stream.Read(bytes, 0, bytes.Length)) > 0) { for (var i = 0; i < count; i++) { Assert.Equal((byte)(index % byte.MaxValue), bytes[i]); index++; } } Assert.Equal(index, stream.Length); } [Fact] public void WritableStreamTest3() { using var expected = new MemoryStream(); using var stream = SerializableBytes.CreateWritableStream(); var random = new Random(0); for (var i = 0; i < 100; i++) { var position = random.Next(10000); WriteByte(expected, stream, position, i); } StreamEqual(expected, stream); } [Fact] public void WritableStreamTest4() { using var expected = new MemoryStream(); using var stream = SerializableBytes.CreateWritableStream(); var random = new Random(0); for (var i = 0; i < 100; i++) { var position = random.Next(10000); WriteByte(expected, stream, position, i); var position1 = random.Next(10000); var temp = GetInitializedArray(100 + position1); Write(expected, stream, position1, temp); } StreamEqual(expected, stream); } [Fact] public void WritableStream_SetLength1() { using (var expected = new MemoryStream()) { expected.WriteByte(1); expected.SetLength(10000); expected.WriteByte(2); expected.SetLength(1); var expectedPosition = expected.Position; expected.Position = 0; using (var stream = SerializableBytes.CreateWritableStream()) { stream.WriteByte(1); stream.SetLength(10000); stream.WriteByte(2); stream.SetLength(1); StreamEqual(expected, stream); Assert.Equal(expectedPosition, stream.Position); } } } [Fact] public void WritableStream_SetLength2() { using (var expected = new MemoryStream()) { expected.WriteByte(1); expected.SetLength(10000); expected.Position = 10000 - 1; expected.WriteByte(2); expected.SetLength(SharedPools.ByteBufferSize); expected.WriteByte(3); var expectedPosition = expected.Position; expected.Position = 0; using (var stream = SerializableBytes.CreateWritableStream()) { stream.WriteByte(1); stream.SetLength(10000); stream.Position = 10000 - 1; stream.WriteByte(2); stream.SetLength(SharedPools.ByteBufferSize); stream.WriteByte(3); StreamEqual(expected, stream); Assert.Equal(expectedPosition, stream.Position); } } } private static void WriteByte(Stream expected, Stream stream, int position, int value) { expected.Position = position; stream.Position = position; var valueByte = (byte)(value % byte.MaxValue); expected.WriteByte(valueByte); stream.WriteByte(valueByte); } private static void Write(Stream expected, Stream stream, int position, byte[] array) { expected.Position = position; stream.Position = position; expected.Write(array, 0, array.Length); stream.Write(array, 0, array.Length); } private static byte[] GetInitializedArray(int length) { var temp = new byte[length]; for (var j = 0; j < temp.Length; j++) { temp[j] = (byte)(j % byte.MaxValue); } return temp; } private static void StreamEqual(Stream expected, Stream stream) { Assert.Equal(expected.Length, stream.Length); var random = new Random(0); expected.Position = 0; stream.Position = 0; var read1 = new byte[10000]; var read2 = new byte[10000]; while (expected.Position < expected.Length) { var count = random.Next(read1.Length) + 1; var return1 = expected.Read(read1, 0, count); var return2 = stream.Read(read2, 0, count); Assert.Equal(return1, return2); for (var i = 0; i < return1; i++) { Assert.Equal(read1[i], read2[i]); } Assert.Equal(expected.ReadByte(), stream.ReadByte()); } } } }
// 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. #nullable disable using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class SerializableBytesTests { [Fact] public async Task ReadableStreamTestReadAByteAtATime() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = await SerializableBytes.CreateReadableStreamAsync(expected, CancellationToken.None); Assert.Equal(expected.Length, stream.Length); expected.Position = 0; stream.Position = 0; for (var i = 0; i < expected.Length; i++) { Assert.Equal(expected.ReadByte(), stream.ReadByte()); } } [Fact] public async Task ReadableStreamTestReadChunks() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = await SerializableBytes.CreateReadableStreamAsync(expected, CancellationToken.None); Assert.Equal(expected.Length, stream.Length); stream.Position = 0; var index = 0; int count; var bytes = new byte[1000]; while ((count = stream.Read(bytes, 0, bytes.Length)) > 0) { for (var i = 0; i < count; i++) { Assert.Equal((byte)(index % byte.MaxValue), bytes[i]); index++; } } Assert.Equal(index, stream.Length); } [Fact] public async Task ReadableStreamTestReadRandomBytes() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = await SerializableBytes.CreateReadableStreamAsync(expected, CancellationToken.None); Assert.Equal(expected.Length, stream.Length); var random = new Random(0); for (var i = 0; i < 100; i++) { var position = random.Next((int)expected.Length); expected.Position = position; stream.Position = position; Assert.Equal(expected.ReadByte(), stream.ReadByte()); } } [Fact] public void WritableStreamTest1() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = SerializableBytes.CreateWritableStream(); for (var i = 0; i < 10000; i++) { stream.WriteByte((byte)(i % byte.MaxValue)); } StreamEqual(expected, stream); } [Fact] public void WritableStreamTest2() { using var expected = new MemoryStream(); for (var i = 0; i < 10000; i++) { expected.WriteByte((byte)(i % byte.MaxValue)); } expected.Position = 0; using var stream = SerializableBytes.CreateWritableStream(); for (var i = 0; i < 10000; i++) { stream.WriteByte((byte)(i % byte.MaxValue)); } Assert.Equal(expected.Length, stream.Length); stream.Position = 0; var index = 0; int count; var bytes = new byte[1000]; while ((count = stream.Read(bytes, 0, bytes.Length)) > 0) { for (var i = 0; i < count; i++) { Assert.Equal((byte)(index % byte.MaxValue), bytes[i]); index++; } } Assert.Equal(index, stream.Length); } [Fact] public void WritableStreamTest3() { using var expected = new MemoryStream(); using var stream = SerializableBytes.CreateWritableStream(); var random = new Random(0); for (var i = 0; i < 100; i++) { var position = random.Next(10000); WriteByte(expected, stream, position, i); } StreamEqual(expected, stream); } [Fact] public void WritableStreamTest4() { using var expected = new MemoryStream(); using var stream = SerializableBytes.CreateWritableStream(); var random = new Random(0); for (var i = 0; i < 100; i++) { var position = random.Next(10000); WriteByte(expected, stream, position, i); var position1 = random.Next(10000); var temp = GetInitializedArray(100 + position1); Write(expected, stream, position1, temp); } StreamEqual(expected, stream); } [Fact] public void WritableStream_SetLength1() { using (var expected = new MemoryStream()) { expected.WriteByte(1); expected.SetLength(10000); expected.WriteByte(2); expected.SetLength(1); var expectedPosition = expected.Position; expected.Position = 0; using (var stream = SerializableBytes.CreateWritableStream()) { stream.WriteByte(1); stream.SetLength(10000); stream.WriteByte(2); stream.SetLength(1); StreamEqual(expected, stream); Assert.Equal(expectedPosition, stream.Position); } } } [Fact] public void WritableStream_SetLength2() { using (var expected = new MemoryStream()) { expected.WriteByte(1); expected.SetLength(10000); expected.Position = 10000 - 1; expected.WriteByte(2); expected.SetLength(SharedPools.ByteBufferSize); expected.WriteByte(3); var expectedPosition = expected.Position; expected.Position = 0; using (var stream = SerializableBytes.CreateWritableStream()) { stream.WriteByte(1); stream.SetLength(10000); stream.Position = 10000 - 1; stream.WriteByte(2); stream.SetLength(SharedPools.ByteBufferSize); stream.WriteByte(3); StreamEqual(expected, stream); Assert.Equal(expectedPosition, stream.Position); } } } private static void WriteByte(Stream expected, Stream stream, int position, int value) { expected.Position = position; stream.Position = position; var valueByte = (byte)(value % byte.MaxValue); expected.WriteByte(valueByte); stream.WriteByte(valueByte); } private static void Write(Stream expected, Stream stream, int position, byte[] array) { expected.Position = position; stream.Position = position; expected.Write(array, 0, array.Length); stream.Write(array, 0, array.Length); } private static byte[] GetInitializedArray(int length) { var temp = new byte[length]; for (var j = 0; j < temp.Length; j++) { temp[j] = (byte)(j % byte.MaxValue); } return temp; } private static void StreamEqual(Stream expected, Stream stream) { Assert.Equal(expected.Length, stream.Length); var random = new Random(0); expected.Position = 0; stream.Position = 0; var read1 = new byte[10000]; var read2 = new byte[10000]; while (expected.Position < expected.Length) { var count = random.Next(read1.Length) + 1; var return1 = expected.Read(read1, 0, count); var return2 = stream.Read(read2, 0, count); Assert.Equal(return1, return2); for (var i = 0; i < return1; i++) { Assert.Equal(read1[i], read2[i]); } Assert.Equal(expected.ReadByte(), stream.ReadByte()); } } } }
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./docs/wiki/Getting-Started-on-Visual-Studio-2015-CTP-6.md
1. Set up a box with Visual Studio 2015 CTP 6. Either [install Visual Studio 2015 CTP 6](https://www.visualstudio.com/en-us/downloads/visual-studio-2015-ctp-vs), or grab a [prebuilt Azure VM image](http://blogs.msdn.com/b/visualstudioalm/archive/2014/06/04/visual-studio-14-ctp-now-available-in-the-virtual-machine-azure-gallery.aspx). 2. Install the [Visual Studio 2015 CTP 6 SDK](http://go.microsoft.com/?linkid=9875738). You'll need to do this even if you're using the Azure VM image. 3. Install the [SDK Templates VSIX package](https://visualstudiogallery.msdn.microsoft.com/ecefb773-36a6-4316-98db-4a87ed8cf5dc) to get the Visual Studio project templates. 4. Install the [Syntax Visualizer VSIX package](https://visualstudiogallery.msdn.microsoft.com/0f18f8c3-ec79-468a-968f-a1a0ee65b388) to get a [Syntax Visualizer tool window](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Syntax-Visualizer.md) to help explore the syntax trees you'll be analyzing.
1. Set up a box with Visual Studio 2015 CTP 6. Either [install Visual Studio 2015 CTP 6](https://www.visualstudio.com/en-us/downloads/visual-studio-2015-ctp-vs), or grab a [prebuilt Azure VM image](http://blogs.msdn.com/b/visualstudioalm/archive/2014/06/04/visual-studio-14-ctp-now-available-in-the-virtual-machine-azure-gallery.aspx). 2. Install the [Visual Studio 2015 CTP 6 SDK](http://go.microsoft.com/?linkid=9875738). You'll need to do this even if you're using the Azure VM image. 3. Install the [SDK Templates VSIX package](https://visualstudiogallery.msdn.microsoft.com/ecefb773-36a6-4316-98db-4a87ed8cf5dc) to get the Visual Studio project templates. 4. Install the [Syntax Visualizer VSIX package](https://visualstudiogallery.msdn.microsoft.com/0f18f8c3-ec79-468a-968f-a1a0ee65b388) to get a [Syntax Visualizer tool window](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Syntax-Visualizer.md) to help explore the syntax trees you'll be analyzing.
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/Core/Implementation/ExtractInterface/AbstractExtractInterfaceCommandHandler.cs
// 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. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExtractInterface; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.ExtractInterface { internal abstract class AbstractExtractInterfaceCommandHandler : ICommandHandler<ExtractInterfaceCommandArgs> { private readonly IThreadingContext _threadingContext; protected AbstractExtractInterfaceCommandHandler(IThreadingContext threadingContext) => _threadingContext = threadingContext; public string DisplayName => EditorFeaturesResources.Extract_Interface; public CommandState GetCommandState(ExtractInterfaceCommandArgs args) => IsAvailable(args.SubjectBuffer, out _) ? CommandState.Available : CommandState.Unspecified; public bool ExecuteCommand(ExtractInterfaceCommandArgs args, CommandExecutionContext context) { using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Extract_Interface)) { var subjectBuffer = args.SubjectBuffer; if (!IsAvailable(subjectBuffer, out var workspace)) { return false; } var caretPoint = args.TextView.GetCaretPoint(subjectBuffer); if (!caretPoint.HasValue) { return false; } var document = subjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( context.OperationContext, _threadingContext); if (document == null) { return false; } // We are about to show a modal UI dialog so we should take over the command execution // wait context. That means the command system won't attempt to show its own wait dialog // and also will take it into consideration when measuring command handling duration. context.OperationContext.TakeOwnership(); var extractInterfaceService = document.GetLanguageService<AbstractExtractInterfaceService>(); var result = _threadingContext.JoinableTaskFactory.Run(() => extractInterfaceService.ExtractInterfaceAsync( document, caretPoint.Value.Position, (errorMessage, severity) => workspace.Services.GetService<INotificationService>().SendNotification(errorMessage, severity: severity), CancellationToken.None)); if (result == null || !result.Succeeded) { return true; } if (!document.Project.Solution.Workspace.TryApplyChanges(result.UpdatedSolution)) { // TODO: handle failure return true; } // TODO: Use a threaded-wait-dialog here so we can cancel navigation. var navigationService = workspace.Services.GetService<IDocumentNavigationService>(); navigationService.TryNavigateToPosition(workspace, result.NavigationDocumentId, 0, CancellationToken.None); return true; } } private static bool IsAvailable(ITextBuffer subjectBuffer, out Workspace workspace) => subjectBuffer.TryGetWorkspace(out workspace) && workspace.CanApplyChange(ApplyChangesKind.AddDocument) && workspace.CanApplyChange(ApplyChangesKind.ChangeDocument) && subjectBuffer.SupportsRefactorings(); } }
// 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. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExtractInterface; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.ExtractInterface { internal abstract class AbstractExtractInterfaceCommandHandler : ICommandHandler<ExtractInterfaceCommandArgs> { private readonly IThreadingContext _threadingContext; protected AbstractExtractInterfaceCommandHandler(IThreadingContext threadingContext) => _threadingContext = threadingContext; public string DisplayName => EditorFeaturesResources.Extract_Interface; public CommandState GetCommandState(ExtractInterfaceCommandArgs args) => IsAvailable(args.SubjectBuffer, out _) ? CommandState.Available : CommandState.Unspecified; public bool ExecuteCommand(ExtractInterfaceCommandArgs args, CommandExecutionContext context) { using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Extract_Interface)) { var subjectBuffer = args.SubjectBuffer; if (!IsAvailable(subjectBuffer, out var workspace)) { return false; } var caretPoint = args.TextView.GetCaretPoint(subjectBuffer); if (!caretPoint.HasValue) { return false; } var document = subjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( context.OperationContext, _threadingContext); if (document == null) { return false; } // We are about to show a modal UI dialog so we should take over the command execution // wait context. That means the command system won't attempt to show its own wait dialog // and also will take it into consideration when measuring command handling duration. context.OperationContext.TakeOwnership(); var extractInterfaceService = document.GetLanguageService<AbstractExtractInterfaceService>(); var result = _threadingContext.JoinableTaskFactory.Run(() => extractInterfaceService.ExtractInterfaceAsync( document, caretPoint.Value.Position, (errorMessage, severity) => workspace.Services.GetService<INotificationService>().SendNotification(errorMessage, severity: severity), CancellationToken.None)); if (result == null || !result.Succeeded) { return true; } if (!document.Project.Solution.Workspace.TryApplyChanges(result.UpdatedSolution)) { // TODO: handle failure return true; } // TODO: Use a threaded-wait-dialog here so we can cancel navigation. var navigationService = workspace.Services.GetService<IDocumentNavigationService>(); navigationService.TryNavigateToPosition(workspace, result.NavigationDocumentId, 0, CancellationToken.None); return true; } } private static bool IsAvailable(ITextBuffer subjectBuffer, out Workspace workspace) => subjectBuffer.TryGetWorkspace(out workspace) && workspace.CanApplyChange(ApplyChangesKind.AddDocument) && workspace.CanApplyChange(ApplyChangesKind.ChangeDocument) && subjectBuffer.SupportsRefactorings(); } }
-1
dotnet/roslyn
55,225
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-07-29T12:13:58Z
2021-07-29T13:29:44Z
8f8f95ed398d61b67cb4d9a5c9e9500318d2dea3
58ffdbfea841d0a04ae1540325fea4861356c76c
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210728.2 - **Date Produced**: 7/28/2021 2:47 PM - **Commit**: dd3652e2ae5ea89703a2286295de9efe908974f1 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21377.2 to 6.0.0-beta.21378.2][1] [1]: https://github.com/dotnet/arcade/compare/cab4a3c...dd3652e [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpCodeGenerationServiceFactory.cs
// 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. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { [ExportLanguageServiceFactory(typeof(ICodeGenerationService), LanguageNames.CSharp), Shared] internal partial class CSharpCodeGenerationServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCodeGenerationServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices provider) => new CSharpCodeGenerationService(provider); } }
// 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. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { [ExportLanguageServiceFactory(typeof(ICodeGenerationService), LanguageNames.CSharp), Shared] internal partial class CSharpCodeGenerationServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCodeGenerationServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices provider) => new CSharpCodeGenerationService(provider); } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Portable/Emitter/EditAndContinue/CSharpSymbolMatcher.cs
// 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 Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Symbols; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class CSharpSymbolMatcher : SymbolMatcher { private readonly MatchDefs _defs; private readonly MatchSymbols _symbols; public CSharpSymbolMatcher( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, SourceAssemblySymbol otherAssembly, EmitContext otherContext, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> otherSynthesizedMembersOpt) { _defs = new MatchDefsToSource(sourceContext, otherContext); _symbols = new MatchSymbols(anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt, new DeepTranslator(otherAssembly.GetSpecialType(SpecialType.System_Object))); } public CSharpSymbolMatcher( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, PEAssemblySymbol otherAssembly) { _defs = new MatchDefsToMetadata(sourceContext, otherAssembly); _symbols = new MatchSymbols( anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembers: null, deepTranslator: null); } public override Cci.IDefinition? MapDefinition(Cci.IDefinition definition) { if (definition.GetInternalSymbol() is Symbol symbol) { return (Cci.IDefinition?)_symbols.Visit(symbol)?.GetCciAdapter(); } // TODO: this appears to be dead code, remove (https://github.com/dotnet/roslyn/issues/51595) return _defs.VisitDef(definition); } public override Cci.INamespace? MapNamespace(Cci.INamespace @namespace) { if (@namespace.GetInternalSymbol() is NamespaceSymbol symbol) { return (Cci.INamespace?)_symbols.Visit(symbol)?.GetCciAdapter(); } return null; } public override Cci.ITypeReference? MapReference(Cci.ITypeReference reference) { if (reference.GetInternalSymbol() is Symbol symbol) { return (Cci.ITypeReference?)_symbols.Visit(symbol)?.GetCciAdapter(); } return null; } internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, [NotNullWhen(true)] out string? name, out int index) => _symbols.TryGetAnonymousTypeName(template, out name, out index); private abstract class MatchDefs { private readonly EmitContext _sourceContext; private readonly ConcurrentDictionary<Cci.IDefinition, Cci.IDefinition?> _matches = new(ReferenceEqualityComparer.Instance); private IReadOnlyDictionary<string, Cci.INamespaceTypeDefinition>? _lazyTopLevelTypes; public MatchDefs(EmitContext sourceContext) { _sourceContext = sourceContext; } public Cci.IDefinition? VisitDef(Cci.IDefinition def) => _matches.GetOrAdd(def, VisitDefInternal); private Cci.IDefinition? VisitDefInternal(Cci.IDefinition def) { if (def is Cci.ITypeDefinition type) { var namespaceType = type.AsNamespaceTypeDefinition(_sourceContext); if (namespaceType != null) { return VisitNamespaceType(namespaceType); } var nestedType = type.AsNestedTypeDefinition(_sourceContext); Debug.Assert(nestedType != null); var otherContainer = (Cci.ITypeDefinition?)VisitDef(nestedType.ContainingTypeDefinition); if (otherContainer == null) { return null; } return VisitTypeMembers(otherContainer, nestedType, GetNestedTypes, (a, b) => StringOrdinalComparer.Equals(a.Name, b.Name)); } if (def is Cci.ITypeDefinitionMember member) { var otherContainer = (Cci.ITypeDefinition?)VisitDef(member.ContainingTypeDefinition); if (otherContainer == null) { return null; } if (def is Cci.IFieldDefinition field) { return VisitTypeMembers(otherContainer, field, GetFields, (a, b) => StringOrdinalComparer.Equals(a.Name, b.Name)); } } // We are only expecting types and fields currently. throw ExceptionUtilities.UnexpectedValue(def); } protected abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes(); protected abstract IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def); protected abstract IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def); private Cci.INamespaceTypeDefinition? VisitNamespaceType(Cci.INamespaceTypeDefinition def) { // All generated top-level types are assumed to be in the global namespace. // However, this may be an embedded NoPIA type within a namespace. // Since we do not support edits that include references to NoPIA types // (see #855640), it's reasonable to simply drop such cases. if (!string.IsNullOrEmpty(def.NamespaceName)) { return null; } RoslynDebug.AssertNotNull(def.Name); var topLevelTypes = GetTopLevelTypesByName(); topLevelTypes.TryGetValue(def.Name, out var otherDef); return otherDef; } private IReadOnlyDictionary<string, Cci.INamespaceTypeDefinition> GetTopLevelTypesByName() { if (_lazyTopLevelTypes == null) { var typesByName = new Dictionary<string, Cci.INamespaceTypeDefinition>(StringOrdinalComparer.Instance); foreach (var type in GetTopLevelTypes()) { // All generated top-level types are assumed to be in the global namespace. if (string.IsNullOrEmpty(type.NamespaceName)) { RoslynDebug.AssertNotNull(type.Name); typesByName.Add(type.Name, type); } } Interlocked.CompareExchange(ref _lazyTopLevelTypes, typesByName, null); } return _lazyTopLevelTypes; } private static T VisitTypeMembers<T>( Cci.ITypeDefinition otherContainer, T member, Func<Cci.ITypeDefinition, IEnumerable<T>> getMembers, Func<T, T, bool> predicate) where T : class, Cci.ITypeDefinitionMember { // We could cache the members by name (see Matcher.VisitNamedTypeMembers) // but the assumption is this class is only used for types with few members // so caching is not necessary and linear search is acceptable. return getMembers(otherContainer).FirstOrDefault(otherMember => predicate(member, otherMember)); } } private sealed class MatchDefsToMetadata : MatchDefs { private readonly PEAssemblySymbol _otherAssembly; public MatchDefsToMetadata(EmitContext sourceContext, PEAssemblySymbol otherAssembly) : base(sourceContext) { _otherAssembly = otherAssembly; } protected override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes() { var builder = ArrayBuilder<Cci.INamespaceTypeDefinition>.GetInstance(); GetTopLevelTypes(builder, _otherAssembly.GlobalNamespace); return builder.ToArrayAndFree(); } protected override IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def) { var type = (PENamedTypeSymbol)def; return type.GetTypeMembers().Cast<Cci.INestedTypeDefinition>(); } protected override IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def) { var type = (PENamedTypeSymbol)def; return type.GetFieldsToEmit().Cast<Cci.IFieldDefinition>(); } private static void GetTopLevelTypes(ArrayBuilder<Cci.INamespaceTypeDefinition> builder, NamespaceSymbol @namespace) { foreach (var member in @namespace.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { GetTopLevelTypes(builder, (NamespaceSymbol)member); } else { builder.Add((Cci.INamespaceTypeDefinition)member.GetCciAdapter()); } } } } private sealed class MatchDefsToSource : MatchDefs { private readonly EmitContext _otherContext; public MatchDefsToSource( EmitContext sourceContext, EmitContext otherContext) : base(sourceContext) { _otherContext = otherContext; } protected override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes() { return _otherContext.Module.GetTopLevelTypeDefinitions(_otherContext); } protected override IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def) { return def.GetNestedTypes(_otherContext); } protected override IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def) { return def.GetFields(_otherContext); } } private sealed class MatchSymbols : CSharpSymbolVisitor<Symbol?> { private readonly IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> _anonymousTypeMap; private readonly SourceAssemblySymbol _sourceAssembly; // metadata or source assembly: private readonly AssemblySymbol _otherAssembly; /// <summary> /// Members that are not listed directly on their containing type or namespace symbol as they were synthesized in a lowering phase, /// after the symbol has been created. /// </summary> private readonly ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>? _otherSynthesizedMembers; private readonly SymbolComparer _comparer; private readonly ConcurrentDictionary<Symbol, Symbol?> _matches = new(ReferenceEqualityComparer.Instance); /// <summary> /// A cache of members per type, populated when the first member for a given /// type is needed. Within each type, members are indexed by name. The reason /// for caching, and indexing by name, is to avoid searching sequentially /// through all members of a given kind each time a member is matched. /// </summary> private readonly ConcurrentDictionary<ISymbolInternal, IReadOnlyDictionary<string, ImmutableArray<ISymbolInternal>>> _otherMembers = new(ReferenceEqualityComparer.Instance); public MatchSymbols( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, AssemblySymbol otherAssembly, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>? otherSynthesizedMembers, DeepTranslator? deepTranslator) { _anonymousTypeMap = anonymousTypeMap; _sourceAssembly = sourceAssembly; _otherAssembly = otherAssembly; _otherSynthesizedMembers = otherSynthesizedMembers; _comparer = new SymbolComparer(this, deepTranslator); } internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, [NotNullWhen(true)] out string? name, out int index) { if (TryFindAnonymousType(type, out var otherType)) { name = otherType.Name; index = otherType.UniqueIndex; return true; } name = null; index = -1; return false; } public override Symbol DefaultVisit(Symbol symbol) { // Symbol should have been handled elsewhere. throw ExceptionUtilities.Unreachable; } public override Symbol? Visit(Symbol symbol) { Debug.Assert((object)symbol.ContainingAssembly != (object)_otherAssembly); // Add an entry for the match, even if there is no match, to avoid // matching the same symbol unsuccessfully multiple times. return _matches.GetOrAdd(symbol, base.Visit); } public override Symbol? VisitArrayType(ArrayTypeSymbol symbol) { var otherElementType = (TypeSymbol?)Visit(symbol.ElementType); if (otherElementType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } var otherModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); if (symbol.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(otherElementType, otherModifiers)); } return ArrayTypeSymbol.CreateMDArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(otherElementType, otherModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); } public override Symbol? VisitEvent(EventSymbol symbol) => VisitNamedTypeMember(symbol, AreEventsEqual); public override Symbol? VisitField(FieldSymbol symbol) => VisitNamedTypeMember(symbol, AreFieldsEqual); public override Symbol? VisitMethod(MethodSymbol symbol) { // Not expecting constructed method. Debug.Assert(symbol.IsDefinition); return VisitNamedTypeMember(symbol, AreMethodsEqual); } public override Symbol? VisitModule(ModuleSymbol module) { var otherAssembly = (AssemblySymbol?)Visit(module.ContainingAssembly); if (otherAssembly is null) { return null; } // manifest module: if (module.Ordinal == 0) { return otherAssembly.Modules[0]; } // match non-manifest module by name: for (int i = 1; i < otherAssembly.Modules.Length; i++) { var otherModule = otherAssembly.Modules[i]; // use case sensitive comparison -- modules whose names differ in casing are considered distinct: if (StringComparer.Ordinal.Equals(otherModule.Name, module.Name)) { return otherModule; } } return null; } public override Symbol? VisitAssembly(AssemblySymbol assembly) { if (assembly.IsLinked) { return assembly; } // When we map synthesized symbols from previous generations to the latest compilation // we might encounter a symbol that is defined in arbitrary preceding generation, // not just the immediately preceding generation. If the source assembly uses time-based // versioning assemblies of preceding generations might differ in their version number. if (IdentityEqualIgnoringVersionWildcard(assembly, _sourceAssembly)) { return _otherAssembly; } // find a referenced assembly with the same source identity (modulo assembly version patterns): foreach (var otherReferencedAssembly in _otherAssembly.Modules[0].ReferencedAssemblySymbols) { if (IdentityEqualIgnoringVersionWildcard(assembly, otherReferencedAssembly)) { return otherReferencedAssembly; } } return null; } private static bool IdentityEqualIgnoringVersionWildcard(AssemblySymbol left, AssemblySymbol right) { var leftIdentity = left.Identity; var rightIdentity = right.Identity; return AssemblyIdentityComparer.SimpleNameComparer.Equals(leftIdentity.Name, rightIdentity.Name) && (left.AssemblyVersionPattern ?? leftIdentity.Version).Equals(right.AssemblyVersionPattern ?? rightIdentity.Version) && AssemblyIdentity.EqualIgnoringNameAndVersion(leftIdentity, rightIdentity); } public override Symbol? VisitNamespace(NamespaceSymbol @namespace) { var otherContainer = Visit(@namespace.ContainingSymbol); // Containing namespace will be missing from other assembly // if its was added in the (newer) source assembly. if (otherContainer is null) { return null; } switch (otherContainer.Kind) { case SymbolKind.NetModule: Debug.Assert(@namespace.IsGlobalNamespace); return ((ModuleSymbol)otherContainer).GlobalNamespace; case SymbolKind.Namespace: return FindMatchingMember(otherContainer, @namespace, AreNamespacesEqual); default: throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind); } } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) { return _otherAssembly.GetSpecialType(SpecialType.System_Object); } public override Symbol? VisitNamedType(NamedTypeSymbol sourceType) { var originalDef = sourceType.OriginalDefinition; if ((object)originalDef != (object)sourceType) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var typeArguments = sourceType.GetAllTypeArguments(ref discardedUseSiteInfo); var otherDef = (NamedTypeSymbol?)Visit(originalDef); if (otherDef is null) { return null; } var otherTypeParameters = otherDef.GetAllTypeParameters(); bool translationFailed = false; var otherTypeArguments = typeArguments.SelectAsArray((t, v) => { var newType = (TypeSymbol?)v.Visit(t.Type); if (newType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. translationFailed = true; newType = t.Type; } return t.WithTypeAndModifiers(newType, v.VisitCustomModifiers(t.CustomModifiers)); }, this); if (translationFailed) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } // TODO: LambdaFrame has alpha renamed type parameters, should we rather fix that? var typeMap = new TypeMap(otherTypeParameters, otherTypeArguments, allowAlpha: true); return typeMap.SubstituteNamedType(otherDef); } Debug.Assert(sourceType.IsDefinition); var otherContainer = this.Visit(sourceType.ContainingSymbol); // Containing type will be missing from other assembly // if the type was added in the (newer) source assembly. if (otherContainer is null) { return null; } switch (otherContainer.Kind) { case SymbolKind.Namespace: if (sourceType is AnonymousTypeManager.AnonymousTypeTemplateSymbol template) { Debug.Assert((object)otherContainer == (object)_otherAssembly.GlobalNamespace); TryFindAnonymousType(template, out var value); return (NamedTypeSymbol?)value.Type?.GetInternalSymbol(); } if (sourceType.IsAnonymousType) { return Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(sourceType)); } return FindMatchingMember(otherContainer, sourceType, AreNamedTypesEqual); case SymbolKind.NamedType: return FindMatchingMember(otherContainer, sourceType, AreNamedTypesEqual); default: throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind); } } public override Symbol VisitParameter(ParameterSymbol parameter) { // Should never reach here. Should be matched as a result of matching the container. throw ExceptionUtilities.Unreachable; } public override Symbol? VisitPointerType(PointerTypeSymbol symbol) { var otherPointedAtType = (TypeSymbol?)Visit(symbol.PointedAtType); if (otherPointedAtType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } var otherModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(otherPointedAtType, otherModifiers)); } public override Symbol? VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { var sig = symbol.Signature; var otherReturnType = (TypeSymbol?)Visit(sig.ReturnType); if (otherReturnType is null) { return null; } var otherRefCustomModifiers = VisitCustomModifiers(sig.RefCustomModifiers); var otherReturnTypeWithAnnotations = sig.ReturnTypeWithAnnotations.WithTypeAndModifiers(otherReturnType, VisitCustomModifiers(sig.ReturnTypeWithAnnotations.CustomModifiers)); var otherParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> otherParamRefCustomModifiers = default; if (sig.ParameterCount > 0) { var otherParamsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(sig.ParameterCount); var otherParamRefCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(sig.ParameterCount); foreach (var param in sig.Parameters) { var otherType = (TypeSymbol?)Visit(param.Type); if (otherType is null) { otherParamsBuilder.Free(); otherParamRefCustomModifiersBuilder.Free(); return null; } otherParamRefCustomModifiersBuilder.Add(VisitCustomModifiers(param.RefCustomModifiers)); otherParamsBuilder.Add(param.TypeWithAnnotations.WithTypeAndModifiers(otherType, VisitCustomModifiers(param.TypeWithAnnotations.CustomModifiers))); } otherParameterTypes = otherParamsBuilder.ToImmutableAndFree(); otherParamRefCustomModifiers = otherParamRefCustomModifiersBuilder.ToImmutableAndFree(); } return symbol.SubstituteTypeSymbol(otherReturnTypeWithAnnotations, otherParameterTypes, otherRefCustomModifiers, otherParamRefCustomModifiers); } public override Symbol? VisitProperty(PropertySymbol symbol) => VisitNamedTypeMember(symbol, ArePropertiesEqual); public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) { if (symbol is IndexedTypeParameterSymbol indexed) { return indexed; } var otherContainer = Visit(symbol.ContainingSymbol); RoslynDebug.AssertNotNull(otherContainer); var otherTypeParameters = otherContainer.Kind switch { SymbolKind.NamedType or SymbolKind.ErrorType => ((NamedTypeSymbol)otherContainer).TypeParameters, SymbolKind.Method => ((MethodSymbol)otherContainer).TypeParameters, _ => throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind), }; return otherTypeParameters[symbol.Ordinal]; } private ImmutableArray<CustomModifier> VisitCustomModifiers(ImmutableArray<CustomModifier> modifiers) { return modifiers.SelectAsArray(VisitCustomModifier); } private CustomModifier VisitCustomModifier(CustomModifier modifier) { var type = (NamedTypeSymbol?)Visit(((CSharpCustomModifier)modifier).ModifierSymbol); RoslynDebug.AssertNotNull(type); return modifier.IsOptional ? CSharpCustomModifier.CreateOptional(type) : CSharpCustomModifier.CreateRequired(type); } internal bool TryFindAnonymousType(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, out AnonymousTypeValue otherType) { Debug.Assert((object)type.ContainingSymbol == (object)_sourceAssembly.GlobalNamespace); return _anonymousTypeMap.TryGetValue(type.GetAnonymousTypeKey(), out otherType); } private Symbol? VisitNamedTypeMember<T>(T member, Func<T, T, bool> predicate) where T : Symbol { var otherType = (NamedTypeSymbol?)Visit(member.ContainingType); // Containing type may be null for synthesized // types such as iterators. if (otherType is null) { return null; } return FindMatchingMember(otherType, member, predicate); } private T? FindMatchingMember<T>(ISymbolInternal otherTypeOrNamespace, T sourceMember, Func<T, T, bool> predicate) where T : Symbol { Debug.Assert(!string.IsNullOrEmpty(sourceMember.MetadataName)); var otherMembersByName = _otherMembers.GetOrAdd(otherTypeOrNamespace, GetAllEmittedMembers); if (otherMembersByName.TryGetValue(sourceMember.MetadataName, out var otherMembers)) { foreach (var otherMember in otherMembers) { if (otherMember is T other && predicate(sourceMember, other)) { return other; } } } return null; } private bool AreArrayTypesEqual(ArrayTypeSymbol type, ArrayTypeSymbol other) { // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.ElementTypeWithAnnotations.CustomModifiers.IsEmpty); Debug.Assert(other.ElementTypeWithAnnotations.CustomModifiers.IsEmpty); return type.HasSameShapeAs(other) && AreTypesEqual(type.ElementType, other.ElementType); } private bool AreEventsEqual(EventSymbol @event, EventSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(@event.Name, other.Name)); return _comparer.Equals(@event.Type, other.Type); } private bool AreFieldsEqual(FieldSymbol field, FieldSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(field.Name, other.Name)); return _comparer.Equals(field.Type, other.Type); } private bool AreMethodsEqual(MethodSymbol method, MethodSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(method.Name, other.Name)); Debug.Assert(method.IsDefinition); Debug.Assert(other.IsDefinition); method = SubstituteTypeParameters(method); other = SubstituteTypeParameters(other); return _comparer.Equals(method.ReturnType, other.ReturnType) && method.RefKind.Equals(other.RefKind) && method.Parameters.SequenceEqual(other.Parameters, AreParametersEqual) && method.TypeParameters.SequenceEqual(other.TypeParameters, AreTypesEqual); } private static MethodSymbol SubstituteTypeParameters(MethodSymbol method) { Debug.Assert(method.IsDefinition); var typeParameters = method.TypeParameters; int n = typeParameters.Length; if (n == 0) { return method; } return method.Construct(IndexedTypeParameterSymbol.Take(n)); } private bool AreNamedTypesEqual(NamedTypeSymbol type, NamedTypeSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(type.MetadataName, other.MetadataName)); // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); Debug.Assert(other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); return type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.SequenceEqual(other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, AreTypesEqual); } private bool AreNamespacesEqual(NamespaceSymbol @namespace, NamespaceSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(@namespace.MetadataName, other.MetadataName)); return true; } private bool AreParametersEqual(ParameterSymbol parameter, ParameterSymbol other) { Debug.Assert(parameter.Ordinal == other.Ordinal); return (parameter.RefKind == other.RefKind) && _comparer.Equals(parameter.Type, other.Type); } private bool ArePointerTypesEqual(PointerTypeSymbol type, PointerTypeSymbol other) { // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.PointedAtTypeWithAnnotations.CustomModifiers.IsEmpty); Debug.Assert(other.PointedAtTypeWithAnnotations.CustomModifiers.IsEmpty); return AreTypesEqual(type.PointedAtType, other.PointedAtType); } private bool AreFunctionPointerTypesEqual(FunctionPointerTypeSymbol type, FunctionPointerTypeSymbol other) { var sig = type.Signature; var otherSig = other.Signature; ValidateFunctionPointerParamOrReturn(sig.ReturnTypeWithAnnotations, sig.RefKind, sig.RefCustomModifiers, allowOut: false); ValidateFunctionPointerParamOrReturn(otherSig.ReturnTypeWithAnnotations, otherSig.RefKind, otherSig.RefCustomModifiers, allowOut: false); if (sig.RefKind != otherSig.RefKind || !AreTypesEqual(sig.ReturnTypeWithAnnotations, otherSig.ReturnTypeWithAnnotations)) { return false; } return sig.Parameters.SequenceEqual(otherSig.Parameters, AreFunctionPointerParametersEqual); } private bool AreFunctionPointerParametersEqual(ParameterSymbol param, ParameterSymbol otherParam) { ValidateFunctionPointerParamOrReturn(param.TypeWithAnnotations, param.RefKind, param.RefCustomModifiers, allowOut: true); ValidateFunctionPointerParamOrReturn(otherParam.TypeWithAnnotations, otherParam.RefKind, otherParam.RefCustomModifiers, allowOut: true); return param.RefKind == otherParam.RefKind && AreTypesEqual(param.TypeWithAnnotations, otherParam.TypeWithAnnotations); } [Conditional("DEBUG")] private static void ValidateFunctionPointerParamOrReturn(TypeWithAnnotations type, RefKind refKind, ImmutableArray<CustomModifier> refCustomModifiers, bool allowOut) { Debug.Assert(type.CustomModifiers.IsEmpty); Debug.Assert(verifyRefModifiers(refCustomModifiers, refKind, allowOut)); static bool verifyRefModifiers(ImmutableArray<CustomModifier> modifiers, RefKind refKind, bool allowOut) { Debug.Assert(RefKind.RefReadOnly == RefKind.In); switch (refKind) { case RefKind.RefReadOnly: case RefKind.Out when allowOut: return modifiers.Length == 1; default: return modifiers.IsEmpty; } } } private bool ArePropertiesEqual(PropertySymbol property, PropertySymbol other) { Debug.Assert(StringOrdinalComparer.Equals(property.MetadataName, other.MetadataName)); return _comparer.Equals(property.Type, other.Type) && property.RefKind.Equals(other.RefKind) && property.Parameters.SequenceEqual(other.Parameters, AreParametersEqual); } private static bool AreTypeParametersEqual(TypeParameterSymbol type, TypeParameterSymbol other) { Debug.Assert(type.Ordinal == other.Ordinal); Debug.Assert(StringOrdinalComparer.Equals(type.Name, other.Name)); // Comparing constraints is unnecessary: two methods cannot differ by // constraints alone and changing the signature of a method is a rude // edit. Furthermore, comparing constraint types might lead to a cycle. Debug.Assert(type.HasConstructorConstraint == other.HasConstructorConstraint); Debug.Assert(type.HasValueTypeConstraint == other.HasValueTypeConstraint); Debug.Assert(type.HasUnmanagedTypeConstraint == other.HasUnmanagedTypeConstraint); Debug.Assert(type.HasReferenceTypeConstraint == other.HasReferenceTypeConstraint); Debug.Assert(type.ConstraintTypesNoUseSiteDiagnostics.Length == other.ConstraintTypesNoUseSiteDiagnostics.Length); return true; } private bool AreTypesEqual(TypeWithAnnotations type, TypeWithAnnotations other) { Debug.Assert(type.CustomModifiers.IsDefaultOrEmpty); Debug.Assert(other.CustomModifiers.IsDefaultOrEmpty); return AreTypesEqual(type.Type, other.Type); } private bool AreTypesEqual(TypeSymbol type, TypeSymbol other) { if (type.Kind != other.Kind) { return false; } switch (type.Kind) { case SymbolKind.ArrayType: return AreArrayTypesEqual((ArrayTypeSymbol)type, (ArrayTypeSymbol)other); case SymbolKind.PointerType: return ArePointerTypesEqual((PointerTypeSymbol)type, (PointerTypeSymbol)other); case SymbolKind.FunctionPointerType: return AreFunctionPointerTypesEqual((FunctionPointerTypeSymbol)type, (FunctionPointerTypeSymbol)other); case SymbolKind.NamedType: case SymbolKind.ErrorType: return AreNamedTypesEqual((NamedTypeSymbol)type, (NamedTypeSymbol)other); case SymbolKind.TypeParameter: return AreTypeParametersEqual((TypeParameterSymbol)type, (TypeParameterSymbol)other); default: throw ExceptionUtilities.UnexpectedValue(type.Kind); } } private IReadOnlyDictionary<string, ImmutableArray<ISymbolInternal>> GetAllEmittedMembers(ISymbolInternal symbol) { var members = ArrayBuilder<ISymbolInternal>.GetInstance(); if (symbol.Kind == SymbolKind.NamedType) { var type = (NamedTypeSymbol)symbol; members.AddRange(type.GetEventsToEmit()); members.AddRange(type.GetFieldsToEmit()); members.AddRange(type.GetMethodsToEmit()); members.AddRange(type.GetTypeMembers()); members.AddRange(type.GetPropertiesToEmit()); } else { members.AddRange(((NamespaceSymbol)symbol).GetMembers()); } if (_otherSynthesizedMembers != null && _otherSynthesizedMembers.TryGetValue(symbol, out var synthesizedMembers)) { members.AddRange(synthesizedMembers); } var result = members.ToDictionary(s => s.MetadataName, StringOrdinalComparer.Instance); members.Free(); return result; } private sealed class SymbolComparer { private readonly MatchSymbols _matcher; private readonly DeepTranslator? _deepTranslator; public SymbolComparer(MatchSymbols matcher, DeepTranslator? deepTranslator) { Debug.Assert(matcher != null); _matcher = matcher; _deepTranslator = deepTranslator; } public bool Equals(TypeSymbol source, TypeSymbol other) { var visitedSource = (TypeSymbol?)_matcher.Visit(source); var visitedOther = (_deepTranslator != null) ? (TypeSymbol)_deepTranslator.Visit(other) : other; return visitedSource?.Equals(visitedOther, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) == true; } } } internal sealed class DeepTranslator : CSharpSymbolVisitor<Symbol> { private readonly ConcurrentDictionary<Symbol, Symbol> _matches; private readonly NamedTypeSymbol _systemObject; public DeepTranslator(NamedTypeSymbol systemObject) { _matches = new ConcurrentDictionary<Symbol, Symbol>(ReferenceEqualityComparer.Instance); _systemObject = systemObject; } public override Symbol DefaultVisit(Symbol symbol) { // Symbol should have been handled elsewhere. throw ExceptionUtilities.Unreachable; } public override Symbol Visit(Symbol symbol) { return _matches.GetOrAdd(symbol, base.Visit(symbol)); } public override Symbol VisitArrayType(ArrayTypeSymbol symbol) { var translatedElementType = (TypeSymbol)this.Visit(symbol.ElementType); var translatedModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); if (symbol.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(translatedElementType, translatedModifiers)); } return ArrayTypeSymbol.CreateMDArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(translatedElementType, translatedModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) { return _systemObject; } public override Symbol VisitNamedType(NamedTypeSymbol type) { var originalDef = type.OriginalDefinition; if ((object)originalDef != type) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var translatedTypeArguments = type.GetAllTypeArguments(ref discardedUseSiteInfo).SelectAsArray((t, v) => t.WithTypeAndModifiers((TypeSymbol)v.Visit(t.Type), v.VisitCustomModifiers(t.CustomModifiers)), this); var translatedOriginalDef = (NamedTypeSymbol)this.Visit(originalDef); var typeMap = new TypeMap(translatedOriginalDef.GetAllTypeParameters(), translatedTypeArguments, allowAlpha: true); return typeMap.SubstituteNamedType(translatedOriginalDef); } Debug.Assert(type.IsDefinition); if (type.IsAnonymousType) { return this.Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type)); } return type; } public override Symbol VisitPointerType(PointerTypeSymbol symbol) { var translatedPointedAtType = (TypeSymbol)this.Visit(symbol.PointedAtType); var translatedModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(translatedPointedAtType, translatedModifiers)); } public override Symbol VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { var sig = symbol.Signature; var translatedReturnType = (TypeSymbol)Visit(sig.ReturnType); var translatedReturnTypeWithAnnotations = sig.ReturnTypeWithAnnotations.WithTypeAndModifiers(translatedReturnType, VisitCustomModifiers(sig.ReturnTypeWithAnnotations.CustomModifiers)); var translatedRefCustomModifiers = VisitCustomModifiers(sig.RefCustomModifiers); var translatedParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> translatedParamRefCustomModifiers = default; if (sig.ParameterCount > 0) { var translatedParamsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(sig.ParameterCount); var translatedParamRefCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(sig.ParameterCount); foreach (var param in sig.Parameters) { var translatedParamType = (TypeSymbol)Visit(param.Type); translatedParamsBuilder.Add(param.TypeWithAnnotations.WithTypeAndModifiers(translatedParamType, VisitCustomModifiers(param.TypeWithAnnotations.CustomModifiers))); translatedParamRefCustomModifiersBuilder.Add(VisitCustomModifiers(param.RefCustomModifiers)); } translatedParameterTypes = translatedParamsBuilder.ToImmutableAndFree(); translatedParamRefCustomModifiers = translatedParamRefCustomModifiersBuilder.ToImmutableAndFree(); } return symbol.SubstituteTypeSymbol(translatedReturnTypeWithAnnotations, translatedParameterTypes, translatedRefCustomModifiers, translatedParamRefCustomModifiers); } public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) { return symbol; } private ImmutableArray<CustomModifier> VisitCustomModifiers(ImmutableArray<CustomModifier> modifiers) { return modifiers.SelectAsArray(VisitCustomModifier); } private CustomModifier VisitCustomModifier(CustomModifier modifier) { var translatedType = (NamedTypeSymbol)this.Visit(((CSharpCustomModifier)modifier).ModifierSymbol); Debug.Assert((object)translatedType != null); return modifier.IsOptional ? CSharpCustomModifier.CreateOptional(translatedType) : CSharpCustomModifier.CreateRequired(translatedType); } } } }
// 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 Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Symbols; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class CSharpSymbolMatcher : SymbolMatcher { private readonly MatchDefs _defs; private readonly MatchSymbols _symbols; public CSharpSymbolMatcher( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> synthesizedDelegates, SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, SourceAssemblySymbol otherAssembly, EmitContext otherContext, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> otherSynthesizedMembersOpt) { _defs = new MatchDefsToSource(sourceContext, otherContext); _symbols = new MatchSymbols(anonymousTypeMap, synthesizedDelegates, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt, new DeepTranslator(otherAssembly.GetSpecialType(SpecialType.System_Object))); } public CSharpSymbolMatcher( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> synthesizedDelegates, SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, PEAssemblySymbol otherAssembly) { _defs = new MatchDefsToMetadata(sourceContext, otherAssembly); _symbols = new MatchSymbols( anonymousTypeMap, synthesizedDelegates, sourceAssembly, otherAssembly, otherSynthesizedMembers: null, deepTranslator: null); } public override Cci.IDefinition? MapDefinition(Cci.IDefinition definition) { if (definition.GetInternalSymbol() is Symbol symbol) { return (Cci.IDefinition?)_symbols.Visit(symbol)?.GetCciAdapter(); } // TODO: this appears to be dead code, remove (https://github.com/dotnet/roslyn/issues/51595) return _defs.VisitDef(definition); } public override Cci.INamespace? MapNamespace(Cci.INamespace @namespace) { if (@namespace.GetInternalSymbol() is NamespaceSymbol symbol) { return (Cci.INamespace?)_symbols.Visit(symbol)?.GetCciAdapter(); } return null; } public override Cci.ITypeReference? MapReference(Cci.ITypeReference reference) { if (reference.GetInternalSymbol() is Symbol symbol) { return (Cci.ITypeReference?)_symbols.Visit(symbol)?.GetCciAdapter(); } return null; } internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, [NotNullWhen(true)] out string? name, out int index) => _symbols.TryGetAnonymousTypeName(template, out name, out index); private abstract class MatchDefs { private readonly EmitContext _sourceContext; private readonly ConcurrentDictionary<Cci.IDefinition, Cci.IDefinition?> _matches = new(ReferenceEqualityComparer.Instance); private IReadOnlyDictionary<string, Cci.INamespaceTypeDefinition>? _lazyTopLevelTypes; public MatchDefs(EmitContext sourceContext) { _sourceContext = sourceContext; } public Cci.IDefinition? VisitDef(Cci.IDefinition def) => _matches.GetOrAdd(def, VisitDefInternal); private Cci.IDefinition? VisitDefInternal(Cci.IDefinition def) { if (def is Cci.ITypeDefinition type) { var namespaceType = type.AsNamespaceTypeDefinition(_sourceContext); if (namespaceType != null) { return VisitNamespaceType(namespaceType); } var nestedType = type.AsNestedTypeDefinition(_sourceContext); Debug.Assert(nestedType != null); var otherContainer = (Cci.ITypeDefinition?)VisitDef(nestedType.ContainingTypeDefinition); if (otherContainer == null) { return null; } return VisitTypeMembers(otherContainer, nestedType, GetNestedTypes, (a, b) => StringOrdinalComparer.Equals(a.Name, b.Name)); } if (def is Cci.ITypeDefinitionMember member) { var otherContainer = (Cci.ITypeDefinition?)VisitDef(member.ContainingTypeDefinition); if (otherContainer == null) { return null; } if (def is Cci.IFieldDefinition field) { return VisitTypeMembers(otherContainer, field, GetFields, (a, b) => StringOrdinalComparer.Equals(a.Name, b.Name)); } } // We are only expecting types and fields currently. throw ExceptionUtilities.UnexpectedValue(def); } protected abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes(); protected abstract IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def); protected abstract IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def); private Cci.INamespaceTypeDefinition? VisitNamespaceType(Cci.INamespaceTypeDefinition def) { // All generated top-level types are assumed to be in the global namespace. // However, this may be an embedded NoPIA type within a namespace. // Since we do not support edits that include references to NoPIA types // (see #855640), it's reasonable to simply drop such cases. if (!string.IsNullOrEmpty(def.NamespaceName)) { return null; } RoslynDebug.AssertNotNull(def.Name); var topLevelTypes = GetTopLevelTypesByName(); topLevelTypes.TryGetValue(def.Name, out var otherDef); return otherDef; } private IReadOnlyDictionary<string, Cci.INamespaceTypeDefinition> GetTopLevelTypesByName() { if (_lazyTopLevelTypes == null) { var typesByName = new Dictionary<string, Cci.INamespaceTypeDefinition>(StringOrdinalComparer.Instance); foreach (var type in GetTopLevelTypes()) { // All generated top-level types are assumed to be in the global namespace. if (string.IsNullOrEmpty(type.NamespaceName)) { RoslynDebug.AssertNotNull(type.Name); typesByName.Add(type.Name, type); } } Interlocked.CompareExchange(ref _lazyTopLevelTypes, typesByName, null); } return _lazyTopLevelTypes; } private static T VisitTypeMembers<T>( Cci.ITypeDefinition otherContainer, T member, Func<Cci.ITypeDefinition, IEnumerable<T>> getMembers, Func<T, T, bool> predicate) where T : class, Cci.ITypeDefinitionMember { // We could cache the members by name (see Matcher.VisitNamedTypeMembers) // but the assumption is this class is only used for types with few members // so caching is not necessary and linear search is acceptable. return getMembers(otherContainer).FirstOrDefault(otherMember => predicate(member, otherMember)); } } private sealed class MatchDefsToMetadata : MatchDefs { private readonly PEAssemblySymbol _otherAssembly; public MatchDefsToMetadata(EmitContext sourceContext, PEAssemblySymbol otherAssembly) : base(sourceContext) { _otherAssembly = otherAssembly; } protected override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes() { var builder = ArrayBuilder<Cci.INamespaceTypeDefinition>.GetInstance(); GetTopLevelTypes(builder, _otherAssembly.GlobalNamespace); return builder.ToArrayAndFree(); } protected override IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def) { var type = (PENamedTypeSymbol)def; return type.GetTypeMembers().Cast<Cci.INestedTypeDefinition>(); } protected override IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def) { var type = (PENamedTypeSymbol)def; return type.GetFieldsToEmit().Cast<Cci.IFieldDefinition>(); } private static void GetTopLevelTypes(ArrayBuilder<Cci.INamespaceTypeDefinition> builder, NamespaceSymbol @namespace) { foreach (var member in @namespace.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { GetTopLevelTypes(builder, (NamespaceSymbol)member); } else { builder.Add((Cci.INamespaceTypeDefinition)member.GetCciAdapter()); } } } } private sealed class MatchDefsToSource : MatchDefs { private readonly EmitContext _otherContext; public MatchDefsToSource( EmitContext sourceContext, EmitContext otherContext) : base(sourceContext) { _otherContext = otherContext; } protected override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes() { return _otherContext.Module.GetTopLevelTypeDefinitions(_otherContext); } protected override IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def) { return def.GetNestedTypes(_otherContext); } protected override IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def) { return def.GetFields(_otherContext); } } private sealed class MatchSymbols : CSharpSymbolVisitor<Symbol?> { private readonly IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> _anonymousTypeMap; private readonly IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> _synthesizedDelegates; private readonly SourceAssemblySymbol _sourceAssembly; // metadata or source assembly: private readonly AssemblySymbol _otherAssembly; /// <summary> /// Members that are not listed directly on their containing type or namespace symbol as they were synthesized in a lowering phase, /// after the symbol has been created. /// </summary> private readonly ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>? _otherSynthesizedMembers; private readonly SymbolComparer _comparer; private readonly ConcurrentDictionary<Symbol, Symbol?> _matches = new(ReferenceEqualityComparer.Instance); /// <summary> /// A cache of members per type, populated when the first member for a given /// type is needed. Within each type, members are indexed by name. The reason /// for caching, and indexing by name, is to avoid searching sequentially /// through all members of a given kind each time a member is matched. /// </summary> private readonly ConcurrentDictionary<ISymbolInternal, IReadOnlyDictionary<string, ImmutableArray<ISymbolInternal>>> _otherMembers = new(ReferenceEqualityComparer.Instance); public MatchSymbols( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> synthesizedDelegates, SourceAssemblySymbol sourceAssembly, AssemblySymbol otherAssembly, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>? otherSynthesizedMembers, DeepTranslator? deepTranslator) { _anonymousTypeMap = anonymousTypeMap; _synthesizedDelegates = synthesizedDelegates; _sourceAssembly = sourceAssembly; _otherAssembly = otherAssembly; _otherSynthesizedMembers = otherSynthesizedMembers; _comparer = new SymbolComparer(this, deepTranslator); } internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, [NotNullWhen(true)] out string? name, out int index) { if (TryFindAnonymousType(type, out var otherType)) { name = otherType.Name; index = otherType.UniqueIndex; return true; } name = null; index = -1; return false; } public override Symbol DefaultVisit(Symbol symbol) { // Symbol should have been handled elsewhere. throw ExceptionUtilities.Unreachable; } public override Symbol? Visit(Symbol symbol) { Debug.Assert((object)symbol.ContainingAssembly != (object)_otherAssembly); // Add an entry for the match, even if there is no match, to avoid // matching the same symbol unsuccessfully multiple times. return _matches.GetOrAdd(symbol, base.Visit); } public override Symbol? VisitArrayType(ArrayTypeSymbol symbol) { var otherElementType = (TypeSymbol?)Visit(symbol.ElementType); if (otherElementType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } var otherModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); if (symbol.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(otherElementType, otherModifiers)); } return ArrayTypeSymbol.CreateMDArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(otherElementType, otherModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); } public override Symbol? VisitEvent(EventSymbol symbol) => VisitNamedTypeMember(symbol, AreEventsEqual); public override Symbol? VisitField(FieldSymbol symbol) => VisitNamedTypeMember(symbol, AreFieldsEqual); public override Symbol? VisitMethod(MethodSymbol symbol) { // Not expecting constructed method. Debug.Assert(symbol.IsDefinition); return VisitNamedTypeMember(symbol, AreMethodsEqual); } public override Symbol? VisitModule(ModuleSymbol module) { var otherAssembly = (AssemblySymbol?)Visit(module.ContainingAssembly); if (otherAssembly is null) { return null; } // manifest module: if (module.Ordinal == 0) { return otherAssembly.Modules[0]; } // match non-manifest module by name: for (int i = 1; i < otherAssembly.Modules.Length; i++) { var otherModule = otherAssembly.Modules[i]; // use case sensitive comparison -- modules whose names differ in casing are considered distinct: if (StringComparer.Ordinal.Equals(otherModule.Name, module.Name)) { return otherModule; } } return null; } public override Symbol? VisitAssembly(AssemblySymbol assembly) { if (assembly.IsLinked) { return assembly; } // When we map synthesized symbols from previous generations to the latest compilation // we might encounter a symbol that is defined in arbitrary preceding generation, // not just the immediately preceding generation. If the source assembly uses time-based // versioning assemblies of preceding generations might differ in their version number. if (IdentityEqualIgnoringVersionWildcard(assembly, _sourceAssembly)) { return _otherAssembly; } // find a referenced assembly with the same source identity (modulo assembly version patterns): foreach (var otherReferencedAssembly in _otherAssembly.Modules[0].ReferencedAssemblySymbols) { if (IdentityEqualIgnoringVersionWildcard(assembly, otherReferencedAssembly)) { return otherReferencedAssembly; } } return null; } private static bool IdentityEqualIgnoringVersionWildcard(AssemblySymbol left, AssemblySymbol right) { var leftIdentity = left.Identity; var rightIdentity = right.Identity; return AssemblyIdentityComparer.SimpleNameComparer.Equals(leftIdentity.Name, rightIdentity.Name) && (left.AssemblyVersionPattern ?? leftIdentity.Version).Equals(right.AssemblyVersionPattern ?? rightIdentity.Version) && AssemblyIdentity.EqualIgnoringNameAndVersion(leftIdentity, rightIdentity); } public override Symbol? VisitNamespace(NamespaceSymbol @namespace) { var otherContainer = Visit(@namespace.ContainingSymbol); // Containing namespace will be missing from other assembly // if its was added in the (newer) source assembly. if (otherContainer is null) { return null; } switch (otherContainer.Kind) { case SymbolKind.NetModule: Debug.Assert(@namespace.IsGlobalNamespace); return ((ModuleSymbol)otherContainer).GlobalNamespace; case SymbolKind.Namespace: return FindMatchingMember(otherContainer, @namespace, AreNamespacesEqual); default: throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind); } } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) { return _otherAssembly.GetSpecialType(SpecialType.System_Object); } public override Symbol? VisitNamedType(NamedTypeSymbol sourceType) { var originalDef = sourceType.OriginalDefinition; if ((object)originalDef != (object)sourceType) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var typeArguments = sourceType.GetAllTypeArguments(ref discardedUseSiteInfo); var otherDef = (NamedTypeSymbol?)Visit(originalDef); if (otherDef is null) { return null; } var otherTypeParameters = otherDef.GetAllTypeParameters(); bool translationFailed = false; var otherTypeArguments = typeArguments.SelectAsArray((t, v) => { var newType = (TypeSymbol?)v.Visit(t.Type); if (newType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. translationFailed = true; newType = t.Type; } return t.WithTypeAndModifiers(newType, v.VisitCustomModifiers(t.CustomModifiers)); }, this); if (translationFailed) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } // TODO: LambdaFrame has alpha renamed type parameters, should we rather fix that? var typeMap = new TypeMap(otherTypeParameters, otherTypeArguments, allowAlpha: true); return typeMap.SubstituteNamedType(otherDef); } Debug.Assert(sourceType.IsDefinition); var otherContainer = this.Visit(sourceType.ContainingSymbol); // Containing type will be missing from other assembly // if the type was added in the (newer) source assembly. if (otherContainer is null) { return null; } switch (otherContainer.Kind) { case SymbolKind.Namespace: if (sourceType is AnonymousTypeManager.AnonymousTypeTemplateSymbol template) { Debug.Assert((object)otherContainer == (object)_otherAssembly.GlobalNamespace); TryFindAnonymousType(template, out var value); return (NamedTypeSymbol?)value.Type?.GetInternalSymbol(); } else if (sourceType is SynthesizedDelegateSymbol delegateSymbol) { Debug.Assert((object)otherContainer == (object)_otherAssembly.GlobalNamespace); TryFindSynthesizedDelegate(delegateSymbol, out var value); return (NamedTypeSymbol?)value.Delegate?.GetInternalSymbol(); } if (sourceType.IsAnonymousType) { return Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(sourceType)); } return FindMatchingMember(otherContainer, sourceType, AreNamedTypesEqual); case SymbolKind.NamedType: return FindMatchingMember(otherContainer, sourceType, AreNamedTypesEqual); default: throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind); } } public override Symbol VisitParameter(ParameterSymbol parameter) { // Should never reach here. Should be matched as a result of matching the container. throw ExceptionUtilities.Unreachable; } public override Symbol? VisitPointerType(PointerTypeSymbol symbol) { var otherPointedAtType = (TypeSymbol?)Visit(symbol.PointedAtType); if (otherPointedAtType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } var otherModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(otherPointedAtType, otherModifiers)); } public override Symbol? VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { var sig = symbol.Signature; var otherReturnType = (TypeSymbol?)Visit(sig.ReturnType); if (otherReturnType is null) { return null; } var otherRefCustomModifiers = VisitCustomModifiers(sig.RefCustomModifiers); var otherReturnTypeWithAnnotations = sig.ReturnTypeWithAnnotations.WithTypeAndModifiers(otherReturnType, VisitCustomModifiers(sig.ReturnTypeWithAnnotations.CustomModifiers)); var otherParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> otherParamRefCustomModifiers = default; if (sig.ParameterCount > 0) { var otherParamsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(sig.ParameterCount); var otherParamRefCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(sig.ParameterCount); foreach (var param in sig.Parameters) { var otherType = (TypeSymbol?)Visit(param.Type); if (otherType is null) { otherParamsBuilder.Free(); otherParamRefCustomModifiersBuilder.Free(); return null; } otherParamRefCustomModifiersBuilder.Add(VisitCustomModifiers(param.RefCustomModifiers)); otherParamsBuilder.Add(param.TypeWithAnnotations.WithTypeAndModifiers(otherType, VisitCustomModifiers(param.TypeWithAnnotations.CustomModifiers))); } otherParameterTypes = otherParamsBuilder.ToImmutableAndFree(); otherParamRefCustomModifiers = otherParamRefCustomModifiersBuilder.ToImmutableAndFree(); } return symbol.SubstituteTypeSymbol(otherReturnTypeWithAnnotations, otherParameterTypes, otherRefCustomModifiers, otherParamRefCustomModifiers); } public override Symbol? VisitProperty(PropertySymbol symbol) => VisitNamedTypeMember(symbol, ArePropertiesEqual); public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) { if (symbol is IndexedTypeParameterSymbol indexed) { return indexed; } var otherContainer = Visit(symbol.ContainingSymbol); RoslynDebug.AssertNotNull(otherContainer); var otherTypeParameters = otherContainer.Kind switch { SymbolKind.NamedType or SymbolKind.ErrorType => ((NamedTypeSymbol)otherContainer).TypeParameters, SymbolKind.Method => ((MethodSymbol)otherContainer).TypeParameters, _ => throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind), }; return otherTypeParameters[symbol.Ordinal]; } private ImmutableArray<CustomModifier> VisitCustomModifiers(ImmutableArray<CustomModifier> modifiers) { return modifiers.SelectAsArray(VisitCustomModifier); } private CustomModifier VisitCustomModifier(CustomModifier modifier) { var type = (NamedTypeSymbol?)Visit(((CSharpCustomModifier)modifier).ModifierSymbol); RoslynDebug.AssertNotNull(type); return modifier.IsOptional ? CSharpCustomModifier.CreateOptional(type) : CSharpCustomModifier.CreateRequired(type); } internal bool TryFindAnonymousType(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, out AnonymousTypeValue otherType) { Debug.Assert((object)type.ContainingSymbol == (object)_sourceAssembly.GlobalNamespace); return _anonymousTypeMap.TryGetValue(type.GetAnonymousTypeKey(), out otherType); } internal bool TryFindSynthesizedDelegate(SynthesizedDelegateSymbol delegateSymbol, out SynthesizedDelegateValue otherDelegateSymbol) { Debug.Assert((object)delegateSymbol.ContainingSymbol == (object)_sourceAssembly.GlobalNamespace); var key = new SynthesizedDelegateKey(delegateSymbol.MetadataName); return _synthesizedDelegates.TryGetValue(key, out otherDelegateSymbol); } private Symbol? VisitNamedTypeMember<T>(T member, Func<T, T, bool> predicate) where T : Symbol { var otherType = (NamedTypeSymbol?)Visit(member.ContainingType); // Containing type may be null for synthesized // types such as iterators. if (otherType is null) { return null; } return FindMatchingMember(otherType, member, predicate); } private T? FindMatchingMember<T>(ISymbolInternal otherTypeOrNamespace, T sourceMember, Func<T, T, bool> predicate) where T : Symbol { Debug.Assert(!string.IsNullOrEmpty(sourceMember.MetadataName)); var otherMembersByName = _otherMembers.GetOrAdd(otherTypeOrNamespace, GetAllEmittedMembers); if (otherMembersByName.TryGetValue(sourceMember.MetadataName, out var otherMembers)) { foreach (var otherMember in otherMembers) { if (otherMember is T other && predicate(sourceMember, other)) { return other; } } } return null; } private bool AreArrayTypesEqual(ArrayTypeSymbol type, ArrayTypeSymbol other) { // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.ElementTypeWithAnnotations.CustomModifiers.IsEmpty); Debug.Assert(other.ElementTypeWithAnnotations.CustomModifiers.IsEmpty); return type.HasSameShapeAs(other) && AreTypesEqual(type.ElementType, other.ElementType); } private bool AreEventsEqual(EventSymbol @event, EventSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(@event.Name, other.Name)); return _comparer.Equals(@event.Type, other.Type); } private bool AreFieldsEqual(FieldSymbol field, FieldSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(field.Name, other.Name)); return _comparer.Equals(field.Type, other.Type); } private bool AreMethodsEqual(MethodSymbol method, MethodSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(method.Name, other.Name)); Debug.Assert(method.IsDefinition); Debug.Assert(other.IsDefinition); method = SubstituteTypeParameters(method); other = SubstituteTypeParameters(other); return _comparer.Equals(method.ReturnType, other.ReturnType) && method.RefKind.Equals(other.RefKind) && method.Parameters.SequenceEqual(other.Parameters, AreParametersEqual) && method.TypeParameters.SequenceEqual(other.TypeParameters, AreTypesEqual); } private static MethodSymbol SubstituteTypeParameters(MethodSymbol method) { Debug.Assert(method.IsDefinition); var typeParameters = method.TypeParameters; int n = typeParameters.Length; if (n == 0) { return method; } return method.Construct(IndexedTypeParameterSymbol.Take(n)); } private bool AreNamedTypesEqual(NamedTypeSymbol type, NamedTypeSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(type.MetadataName, other.MetadataName)); // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); Debug.Assert(other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); return type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.SequenceEqual(other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, AreTypesEqual); } private bool AreNamespacesEqual(NamespaceSymbol @namespace, NamespaceSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(@namespace.MetadataName, other.MetadataName)); return true; } private bool AreParametersEqual(ParameterSymbol parameter, ParameterSymbol other) { Debug.Assert(parameter.Ordinal == other.Ordinal); return (parameter.RefKind == other.RefKind) && _comparer.Equals(parameter.Type, other.Type); } private bool ArePointerTypesEqual(PointerTypeSymbol type, PointerTypeSymbol other) { // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.PointedAtTypeWithAnnotations.CustomModifiers.IsEmpty); Debug.Assert(other.PointedAtTypeWithAnnotations.CustomModifiers.IsEmpty); return AreTypesEqual(type.PointedAtType, other.PointedAtType); } private bool AreFunctionPointerTypesEqual(FunctionPointerTypeSymbol type, FunctionPointerTypeSymbol other) { var sig = type.Signature; var otherSig = other.Signature; ValidateFunctionPointerParamOrReturn(sig.ReturnTypeWithAnnotations, sig.RefKind, sig.RefCustomModifiers, allowOut: false); ValidateFunctionPointerParamOrReturn(otherSig.ReturnTypeWithAnnotations, otherSig.RefKind, otherSig.RefCustomModifiers, allowOut: false); if (sig.RefKind != otherSig.RefKind || !AreTypesEqual(sig.ReturnTypeWithAnnotations, otherSig.ReturnTypeWithAnnotations)) { return false; } return sig.Parameters.SequenceEqual(otherSig.Parameters, AreFunctionPointerParametersEqual); } private bool AreFunctionPointerParametersEqual(ParameterSymbol param, ParameterSymbol otherParam) { ValidateFunctionPointerParamOrReturn(param.TypeWithAnnotations, param.RefKind, param.RefCustomModifiers, allowOut: true); ValidateFunctionPointerParamOrReturn(otherParam.TypeWithAnnotations, otherParam.RefKind, otherParam.RefCustomModifiers, allowOut: true); return param.RefKind == otherParam.RefKind && AreTypesEqual(param.TypeWithAnnotations, otherParam.TypeWithAnnotations); } [Conditional("DEBUG")] private static void ValidateFunctionPointerParamOrReturn(TypeWithAnnotations type, RefKind refKind, ImmutableArray<CustomModifier> refCustomModifiers, bool allowOut) { Debug.Assert(type.CustomModifiers.IsEmpty); Debug.Assert(verifyRefModifiers(refCustomModifiers, refKind, allowOut)); static bool verifyRefModifiers(ImmutableArray<CustomModifier> modifiers, RefKind refKind, bool allowOut) { Debug.Assert(RefKind.RefReadOnly == RefKind.In); switch (refKind) { case RefKind.RefReadOnly: case RefKind.Out when allowOut: return modifiers.Length == 1; default: return modifiers.IsEmpty; } } } private bool ArePropertiesEqual(PropertySymbol property, PropertySymbol other) { Debug.Assert(StringOrdinalComparer.Equals(property.MetadataName, other.MetadataName)); return _comparer.Equals(property.Type, other.Type) && property.RefKind.Equals(other.RefKind) && property.Parameters.SequenceEqual(other.Parameters, AreParametersEqual); } private static bool AreTypeParametersEqual(TypeParameterSymbol type, TypeParameterSymbol other) { Debug.Assert(type.Ordinal == other.Ordinal); Debug.Assert(StringOrdinalComparer.Equals(type.Name, other.Name)); // Comparing constraints is unnecessary: two methods cannot differ by // constraints alone and changing the signature of a method is a rude // edit. Furthermore, comparing constraint types might lead to a cycle. Debug.Assert(type.HasConstructorConstraint == other.HasConstructorConstraint); Debug.Assert(type.HasValueTypeConstraint == other.HasValueTypeConstraint); Debug.Assert(type.HasUnmanagedTypeConstraint == other.HasUnmanagedTypeConstraint); Debug.Assert(type.HasReferenceTypeConstraint == other.HasReferenceTypeConstraint); Debug.Assert(type.ConstraintTypesNoUseSiteDiagnostics.Length == other.ConstraintTypesNoUseSiteDiagnostics.Length); return true; } private bool AreTypesEqual(TypeWithAnnotations type, TypeWithAnnotations other) { Debug.Assert(type.CustomModifiers.IsDefaultOrEmpty); Debug.Assert(other.CustomModifiers.IsDefaultOrEmpty); return AreTypesEqual(type.Type, other.Type); } private bool AreTypesEqual(TypeSymbol type, TypeSymbol other) { if (type.Kind != other.Kind) { return false; } switch (type.Kind) { case SymbolKind.ArrayType: return AreArrayTypesEqual((ArrayTypeSymbol)type, (ArrayTypeSymbol)other); case SymbolKind.PointerType: return ArePointerTypesEqual((PointerTypeSymbol)type, (PointerTypeSymbol)other); case SymbolKind.FunctionPointerType: return AreFunctionPointerTypesEqual((FunctionPointerTypeSymbol)type, (FunctionPointerTypeSymbol)other); case SymbolKind.NamedType: case SymbolKind.ErrorType: return AreNamedTypesEqual((NamedTypeSymbol)type, (NamedTypeSymbol)other); case SymbolKind.TypeParameter: return AreTypeParametersEqual((TypeParameterSymbol)type, (TypeParameterSymbol)other); default: throw ExceptionUtilities.UnexpectedValue(type.Kind); } } private IReadOnlyDictionary<string, ImmutableArray<ISymbolInternal>> GetAllEmittedMembers(ISymbolInternal symbol) { var members = ArrayBuilder<ISymbolInternal>.GetInstance(); if (symbol.Kind == SymbolKind.NamedType) { var type = (NamedTypeSymbol)symbol; members.AddRange(type.GetEventsToEmit()); members.AddRange(type.GetFieldsToEmit()); members.AddRange(type.GetMethodsToEmit()); members.AddRange(type.GetTypeMembers()); members.AddRange(type.GetPropertiesToEmit()); } else { members.AddRange(((NamespaceSymbol)symbol).GetMembers()); } if (_otherSynthesizedMembers != null && _otherSynthesizedMembers.TryGetValue(symbol, out var synthesizedMembers)) { members.AddRange(synthesizedMembers); } var result = members.ToDictionary(s => s.MetadataName, StringOrdinalComparer.Instance); members.Free(); return result; } private sealed class SymbolComparer { private readonly MatchSymbols _matcher; private readonly DeepTranslator? _deepTranslator; public SymbolComparer(MatchSymbols matcher, DeepTranslator? deepTranslator) { Debug.Assert(matcher != null); _matcher = matcher; _deepTranslator = deepTranslator; } public bool Equals(TypeSymbol source, TypeSymbol other) { var visitedSource = (TypeSymbol?)_matcher.Visit(source); var visitedOther = (_deepTranslator != null) ? (TypeSymbol)_deepTranslator.Visit(other) : other; return visitedSource?.Equals(visitedOther, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) == true; } } } internal sealed class DeepTranslator : CSharpSymbolVisitor<Symbol> { private readonly ConcurrentDictionary<Symbol, Symbol> _matches; private readonly NamedTypeSymbol _systemObject; public DeepTranslator(NamedTypeSymbol systemObject) { _matches = new ConcurrentDictionary<Symbol, Symbol>(ReferenceEqualityComparer.Instance); _systemObject = systemObject; } public override Symbol DefaultVisit(Symbol symbol) { // Symbol should have been handled elsewhere. throw ExceptionUtilities.Unreachable; } public override Symbol Visit(Symbol symbol) { return _matches.GetOrAdd(symbol, base.Visit(symbol)); } public override Symbol VisitArrayType(ArrayTypeSymbol symbol) { var translatedElementType = (TypeSymbol)this.Visit(symbol.ElementType); var translatedModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); if (symbol.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(translatedElementType, translatedModifiers)); } return ArrayTypeSymbol.CreateMDArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(translatedElementType, translatedModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) { return _systemObject; } public override Symbol VisitNamedType(NamedTypeSymbol type) { var originalDef = type.OriginalDefinition; if ((object)originalDef != type) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var translatedTypeArguments = type.GetAllTypeArguments(ref discardedUseSiteInfo).SelectAsArray((t, v) => t.WithTypeAndModifiers((TypeSymbol)v.Visit(t.Type), v.VisitCustomModifiers(t.CustomModifiers)), this); var translatedOriginalDef = (NamedTypeSymbol)this.Visit(originalDef); var typeMap = new TypeMap(translatedOriginalDef.GetAllTypeParameters(), translatedTypeArguments, allowAlpha: true); return typeMap.SubstituteNamedType(translatedOriginalDef); } Debug.Assert(type.IsDefinition); if (type.IsAnonymousType) { return this.Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type)); } return type; } public override Symbol VisitPointerType(PointerTypeSymbol symbol) { var translatedPointedAtType = (TypeSymbol)this.Visit(symbol.PointedAtType); var translatedModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(translatedPointedAtType, translatedModifiers)); } public override Symbol VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { var sig = symbol.Signature; var translatedReturnType = (TypeSymbol)Visit(sig.ReturnType); var translatedReturnTypeWithAnnotations = sig.ReturnTypeWithAnnotations.WithTypeAndModifiers(translatedReturnType, VisitCustomModifiers(sig.ReturnTypeWithAnnotations.CustomModifiers)); var translatedRefCustomModifiers = VisitCustomModifiers(sig.RefCustomModifiers); var translatedParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> translatedParamRefCustomModifiers = default; if (sig.ParameterCount > 0) { var translatedParamsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(sig.ParameterCount); var translatedParamRefCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(sig.ParameterCount); foreach (var param in sig.Parameters) { var translatedParamType = (TypeSymbol)Visit(param.Type); translatedParamsBuilder.Add(param.TypeWithAnnotations.WithTypeAndModifiers(translatedParamType, VisitCustomModifiers(param.TypeWithAnnotations.CustomModifiers))); translatedParamRefCustomModifiersBuilder.Add(VisitCustomModifiers(param.RefCustomModifiers)); } translatedParameterTypes = translatedParamsBuilder.ToImmutableAndFree(); translatedParamRefCustomModifiers = translatedParamRefCustomModifiersBuilder.ToImmutableAndFree(); } return symbol.SubstituteTypeSymbol(translatedReturnTypeWithAnnotations, translatedParameterTypes, translatedRefCustomModifiers, translatedParamRefCustomModifiers); } public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) { return symbol; } private ImmutableArray<CustomModifier> VisitCustomModifiers(ImmutableArray<CustomModifier> modifiers) { return modifiers.SelectAsArray(VisitCustomModifier); } private CustomModifier VisitCustomModifier(CustomModifier modifier) { var translatedType = (NamedTypeSymbol)this.Visit(((CSharpCustomModifier)modifier).ModifierSymbol); Debug.Assert((object)translatedType != null); return modifier.IsOptional ? CSharpCustomModifier.CreateOptional(translatedType) : CSharpCustomModifier.CreateRequired(translatedType); } } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Portable/Emitter/EditAndContinue/EmitHelpers.cs
// 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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Reflection.Metadata; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal static class EmitHelpers { internal static EmitDifferenceResult EmitDifference( CSharpCompilation compilation, EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, CompilationTestData? testData, CancellationToken cancellationToken) { var diagnostics = DiagnosticBag.GetInstance(); var emitOptions = EmitOptions.Default.WithDebugInformationFormat(baseline.HasPortablePdb ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb); var runtimeMDVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics); var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMDVersion, baseline.ModuleVersionId); var manifestResources = SpecializedCollections.EmptyEnumerable<ResourceDescription>(); PEDeltaAssemblyBuilder moduleBeingBuilt; try { moduleBeingBuilt = new PEDeltaAssemblyBuilder( compilation.SourceAssembly, emitOptions: emitOptions, outputKind: compilation.Options.OutputKind, serializationProperties: serializationProperties, manifestResources: manifestResources, previousGeneration: baseline, edits: edits, isAddedSymbol: isAddedSymbol); } catch (NotSupportedException e) { // TODO: https://github.com/dotnet/roslyn/issues/9004 diagnostics.Add(ErrorCode.ERR_ModuleEmitFailure, NoLocation.Singleton, compilation.AssemblyName, e.Message); return new EmitDifferenceResult( success: false, diagnostics: diagnostics.ToReadOnlyAndFree(), baseline: null, updatedMethods: ImmutableArray<MethodDefinitionHandle>.Empty, changedTypes: ImmutableArray<TypeDefinitionHandle>.Empty); } if (testData != null) { moduleBeingBuilt.SetMethodTestData(testData.Methods); testData.Module = moduleBeingBuilt; } var definitionMap = moduleBeingBuilt.PreviousDefinitions; var changes = moduleBeingBuilt.EncSymbolChanges; Debug.Assert(changes != null); EmitBaseline? newBaseline = null; var updatedMethods = ArrayBuilder<MethodDefinitionHandle>.GetInstance(); var changedTypes = ArrayBuilder<TypeDefinitionHandle>.GetInstance(); if (compilation.Compile( moduleBeingBuilt, emittingPdb: true, diagnostics: diagnostics, filterOpt: s => changes.RequiresCompilation(s.GetISymbol()), cancellationToken: cancellationToken)) { // Map the definitions from the previous compilation to the current compilation. // This must be done after compiling above since synthesized definitions // (generated when compiling method bodies) may be required. var mappedBaseline = MapToCompilation(compilation, moduleBeingBuilt); newBaseline = compilation.SerializeToDeltaStreams( moduleBeingBuilt, mappedBaseline, definitionMap, changes, metadataStream, ilStream, pdbStream, updatedMethods, changedTypes, diagnostics, testData?.SymWriterFactory, emitOptions.PdbFilePath, cancellationToken); } return new EmitDifferenceResult( success: newBaseline != null, diagnostics: diagnostics.ToReadOnlyAndFree(), baseline: newBaseline, updatedMethods: updatedMethods.ToImmutableAndFree(), changedTypes: changedTypes.ToImmutableAndFree()); } /// <summary> /// Return a version of the baseline with all definitions mapped to this compilation. /// Definitions from the initial generation, from metadata, are not mapped since /// the initial generation is always included as metadata. That is, the symbols from /// types, methods, ... in the TypesAdded, MethodsAdded, ... collections are replaced /// by the corresponding symbols from the current compilation. /// </summary> private static EmitBaseline MapToCompilation( CSharpCompilation compilation, PEDeltaAssemblyBuilder moduleBeingBuilt) { var previousGeneration = moduleBeingBuilt.PreviousGeneration; RoslynDebug.Assert(previousGeneration.Compilation != compilation); if (previousGeneration.Ordinal == 0) { // Initial generation, nothing to map. (Since the initial generation // is always loaded from metadata in the context of the current // compilation, there's no separate mapping step.) return previousGeneration; } RoslynDebug.AssertNotNull(previousGeneration.Compilation); RoslynDebug.AssertNotNull(previousGeneration.PEModuleBuilder); var currentSynthesizedMembers = moduleBeingBuilt.GetAllSynthesizedMembers(); // Mapping from previous compilation to the current. var anonymousTypeMap = moduleBeingBuilt.GetAnonymousTypeMap(); var sourceAssembly = ((CSharpCompilation)previousGeneration.Compilation).SourceAssembly; var sourceContext = new EmitContext((PEModuleBuilder)previousGeneration.PEModuleBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var otherContext = new EmitContext(moduleBeingBuilt, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var matcher = new CSharpSymbolMatcher( anonymousTypeMap, sourceAssembly, sourceContext, compilation.SourceAssembly, otherContext, currentSynthesizedMembers); var mappedSynthesizedMembers = matcher.MapSynthesizedMembers(previousGeneration.SynthesizedMembers, currentSynthesizedMembers); // TODO: can we reuse some data from the previous matcher? var matcherWithAllSynthesizedMembers = new CSharpSymbolMatcher( anonymousTypeMap, sourceAssembly, sourceContext, compilation.SourceAssembly, otherContext, mappedSynthesizedMembers); return matcherWithAllSynthesizedMembers.MapBaselineToCompilation( previousGeneration, compilation, moduleBeingBuilt, mappedSynthesizedMembers); } } }
// 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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Reflection.Metadata; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal static class EmitHelpers { internal static EmitDifferenceResult EmitDifference( CSharpCompilation compilation, EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, CompilationTestData? testData, CancellationToken cancellationToken) { var diagnostics = DiagnosticBag.GetInstance(); var emitOptions = EmitOptions.Default.WithDebugInformationFormat(baseline.HasPortablePdb ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb); var runtimeMDVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics); var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMDVersion, baseline.ModuleVersionId); var manifestResources = SpecializedCollections.EmptyEnumerable<ResourceDescription>(); PEDeltaAssemblyBuilder moduleBeingBuilt; try { moduleBeingBuilt = new PEDeltaAssemblyBuilder( compilation.SourceAssembly, emitOptions: emitOptions, outputKind: compilation.Options.OutputKind, serializationProperties: serializationProperties, manifestResources: manifestResources, previousGeneration: baseline, edits: edits, isAddedSymbol: isAddedSymbol); } catch (NotSupportedException e) { // TODO: https://github.com/dotnet/roslyn/issues/9004 diagnostics.Add(ErrorCode.ERR_ModuleEmitFailure, NoLocation.Singleton, compilation.AssemblyName, e.Message); return new EmitDifferenceResult( success: false, diagnostics: diagnostics.ToReadOnlyAndFree(), baseline: null, updatedMethods: ImmutableArray<MethodDefinitionHandle>.Empty, changedTypes: ImmutableArray<TypeDefinitionHandle>.Empty); } if (testData != null) { moduleBeingBuilt.SetMethodTestData(testData.Methods); testData.Module = moduleBeingBuilt; } var definitionMap = moduleBeingBuilt.PreviousDefinitions; var changes = moduleBeingBuilt.EncSymbolChanges; Debug.Assert(changes != null); EmitBaseline? newBaseline = null; var updatedMethods = ArrayBuilder<MethodDefinitionHandle>.GetInstance(); var changedTypes = ArrayBuilder<TypeDefinitionHandle>.GetInstance(); if (compilation.Compile( moduleBeingBuilt, emittingPdb: true, diagnostics: diagnostics, filterOpt: s => changes.RequiresCompilation(s.GetISymbol()), cancellationToken: cancellationToken)) { // Map the definitions from the previous compilation to the current compilation. // This must be done after compiling above since synthesized definitions // (generated when compiling method bodies) may be required. var mappedBaseline = MapToCompilation(compilation, moduleBeingBuilt); newBaseline = compilation.SerializeToDeltaStreams( moduleBeingBuilt, mappedBaseline, definitionMap, changes, metadataStream, ilStream, pdbStream, updatedMethods, changedTypes, diagnostics, testData?.SymWriterFactory, emitOptions.PdbFilePath, cancellationToken); } return new EmitDifferenceResult( success: newBaseline != null, diagnostics: diagnostics.ToReadOnlyAndFree(), baseline: newBaseline, updatedMethods: updatedMethods.ToImmutableAndFree(), changedTypes: changedTypes.ToImmutableAndFree()); } /// <summary> /// Return a version of the baseline with all definitions mapped to this compilation. /// Definitions from the initial generation, from metadata, are not mapped since /// the initial generation is always included as metadata. That is, the symbols from /// types, methods, ... in the TypesAdded, MethodsAdded, ... collections are replaced /// by the corresponding symbols from the current compilation. /// </summary> private static EmitBaseline MapToCompilation( CSharpCompilation compilation, PEDeltaAssemblyBuilder moduleBeingBuilt) { var previousGeneration = moduleBeingBuilt.PreviousGeneration; RoslynDebug.Assert(previousGeneration.Compilation != compilation); if (previousGeneration.Ordinal == 0) { // Initial generation, nothing to map. (Since the initial generation // is always loaded from metadata in the context of the current // compilation, there's no separate mapping step.) return previousGeneration; } RoslynDebug.AssertNotNull(previousGeneration.Compilation); RoslynDebug.AssertNotNull(previousGeneration.PEModuleBuilder); var currentSynthesizedMembers = moduleBeingBuilt.GetAllSynthesizedMembers(); // Mapping from previous compilation to the current. var anonymousTypeMap = moduleBeingBuilt.GetAnonymousTypeMap(); var synthesizedDelegates = moduleBeingBuilt.GetSynthesizedDelegates(); var sourceAssembly = ((CSharpCompilation)previousGeneration.Compilation).SourceAssembly; var sourceContext = new EmitContext((PEModuleBuilder)previousGeneration.PEModuleBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var otherContext = new EmitContext(moduleBeingBuilt, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var matcher = new CSharpSymbolMatcher( anonymousTypeMap, synthesizedDelegates, sourceAssembly, sourceContext, compilation.SourceAssembly, otherContext, currentSynthesizedMembers); var mappedSynthesizedMembers = matcher.MapSynthesizedMembers(previousGeneration.SynthesizedMembers, currentSynthesizedMembers); // TODO: can we reuse some data from the previous matcher? var matcherWithAllSynthesizedMembers = new CSharpSymbolMatcher( anonymousTypeMap, synthesizedDelegates, sourceAssembly, sourceContext, compilation.SourceAssembly, otherContext, mappedSynthesizedMembers); return matcherWithAllSynthesizedMembers.MapBaselineToCompilation( previousGeneration, compilation, moduleBeingBuilt, mappedSynthesizedMembers); } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Portable/Emitter/EditAndContinue/PEDeltaAssemblyBuilder.cs
// 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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class PEDeltaAssemblyBuilder : PEAssemblyBuilderBase, IPEDeltaAssemblyBuilder { private readonly EmitBaseline _previousGeneration; private readonly CSharpDefinitionMap _previousDefinitions; private readonly SymbolChanges _changes; private readonly CSharpSymbolMatcher.DeepTranslator _deepTranslator; public PEDeltaAssemblyBuilder( SourceAssemblySymbol sourceAssembly, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources, EmitBaseline previousGeneration, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol) : base(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, additionalTypes: ImmutableArray<NamedTypeSymbol>.Empty) { var initialBaseline = previousGeneration.InitialBaseline; var context = new EmitContext(this, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); // Hydrate symbols from initial metadata. Once we do so it is important to reuse these symbols across all generations, // in order for the symbol matcher to be able to use reference equality once it maps symbols to initial metadata. var metadataSymbols = GetOrCreateMetadataSymbols(initialBaseline, sourceAssembly.DeclaringCompilation); var metadataDecoder = (MetadataDecoder)metadataSymbols.MetadataDecoder; var metadataAssembly = (PEAssemblySymbol)metadataDecoder.ModuleSymbol.ContainingAssembly; var matchToMetadata = new CSharpSymbolMatcher(metadataSymbols.AnonymousTypes, sourceAssembly, context, metadataAssembly); CSharpSymbolMatcher? matchToPrevious = null; if (previousGeneration.Ordinal > 0) { RoslynDebug.AssertNotNull(previousGeneration.Compilation); RoslynDebug.AssertNotNull(previousGeneration.PEModuleBuilder); var previousAssembly = ((CSharpCompilation)previousGeneration.Compilation).SourceAssembly; var previousContext = new EmitContext((PEModuleBuilder)previousGeneration.PEModuleBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); matchToPrevious = new CSharpSymbolMatcher( previousGeneration.AnonymousTypeMap, sourceAssembly: sourceAssembly, sourceContext: context, otherAssembly: previousAssembly, otherContext: previousContext, otherSynthesizedMembersOpt: previousGeneration.SynthesizedMembers); } _previousDefinitions = new CSharpDefinitionMap(edits, metadataDecoder, matchToMetadata, matchToPrevious); _previousGeneration = previousGeneration; _changes = new CSharpSymbolChanges(_previousDefinitions, edits, isAddedSymbol); // Workaround for https://github.com/dotnet/roslyn/issues/3192. // When compiling state machine we stash types of awaiters and state-machine hoisted variables, // so that next generation can look variables up and reuse their slots if possible. // // When we are about to allocate a slot for a lifted variable while compiling the next generation // we map its type to the previous generation and then check the slot types that we stashed earlier. // If the variable type matches we reuse it. In order to compare the previous variable type with the current one // both need to be completely lowered (translated). Standard translation only goes one level deep. // Generic arguments are not translated until they are needed by metadata writer. // // In order to get the fully lowered form we run the type symbols of stashed variables through a deep translator // that translates the symbol recursively. _deepTranslator = new CSharpSymbolMatcher.DeepTranslator(sourceAssembly.GetSpecialType(SpecialType.System_Object)); } public override SymbolChanges? EncSymbolChanges => _changes; public override EmitBaseline PreviousGeneration => _previousGeneration; internal override Cci.ITypeReference EncTranslateLocalVariableType(TypeSymbol type, DiagnosticBag diagnostics) { // Note: The translator is not aware of synthesized types. If type is a synthesized type it won't get mapped. // In such case use the type itself. This can only happen for variables storing lambda display classes. var visited = (TypeSymbol)_deepTranslator.Visit(type); Debug.Assert((object)visited != null); //Debug.Assert(visited != null || type is LambdaFrame || ((NamedTypeSymbol)type).ConstructedFrom is LambdaFrame); return Translate(visited ?? type, null, diagnostics); } private static EmitBaseline.MetadataSymbols GetOrCreateMetadataSymbols(EmitBaseline initialBaseline, CSharpCompilation compilation) { if (initialBaseline.LazyMetadataSymbols != null) { return initialBaseline.LazyMetadataSymbols; } var originalMetadata = initialBaseline.OriginalMetadata; // The purpose of this compilation is to provide PE symbols for original metadata. // We need to transfer the references from the current source compilation but don't need its syntax trees. var metadataCompilation = compilation.RemoveAllSyntaxTrees(); ImmutableDictionary<AssemblyIdentity, AssemblyIdentity> assemblyReferenceIdentityMap; var metadataAssembly = metadataCompilation.GetBoundReferenceManager().CreatePEAssemblyForAssemblyMetadata(AssemblyMetadata.Create(originalMetadata), MetadataImportOptions.All, out assemblyReferenceIdentityMap); var metadataDecoder = new MetadataDecoder(metadataAssembly.PrimaryModule); var metadataAnonymousTypes = GetAnonymousTypeMapFromMetadata(originalMetadata.MetadataReader, metadataDecoder); var metadataSymbols = new EmitBaseline.MetadataSymbols(metadataAnonymousTypes, metadataDecoder, assemblyReferenceIdentityMap); return InterlockedOperations.Initialize(ref initialBaseline.LazyMetadataSymbols, metadataSymbols); } // internal for testing internal static IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> GetAnonymousTypeMapFromMetadata(MetadataReader reader, MetadataDecoder metadataDecoder) { // In general, the anonymous type name is "<{module-id}>f__AnonymousType{index}#{submission-index}", // but EnC is not supported for modules nor submissions. Hence we only look for type names with no module id and no submission index. const string AnonymousNameWithoutModulePrefix = "<>f__AnonymousType"; var result = new Dictionary<AnonymousTypeKey, AnonymousTypeValue>(); foreach (var handle in reader.TypeDefinitions) { var def = reader.GetTypeDefinition(handle); if (!def.Namespace.IsNil) { continue; } if (!reader.StringComparer.StartsWith(def.Name, AnonymousNameWithoutModulePrefix)) { continue; } var metadataName = reader.GetString(def.Name); var name = MetadataHelpers.InferTypeArityAndUnmangleMetadataName(metadataName, out _); if (name.StartsWith(AnonymousNameWithoutModulePrefix, StringComparison.Ordinal) && int.TryParse(name.Substring(AnonymousNameWithoutModulePrefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out int index)) { var builder = ArrayBuilder<AnonymousTypeKeyField>.GetInstance(); if (TryGetAnonymousTypeKey(reader, def, builder)) { var type = (NamedTypeSymbol)metadataDecoder.GetTypeOfToken(handle); var key = new AnonymousTypeKey(builder.ToImmutable()); var value = new AnonymousTypeValue(name, index, type.GetCciAdapter()); result.Add(key, value); } builder.Free(); } } return result; } private static bool TryGetAnonymousTypeKey( MetadataReader reader, TypeDefinition def, ArrayBuilder<AnonymousTypeKeyField> builder) { foreach (var typeParameterHandle in def.GetGenericParameters()) { var typeParameter = reader.GetGenericParameter(typeParameterHandle); if (!GeneratedNameParser.TryParseAnonymousTypeParameterName(reader.GetString(typeParameter.Name), out var fieldName)) { return false; } builder.Add(new AnonymousTypeKeyField(fieldName, isKey: false, ignoreCase: false)); } return true; } internal CSharpDefinitionMap PreviousDefinitions { get { return _previousDefinitions; } } internal override bool SupportsPrivateImplClass { get { // Disable <PrivateImplementationDetails> in ENC since the // CLR does not support adding non-private members. return false; } } public IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> GetAnonymousTypeMap() { var anonymousTypes = this.Compilation.AnonymousTypeManager.GetAnonymousTypeMap(); // Should contain all entries in previous generation. Debug.Assert(_previousGeneration.AnonymousTypeMap.All(p => anonymousTypes.ContainsKey(p.Key))); return anonymousTypes; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitions(EmitContext context) { foreach (var typeDef in GetAnonymousTypeDefinitions(context)) { yield return typeDef; } foreach (var typeDef in GetTopLevelTypeDefinitionsCore(context)) { yield return typeDef; } } public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context) { return _changes.GetTopLevelSourceTypeDefinitions(context); } internal override VariableSlotAllocator? TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics) { return _previousDefinitions.TryCreateVariableSlotAllocator(_previousGeneration, Compilation, method, topLevelMethod, diagnostics); } internal override ImmutableArray<AnonymousTypeKey> GetPreviousAnonymousTypes() { return ImmutableArray.CreateRange(_previousGeneration.AnonymousTypeMap.Keys); } internal override int GetNextAnonymousTypeIndex() { return _previousGeneration.GetNextAnonymousTypeIndex(); } internal override bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, [NotNullWhen(true)] out string? name, out int index) { Debug.Assert(this.Compilation == template.DeclaringCompilation); return _previousDefinitions.TryGetAnonymousTypeName(template, out name, out index); } public void OnCreatedIndices(DiagnosticBag diagnostics) { var embeddedTypesManager = this.EmbeddedTypesManagerOpt; if (embeddedTypesManager != null) { foreach (var embeddedType in embeddedTypesManager.EmbeddedTypesMap.Keys) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_EncNoPIAReference, embeddedType.AdaptedSymbol), Location.None); } } } } }
// 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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class PEDeltaAssemblyBuilder : PEAssemblyBuilderBase, IPEDeltaAssemblyBuilder { private readonly EmitBaseline _previousGeneration; private readonly CSharpDefinitionMap _previousDefinitions; private readonly SymbolChanges _changes; private readonly CSharpSymbolMatcher.DeepTranslator _deepTranslator; public PEDeltaAssemblyBuilder( SourceAssemblySymbol sourceAssembly, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources, EmitBaseline previousGeneration, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol) : base(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, additionalTypes: ImmutableArray<NamedTypeSymbol>.Empty) { var initialBaseline = previousGeneration.InitialBaseline; var context = new EmitContext(this, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); // Hydrate symbols from initial metadata. Once we do so it is important to reuse these symbols across all generations, // in order for the symbol matcher to be able to use reference equality once it maps symbols to initial metadata. var metadataSymbols = GetOrCreateMetadataSymbols(initialBaseline, sourceAssembly.DeclaringCompilation); var metadataDecoder = (MetadataDecoder)metadataSymbols.MetadataDecoder; var metadataAssembly = (PEAssemblySymbol)metadataDecoder.ModuleSymbol.ContainingAssembly; var matchToMetadata = new CSharpSymbolMatcher(metadataSymbols.AnonymousTypes, metadataSymbols.SynthesizedDelegates, sourceAssembly, context, metadataAssembly); CSharpSymbolMatcher? matchToPrevious = null; if (previousGeneration.Ordinal > 0) { RoslynDebug.AssertNotNull(previousGeneration.Compilation); RoslynDebug.AssertNotNull(previousGeneration.PEModuleBuilder); var previousAssembly = ((CSharpCompilation)previousGeneration.Compilation).SourceAssembly; var previousContext = new EmitContext((PEModuleBuilder)previousGeneration.PEModuleBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); matchToPrevious = new CSharpSymbolMatcher( previousGeneration.AnonymousTypeMap, previousGeneration.SynthesizedDelegates, sourceAssembly: sourceAssembly, sourceContext: context, otherAssembly: previousAssembly, otherContext: previousContext, otherSynthesizedMembersOpt: previousGeneration.SynthesizedMembers); } _previousDefinitions = new CSharpDefinitionMap(edits, metadataDecoder, matchToMetadata, matchToPrevious); _previousGeneration = previousGeneration; _changes = new CSharpSymbolChanges(_previousDefinitions, edits, isAddedSymbol); // Workaround for https://github.com/dotnet/roslyn/issues/3192. // When compiling state machine we stash types of awaiters and state-machine hoisted variables, // so that next generation can look variables up and reuse their slots if possible. // // When we are about to allocate a slot for a lifted variable while compiling the next generation // we map its type to the previous generation and then check the slot types that we stashed earlier. // If the variable type matches we reuse it. In order to compare the previous variable type with the current one // both need to be completely lowered (translated). Standard translation only goes one level deep. // Generic arguments are not translated until they are needed by metadata writer. // // In order to get the fully lowered form we run the type symbols of stashed variables through a deep translator // that translates the symbol recursively. _deepTranslator = new CSharpSymbolMatcher.DeepTranslator(sourceAssembly.GetSpecialType(SpecialType.System_Object)); } public override SymbolChanges? EncSymbolChanges => _changes; public override EmitBaseline PreviousGeneration => _previousGeneration; internal override Cci.ITypeReference EncTranslateLocalVariableType(TypeSymbol type, DiagnosticBag diagnostics) { // Note: The translator is not aware of synthesized types. If type is a synthesized type it won't get mapped. // In such case use the type itself. This can only happen for variables storing lambda display classes. var visited = (TypeSymbol)_deepTranslator.Visit(type); Debug.Assert((object)visited != null); //Debug.Assert(visited != null || type is LambdaFrame || ((NamedTypeSymbol)type).ConstructedFrom is LambdaFrame); return Translate(visited ?? type, null, diagnostics); } private static EmitBaseline.MetadataSymbols GetOrCreateMetadataSymbols(EmitBaseline initialBaseline, CSharpCompilation compilation) { if (initialBaseline.LazyMetadataSymbols != null) { return initialBaseline.LazyMetadataSymbols; } var originalMetadata = initialBaseline.OriginalMetadata; // The purpose of this compilation is to provide PE symbols for original metadata. // We need to transfer the references from the current source compilation but don't need its syntax trees. var metadataCompilation = compilation.RemoveAllSyntaxTrees(); ImmutableDictionary<AssemblyIdentity, AssemblyIdentity> assemblyReferenceIdentityMap; var metadataAssembly = metadataCompilation.GetBoundReferenceManager().CreatePEAssemblyForAssemblyMetadata(AssemblyMetadata.Create(originalMetadata), MetadataImportOptions.All, out assemblyReferenceIdentityMap); var metadataDecoder = new MetadataDecoder(metadataAssembly.PrimaryModule); var metadataAnonymousTypes = GetAnonymousTypeMapFromMetadata(originalMetadata.MetadataReader, metadataDecoder); var metadataSynthesizedDelegates = GetSynthesizedDelegateMapFromMetadata(originalMetadata.MetadataReader, metadataDecoder); var metadataSymbols = new EmitBaseline.MetadataSymbols(metadataAnonymousTypes, metadataSynthesizedDelegates, metadataDecoder, assemblyReferenceIdentityMap); return InterlockedOperations.Initialize(ref initialBaseline.LazyMetadataSymbols, metadataSymbols); } // internal for testing internal static IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> GetAnonymousTypeMapFromMetadata(MetadataReader reader, MetadataDecoder metadataDecoder) { // In general, the anonymous type name is "<{module-id}>f__AnonymousType{index}#{submission-index}", // but EnC is not supported for modules nor submissions. Hence we only look for type names with no module id and no submission index. const string AnonymousNameWithoutModulePrefix = "<>f__AnonymousType"; var result = new Dictionary<AnonymousTypeKey, AnonymousTypeValue>(); foreach (var handle in reader.TypeDefinitions) { var def = reader.GetTypeDefinition(handle); if (!def.Namespace.IsNil) { continue; } if (!reader.StringComparer.StartsWith(def.Name, AnonymousNameWithoutModulePrefix)) { continue; } var metadataName = reader.GetString(def.Name); var name = MetadataHelpers.InferTypeArityAndUnmangleMetadataName(metadataName, out _); if (name.StartsWith(AnonymousNameWithoutModulePrefix, StringComparison.Ordinal) && int.TryParse(name.Substring(AnonymousNameWithoutModulePrefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out int index)) { var builder = ArrayBuilder<AnonymousTypeKeyField>.GetInstance(); if (TryGetAnonymousTypeKey(reader, def, builder)) { var type = (NamedTypeSymbol)metadataDecoder.GetTypeOfToken(handle); var key = new AnonymousTypeKey(builder.ToImmutable()); var value = new AnonymousTypeValue(name, index, type.GetCciAdapter()); result.Add(key, value); } builder.Free(); } } return result; } // internal for testing internal static IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> GetSynthesizedDelegateMapFromMetadata(MetadataReader reader, MetadataDecoder metadataDecoder) { var result = new Dictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>(); foreach (var handle in reader.TypeDefinitions) { var def = reader.GetTypeDefinition(handle); if (!def.Namespace.IsNil) { continue; } if (!reader.StringComparer.StartsWith(def.Name, GeneratedNames.ActionDelegateNamePrefix) && !reader.StringComparer.StartsWith(def.Name, GeneratedNames.FuncDelegateNamePrefix)) { continue; } // The name of a synthesized delegate neatly encodes everything we need to identify it, either // in the prefix (return void or not) or the name (ref kinds and arity) so we don't need anything // fancy for a key. var metadataName = reader.GetString(def.Name); var key = new SynthesizedDelegateKey(metadataName); var type = (NamedTypeSymbol)metadataDecoder.GetTypeOfToken(handle); var value = new SynthesizedDelegateValue(type.GetCciAdapter()); result.Add(key, value); } return result; } private static bool TryGetAnonymousTypeKey( MetadataReader reader, TypeDefinition def, ArrayBuilder<AnonymousTypeKeyField> builder) { foreach (var typeParameterHandle in def.GetGenericParameters()) { var typeParameter = reader.GetGenericParameter(typeParameterHandle); if (!GeneratedNameParser.TryParseAnonymousTypeParameterName(reader.GetString(typeParameter.Name), out var fieldName)) { return false; } builder.Add(new AnonymousTypeKeyField(fieldName, isKey: false, ignoreCase: false)); } return true; } internal CSharpDefinitionMap PreviousDefinitions { get { return _previousDefinitions; } } internal override bool SupportsPrivateImplClass { get { // Disable <PrivateImplementationDetails> in ENC since the // CLR does not support adding non-private members. return false; } } public IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> GetAnonymousTypeMap() { var anonymousTypes = this.Compilation.AnonymousTypeManager.GetAnonymousTypeMap(); // Should contain all entries in previous generation. Debug.Assert(_previousGeneration.AnonymousTypeMap.All(p => anonymousTypes.ContainsKey(p.Key))); return anonymousTypes; } public IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> GetSynthesizedDelegates() { var synthesizedDelegates = this.Compilation.AnonymousTypeManager.GetSynthesizedDelegates(); // Should contain all entries in previous generation. Debug.Assert(_previousGeneration.SynthesizedDelegates.All(p => synthesizedDelegates.ContainsKey(p.Key))); return synthesizedDelegates; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitions(EmitContext context) { foreach (var typeDef in GetAnonymousTypeDefinitions(context)) { yield return typeDef; } foreach (var typeDef in GetTopLevelTypeDefinitionsCore(context)) { yield return typeDef; } } public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context) { return _changes.GetTopLevelSourceTypeDefinitions(context); } internal override VariableSlotAllocator? TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics) { return _previousDefinitions.TryCreateVariableSlotAllocator(_previousGeneration, Compilation, method, topLevelMethod, diagnostics); } internal override ImmutableArray<AnonymousTypeKey> GetPreviousAnonymousTypes() { return ImmutableArray.CreateRange(_previousGeneration.AnonymousTypeMap.Keys); } internal override ImmutableArray<SynthesizedDelegateKey> GetPreviousSynthesizedDelegates() { return ImmutableArray.CreateRange(_previousGeneration.SynthesizedDelegates.Keys); } internal override int GetNextAnonymousTypeIndex() { return _previousGeneration.GetNextAnonymousTypeIndex(); } internal override bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, [NotNullWhen(true)] out string? name, out int index) { Debug.Assert(this.Compilation == template.DeclaringCompilation); return _previousDefinitions.TryGetAnonymousTypeName(template, out name, out index); } public void OnCreatedIndices(DiagnosticBag diagnostics) { var embeddedTypesManager = this.EmbeddedTypesManagerOpt; if (embeddedTypesManager != null) { foreach (var embeddedType in embeddedTypesManager.EmbeddedTypesMap.Keys) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_EncNoPIAReference, embeddedType.AdaptedSymbol), Location.None); } } } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Portable/Emitter/Model/PEModuleBuilder.cs
// 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. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.PortableExecutable; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal abstract class PEModuleBuilder : PEModuleBuilder<CSharpCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState> { // TODO: Need to estimate amount of elements for this map and pass that value to the constructor. protected readonly ConcurrentDictionary<Symbol, Cci.IModuleReference> AssemblyOrModuleSymbolToModuleRefMap = new ConcurrentDictionary<Symbol, Cci.IModuleReference>(); private readonly ConcurrentDictionary<Symbol, object> _genericInstanceMap = new ConcurrentDictionary<Symbol, object>(Symbols.SymbolEqualityComparer.ConsiderEverything); private readonly ConcurrentSet<TypeSymbol> _reportedErrorTypesMap = new ConcurrentSet<TypeSymbol>(); private readonly NoPia.EmbeddedTypesManager _embeddedTypesManagerOpt; public override NoPia.EmbeddedTypesManager EmbeddedTypesManagerOpt => _embeddedTypesManagerOpt; // Gives the name of this module (may not reflect the name of the underlying symbol). // See Assembly.MetadataName. private readonly string _metadataName; private ImmutableArray<Cci.ExportedType> _lazyExportedTypes; /// <summary> /// The compiler-generated implementation type for each fixed-size buffer. /// </summary> private Dictionary<FieldSymbol, NamedTypeSymbol> _fixedImplementationTypes; private int _needsGeneratedAttributes; private bool _needsGeneratedAttributes_IsFrozen; /// <summary> /// Returns a value indicating which embedded attributes should be generated during emit phase. /// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it. /// Freezing is needed to make sure that nothing tries to modify the value after the value is read. /// </summary> internal EmbeddableAttributes GetNeedsGeneratedAttributes() { _needsGeneratedAttributes_IsFrozen = true; return GetNeedsGeneratedAttributesInternal(); } private EmbeddableAttributes GetNeedsGeneratedAttributesInternal() { return (EmbeddableAttributes)_needsGeneratedAttributes | Compilation.GetNeedsGeneratedAttributes(); } private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes); } internal PEModuleBuilder( SourceModuleSymbol sourceModule, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources) : base(sourceModule.ContainingSourceAssembly.DeclaringCompilation, sourceModule, serializationProperties, manifestResources, outputKind, emitOptions, new ModuleCompilationState()) { var specifiedName = sourceModule.MetadataName; _metadataName = specifiedName != Microsoft.CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName ? specifiedName : emitOptions.OutputNameOverride ?? specifiedName; AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, this); if (sourceModule.AnyReferencedAssembliesAreLinked) { _embeddedTypesManagerOpt = new NoPia.EmbeddedTypesManager(this); } } public override string Name { get { return _metadataName; } } internal sealed override string ModuleName { get { return _metadataName; } } internal sealed override Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor) { return Compilation.TrySynthesizeAttribute(attributeConstructor); } public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly) { return SourceModule.ContainingSourceAssembly .GetCustomAttributesToEmit(this, isRefAssembly, emittingAssemblyAttributesInNetModule: OutputKind.IsNetModule()); } public sealed override IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes() { return SourceModule.ContainingSourceAssembly.GetSecurityAttributes(); } public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes() { return SourceModule.GetCustomAttributesToEmit(this); } internal sealed override AssemblySymbol CorLibrary { get { return SourceModule.ContainingSourceAssembly.CorLibrary; } } public sealed override bool GenerateVisualBasicStylePdb => false; // C# doesn't emit linked assembly names into PDBs. public sealed override IEnumerable<string> LinkedAssembliesDebugInfo => SpecializedCollections.EmptyEnumerable<string>(); // C# currently doesn't emit compilation level imports (TODO: scripting). public sealed override ImmutableArray<Cci.UsedNamespaceOrType> GetImports() => ImmutableArray<Cci.UsedNamespaceOrType>.Empty; // C# doesn't allow to define default namespace for compilation. public sealed override string DefaultNamespace => null; protected sealed override IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics) { ImmutableArray<ModuleSymbol> modules = SourceModule.ContainingAssembly.Modules; for (int i = 1; i < modules.Length; i++) { foreach (AssemblySymbol aRef in modules[i].GetReferencedAssemblySymbols()) { yield return Translate(aRef, diagnostics); } } } private void ValidateReferencedAssembly(AssemblySymbol assembly, AssemblyReference asmRef, DiagnosticBag diagnostics) { AssemblyIdentity asmIdentity = SourceModule.ContainingAssembly.Identity; AssemblyIdentity refIdentity = asmRef.Identity; if (asmIdentity.IsStrongName && !refIdentity.IsStrongName && asmRef.Identity.ContentType != AssemblyContentType.WindowsRuntime) { // Dev12 reported error, we have changed it to a warning to allow referencing libraries // built for platforms that don't support strong names. diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton); } if (OutputKind != OutputKind.NetModule && !string.IsNullOrEmpty(refIdentity.CultureName) && !string.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase)) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton); } var refMachine = assembly.Machine; // If other assembly is agnostic this is always safe // Also, if no mscorlib was specified for back compat we add a reference to mscorlib // that resolves to the current framework directory. If the compiler is 64-bit // this is a 64-bit mscorlib, which will produce a warning if /platform:x86 is // specified. A reference to the default mscorlib should always succeed without // warning so we ignore it here. if ((object)assembly != (object)assembly.CorLibrary && !(refMachine == Machine.I386 && !assembly.Bit32Required)) { var machine = SourceModule.Machine; if (!(machine == Machine.I386 && !SourceModule.Bit32Required) && machine != refMachine) { // Different machine types, and neither is agnostic diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton); } } if (_embeddedTypesManagerOpt != null && _embeddedTypesManagerOpt.IsFrozen) { _embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics); } } internal sealed override IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(NamedTypeSymbol container) { return null; } public sealed override MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap() { var result = new MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation>(); var namespacesAndTypesToProcess = new Stack<NamespaceOrTypeSymbol>(); namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace); Location location = null; while (namespacesAndTypesToProcess.Count > 0) { NamespaceOrTypeSymbol symbol = namespacesAndTypesToProcess.Pop(); switch (symbol.Kind) { case SymbolKind.Namespace: location = GetSmallestSourceLocationOrNull(symbol); // filtering out synthesized symbols not having real source // locations such as anonymous types, etc... if (location != null) { foreach (var member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.Namespace: case SymbolKind.NamedType: namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member); break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } break; case SymbolKind.NamedType: location = GetSmallestSourceLocationOrNull(symbol); if (location != null) { // add this named type location AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter()); foreach (var member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.NamedType: namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member); break; case SymbolKind.Method: // NOTE: Dev11 does not add synthesized static constructors to this map, // but adds synthesized instance constructors, Roslyn adds both var method = (MethodSymbol)member; if (!method.ShouldEmit()) { break; } AddSymbolLocation(result, member); break; case SymbolKind.Property: AddSymbolLocation(result, member); break; case SymbolKind.Field: if (member is TupleErrorFieldSymbol) { break; } // NOTE: Dev11 does not add synthesized backing fields for properties, // but adds backing fields for events, Roslyn adds both AddSymbolLocation(result, member); break; case SymbolKind.Event: AddSymbolLocation(result, member); // event backing fields do not show up in GetMembers { FieldSymbol field = ((EventSymbol)member).AssociatedField; if ((object)field != null) { AddSymbolLocation(result, field); } } break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } break; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } return result; } private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Symbol symbol) { var location = GetSmallestSourceLocationOrNull(symbol); if (location != null) { AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter()); } } private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Location location, Cci.IDefinition definition) { FileLinePositionSpan span = location.GetLineSpan(); Cci.DebugSourceDocument doc = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath: location.SourceTree.FilePath); if (doc != null) { result.Add(doc, new Cci.DefinitionWithLocation( definition, span.StartLinePosition.Line, span.StartLinePosition.Character, span.EndLinePosition.Line, span.EndLinePosition.Character)); } } private Location GetSmallestSourceLocationOrNull(Symbol symbol) { CSharpCompilation compilation = symbol.DeclaringCompilation; Debug.Assert(Compilation == compilation, "How did we get symbol from different compilation?"); Location result = null; foreach (var loc in symbol.Locations) { if (loc.IsInSource && (result == null || compilation.CompareSourceLocations(result, loc) > 0)) { result = loc; } } return result; } /// <summary> /// Ignore accessibility when resolving well-known type /// members, in particular for generic type arguments /// (e.g.: binding to internal types in the EE). /// </summary> internal virtual bool IgnoreAccessibility => false; /// <summary> /// Override the dynamic operation context type for all dynamic calls in the module. /// </summary> internal virtual NamedTypeSymbol GetDynamicOperationContextType(NamedTypeSymbol contextType) { return contextType; } internal virtual VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics) { return null; } internal virtual ImmutableArray<AnonymousTypeKey> GetPreviousAnonymousTypes() { return ImmutableArray<AnonymousTypeKey>.Empty; } internal virtual int GetNextAnonymousTypeIndex() { return 0; } internal virtual bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, out string name, out int index) { Debug.Assert(Compilation == template.DeclaringCompilation); name = null; index = -1; return false; } public sealed override IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context) { if (context.MetadataOnly) { return SpecializedCollections.EmptyEnumerable<Cci.INamespaceTypeDefinition>(); } return Compilation.AnonymousTypeManager.GetAllCreatedTemplates() #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context) { var namespacesToProcess = new Stack<NamespaceSymbol>(); namespacesToProcess.Push(SourceModule.GlobalNamespace); while (namespacesToProcess.Count > 0) { var ns = namespacesToProcess.Pop(); foreach (var member in ns.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { namespacesToProcess.Push((NamespaceSymbol)member); } else { yield return ((NamedTypeSymbol)member).GetCciAdapter(); } } } } private static void GetExportedTypes(NamespaceOrTypeSymbol symbol, int parentIndex, ArrayBuilder<Cci.ExportedType> builder) { int index; if (symbol.Kind == SymbolKind.NamedType) { if (symbol.DeclaredAccessibility != Accessibility.Public) { return; } Debug.Assert(symbol.IsDefinition); index = builder.Count; builder.Add(new Cci.ExportedType((Cci.ITypeReference)symbol.GetCciAdapter(), parentIndex, isForwarder: false)); } else { index = -1; } foreach (var member in symbol.GetMembers()) { var namespaceOrType = member as NamespaceOrTypeSymbol; if ((object)namespaceOrType != null) { GetExportedTypes(namespaceOrType, index, builder); } } } public sealed override ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics) { Debug.Assert(HaveDeterminedTopLevelTypes); if (_lazyExportedTypes.IsDefault) { _lazyExportedTypes = CalculateExportedTypes(); if (_lazyExportedTypes.Length > 0) { ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics); } } return _lazyExportedTypes; } /// <summary> /// Builds an array of public type symbols defined in netmodules included in the compilation /// and type forwarders defined in this compilation or any included netmodule (in this order). /// </summary> private ImmutableArray<Cci.ExportedType> CalculateExportedTypes() { SourceAssemblySymbol sourceAssembly = SourceModule.ContainingSourceAssembly; var builder = ArrayBuilder<Cci.ExportedType>.GetInstance(); if (!OutputKind.IsNetModule()) { var modules = sourceAssembly.Modules; for (int i = 1; i < modules.Length; i++) //NOTE: skipping modules[0] { GetExportedTypes(modules[i].GlobalNamespace, -1, builder); } } Debug.Assert(OutputKind.IsNetModule() == sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()); GetForwardedTypes(sourceAssembly, builder); return builder.ToImmutableAndFree(); } #nullable enable /// <summary> /// Returns a set of top-level forwarded types /// </summary> internal static HashSet<NamedTypeSymbol> GetForwardedTypes(SourceAssemblySymbol sourceAssembly, ArrayBuilder<Cci.ExportedType>? builder) { var seenTopLevelForwardedTypes = new HashSet<NamedTypeSymbol>(); GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder); if (!sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()) { GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder); } return seenTopLevelForwardedTypes; } #nullable disable private void ReportExportedTypeNameCollisions(ImmutableArray<Cci.ExportedType> exportedTypes, DiagnosticBag diagnostics) { var sourceAssembly = SourceModule.ContainingSourceAssembly; var exportedNamesMap = new Dictionary<string, NamedTypeSymbol>(StringOrdinalComparer.Instance); foreach (var exportedType in exportedTypes) { var type = (NamedTypeSymbol)exportedType.Type.GetInternalSymbol(); Debug.Assert(type.IsDefinition); if (!type.IsTopLevelType()) { continue; } // exported types are not emitted in EnC deltas (hence generation 0): string fullEmittedName = MetadataHelpers.BuildQualifiedName( ((Cci.INamespaceTypeReference)type.GetCciAdapter()).NamespaceName, Cci.MetadataWriter.GetMangledName(type.GetCciAdapter(), generation: 0)); // First check against types declared in the primary module if (ContainsTopLevelType(fullEmittedName)) { if ((object)type.ContainingAssembly == sourceAssembly) { diagnostics.Add(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule); } else { diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, type); } continue; } NamedTypeSymbol contender; // Now check against other exported types if (exportedNamesMap.TryGetValue(fullEmittedName, out contender)) { if ((object)type.ContainingAssembly == sourceAssembly) { // all exported types precede forwarded types, therefore contender cannot be a forwarded type. Debug.Assert(contender.ContainingAssembly == sourceAssembly); diagnostics.Add(ErrorCode.ERR_ExportedTypesConflict, NoLocation.Singleton, type, type.ContainingModule, contender, contender.ContainingModule); } else if ((object)contender.ContainingAssembly == sourceAssembly) { // Forwarded type conflicts with exported type diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingModule); } else { // Forwarded type conflicts with another forwarded type diagnostics.Add(ErrorCode.ERR_ForwardedTypesConflict, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingAssembly); } continue; } exportedNamesMap.Add(fullEmittedName, type); } } #nullable enable private static void GetForwardedTypes( HashSet<NamedTypeSymbol> seenTopLevelTypes, CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> wellKnownAttributeData, ArrayBuilder<Cci.ExportedType>? builder) { if (wellKnownAttributeData?.ForwardedTypes?.Count > 0) { // (type, index of the parent exported type in builder, or -1 if the type is a top-level type) var stack = ArrayBuilder<(NamedTypeSymbol type, int parentIndex)>.GetInstance(); // Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names. IEnumerable<NamedTypeSymbol> orderedForwardedTypes = wellKnownAttributeData.ForwardedTypes; if (builder is object) { orderedForwardedTypes = orderedForwardedTypes.OrderBy(t => t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); } foreach (NamedTypeSymbol forwardedType in orderedForwardedTypes) { NamedTypeSymbol originalDefinition = forwardedType.OriginalDefinition; Debug.Assert((object)originalDefinition.ContainingType == null, "How did a nested type get forwarded?"); // Since we need to allow multiple constructions of the same generic type at the source // level, we need to de-dup the original definitions before emitting. if (!seenTopLevelTypes.Add(originalDefinition)) continue; if (builder is object) { // Return all nested types. // Note the order: depth first, children in reverse order (to match dev10, not a requirement). Debug.Assert(stack.Count == 0); stack.Push((originalDefinition, -1)); while (stack.Count > 0) { var (type, parentIndex) = stack.Pop(); // In general, we don't want private types to appear in the ExportedTypes table. // BREAK: dev11 emits these types. The problem was discovered in dev10, but failed // to meet the bar Bug: Dev10/258038 and was left as-is. if (type.DeclaredAccessibility == Accessibility.Private) { // NOTE: this will also exclude nested types of type continue; } // NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection. int index = builder.Count; builder.Add(new Cci.ExportedType(type.GetCciAdapter(), parentIndex, isForwarder: true)); // Iterate backwards so they get popped in forward order. ImmutableArray<NamedTypeSymbol> nested = type.GetTypeMembers(); // Ordered. for (int i = nested.Length - 1; i >= 0; i--) { stack.Push((nested[i], index)); } } } } stack.Free(); } } #nullable disable internal IEnumerable<AssemblySymbol> GetReferencedAssembliesUsedSoFar() { foreach (AssemblySymbol a in SourceModule.GetReferencedAssemblySymbols()) { if (!a.IsLinked && !a.IsMissing && AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(a)) { yield return a; } } } private NamedTypeSymbol GetUntranslatedSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); var typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType); DiagnosticInfo info = typeSymbol.GetUseSiteInfo().DiagnosticInfo; if (info != null) { Symbol.ReportUseSiteDiagnostic(info, diagnostics, syntaxNodeOpt != null ? syntaxNodeOpt.Location : NoLocation.Singleton); } return typeSymbol; } internal sealed override Cci.INamedTypeReference GetSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics), diagnostics: diagnostics, syntaxNodeOpt: syntaxNodeOpt, needDeclaration: true); } public sealed override Cci.IMethodReference GetInitArrayHelper() { return ((MethodSymbol)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle))?.GetCciAdapter(); } public sealed override bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType) { var namedType = typeRef.GetInternalSymbol() as NamedTypeSymbol; if ((object)namedType != null) { if (platformType == Cci.PlatformType.SystemType) { return (object)namedType == (object)Compilation.GetWellKnownType(WellKnownType.System_Type); } return namedType.SpecialType == (SpecialType)platformType; } return false; } protected sealed override Cci.IAssemblyReference GetCorLibraryReferenceToEmit(CodeAnalysis.Emit.EmitContext context) { AssemblySymbol corLibrary = CorLibrary; if (!corLibrary.IsMissing && !corLibrary.IsLinked && !ReferenceEquals(corLibrary, SourceModule.ContainingAssembly)) { return Translate(corLibrary, context.Diagnostics); } return null; } internal sealed override Cci.IAssemblyReference Translate(AssemblySymbol assembly, DiagnosticBag diagnostics) { if (ReferenceEquals(SourceModule.ContainingAssembly, assembly)) { return (Cci.IAssemblyReference)this; } Cci.IModuleReference reference; if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(assembly, out reference)) { return (Cci.IAssemblyReference)reference; } AssemblyReference asmRef = new AssemblyReference(assembly); AssemblyReference cachedAsmRef = (AssemblyReference)AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(assembly, asmRef); if (cachedAsmRef == asmRef) { ValidateReferencedAssembly(assembly, cachedAsmRef, diagnostics); } // TryAdd because whatever is associated with assembly should be associated with Modules[0] AssemblyOrModuleSymbolToModuleRefMap.TryAdd(assembly.Modules[0], cachedAsmRef); return cachedAsmRef; } internal Cci.IModuleReference Translate(ModuleSymbol module, DiagnosticBag diagnostics) { if (ReferenceEquals(SourceModule, module)) { return this; } if ((object)module == null) { return null; } Cci.IModuleReference moduleRef; if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(module, out moduleRef)) { return moduleRef; } moduleRef = TranslateModule(module, diagnostics); moduleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(module, moduleRef); return moduleRef; } protected virtual Cci.IModuleReference TranslateModule(ModuleSymbol module, DiagnosticBag diagnostics) { AssemblySymbol container = module.ContainingAssembly; if ((object)container != null && ReferenceEquals(container.Modules[0], module)) { Cci.IModuleReference moduleRef = new AssemblyReference(container); Cci.IModuleReference cachedModuleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(container, moduleRef); if (cachedModuleRef == moduleRef) { ValidateReferencedAssembly(container, (AssemblyReference)moduleRef, diagnostics); } else { moduleRef = cachedModuleRef; } return moduleRef; } else { return new ModuleReference(this, module); } } internal Cci.INamedTypeReference Translate( NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool fromImplements = false, bool needDeclaration = false) { Debug.Assert(namedTypeSymbol.IsDefinitionOrDistinct()); Debug.Assert(diagnostics != null); // Anonymous type being translated if (namedTypeSymbol.IsAnonymousType) { Debug.Assert(!needDeclaration); namedTypeSymbol = AnonymousTypeManager.TranslateAnonymousTypeSymbol(namedTypeSymbol); } else if (namedTypeSymbol.IsTupleType) { CheckTupleUnderlyingType(namedTypeSymbol, syntaxNodeOpt, diagnostics); } // Substitute error types with a special singleton object. // Unreported bad types can come through NoPia embedding, for example. if (namedTypeSymbol.OriginalDefinition.Kind == SymbolKind.ErrorType) { ErrorTypeSymbol errorType = (ErrorTypeSymbol)namedTypeSymbol.OriginalDefinition; DiagnosticInfo diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo; if (diagInfo == null && namedTypeSymbol.Kind == SymbolKind.ErrorType) { errorType = (ErrorTypeSymbol)namedTypeSymbol; diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo; } // Try to decrease noise by not complaining about the same type over and over again. if (_reportedErrorTypesMap.Add(errorType)) { diagnostics.Add(new CSDiagnostic(diagInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty), syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location)); } return CodeAnalysis.Emit.ErrorType.Singleton; } if (!namedTypeSymbol.IsDefinition) { // generic instantiation for sure Debug.Assert(!needDeclaration); if (namedTypeSymbol.IsUnboundGenericType) { namedTypeSymbol = namedTypeSymbol.OriginalDefinition; } else { return (Cci.INamedTypeReference)GetCciAdapter(namedTypeSymbol); } } else if (!needDeclaration) { object reference; Cci.INamedTypeReference typeRef; NamedTypeSymbol container = namedTypeSymbol.ContainingType; if (namedTypeSymbol.Arity > 0) { if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference)) { return (Cci.INamedTypeReference)reference; } if ((object)container != null) { if (IsGenericType(container)) { // Container is a generic instance too. typeRef = new SpecializedGenericNestedTypeInstanceReference(namedTypeSymbol); } else { typeRef = new GenericNestedTypeInstanceReference(namedTypeSymbol); } } else { typeRef = new GenericNamespaceTypeInstanceReference(namedTypeSymbol); } typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef); return typeRef; } else if (IsGenericType(container)) { Debug.Assert((object)container != null); if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference)) { return (Cci.INamedTypeReference)reference; } typeRef = new SpecializedNestedTypeReference(namedTypeSymbol); typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef); return typeRef; } else if (namedTypeSymbol.NativeIntegerUnderlyingType is NamedTypeSymbol underlyingType) { namedTypeSymbol = underlyingType; } } // NoPia: See if this is a type, which definition we should copy into our assembly. Debug.Assert(namedTypeSymbol.IsDefinition); return _embeddedTypesManagerOpt?.EmbedTypeIfNeedTo(namedTypeSymbol, fromImplements, syntaxNodeOpt, diagnostics) ?? namedTypeSymbol.GetCciAdapter(); } private object GetCciAdapter(Symbol symbol) { return _genericInstanceMap.GetOrAdd(symbol, s => s.GetCciAdapter()); } private void CheckTupleUnderlyingType(NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { // check that underlying type of a ValueTuple is indeed a value type (or error) // this should never happen, in theory, // but if it does happen we should make it a failure. // NOTE: declaredBase could be null for interfaces var declaredBase = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics; if ((object)declaredBase != null && declaredBase.SpecialType == SpecialType.System_ValueType) { return; } // Try to decrease noise by not complaining about the same type over and over again. if (!_reportedErrorTypesMap.Add(namedTypeSymbol)) { return; } var location = syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location; if ((object)declaredBase != null) { var diagnosticInfo = declaredBase.GetUseSiteInfo().DiagnosticInfo; if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error) { diagnostics.Add(diagnosticInfo, location); return; } } diagnostics.Add( new CSDiagnostic( new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, namedTypeSymbol.MetadataName), location)); } public static bool IsGenericType(NamedTypeSymbol toCheck) { while ((object)toCheck != null) { if (toCheck.Arity > 0) { return true; } toCheck = toCheck.ContainingType; } return false; } internal static Cci.IGenericParameterReference Translate(TypeParameterSymbol param) { if (!param.IsDefinition) throw new InvalidOperationException(string.Format(CSharpResources.GenericParameterDefinition, param.Name)); return param.GetCciAdapter(); } internal sealed override Cci.ITypeReference Translate( TypeSymbol typeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); switch (typeSymbol.Kind) { case SymbolKind.DynamicType: return Translate((DynamicTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics); case SymbolKind.ArrayType: return Translate((ArrayTypeSymbol)typeSymbol); case SymbolKind.ErrorType: case SymbolKind.NamedType: return Translate((NamedTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics); case SymbolKind.PointerType: return Translate((PointerTypeSymbol)typeSymbol); case SymbolKind.TypeParameter: return Translate((TypeParameterSymbol)typeSymbol); case SymbolKind.FunctionPointerType: return Translate((FunctionPointerTypeSymbol)typeSymbol); } throw ExceptionUtilities.UnexpectedValue(typeSymbol.Kind); } internal Cci.IFieldReference Translate( FieldSymbol fieldSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration = false) { Debug.Assert(fieldSymbol.IsDefinitionOrDistinct()); Debug.Assert(!fieldSymbol.IsVirtualTupleField && (object)(fieldSymbol.TupleUnderlyingField ?? fieldSymbol) == fieldSymbol && fieldSymbol is not TupleErrorFieldSymbol, "tuple fields should be rewritten to underlying by now"); if (!fieldSymbol.IsDefinition) { Debug.Assert(!needDeclaration); return (Cci.IFieldReference)GetCciAdapter(fieldSymbol); } else if (!needDeclaration && IsGenericType(fieldSymbol.ContainingType)) { object reference; Cci.IFieldReference fieldRef; if (_genericInstanceMap.TryGetValue(fieldSymbol, out reference)) { return (Cci.IFieldReference)reference; } fieldRef = new SpecializedFieldReference(fieldSymbol); fieldRef = (Cci.IFieldReference)_genericInstanceMap.GetOrAdd(fieldSymbol, fieldRef); return fieldRef; } return _embeddedTypesManagerOpt?.EmbedFieldIfNeedTo(fieldSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics) ?? fieldSymbol.GetCciAdapter(); } public static Cci.TypeMemberVisibility MemberVisibility(Symbol symbol) { // // We need to relax visibility of members in interactive submissions since they might be emitted into multiple assemblies. // // Top-level: // private -> public // protected -> public (compiles with a warning) // public // internal -> public // // In a nested class: // // private // protected // public // internal -> public // switch (symbol.DeclaredAccessibility) { case Accessibility.Public: return Cci.TypeMemberVisibility.Public; case Accessibility.Private: if (symbol.ContainingType?.TypeKind == TypeKind.Submission) { // top-level private member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Private; } case Accessibility.Internal: if (symbol.ContainingAssembly.IsInteractive) { // top-level or nested internal member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Assembly; } case Accessibility.Protected: if (symbol.ContainingType.TypeKind == TypeKind.Submission) { // top-level protected member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Family; } case Accessibility.ProtectedAndInternal: Debug.Assert(symbol.ContainingType.TypeKind != TypeKind.Submission); return Cci.TypeMemberVisibility.FamilyAndAssembly; case Accessibility.ProtectedOrInternal: if (symbol.ContainingAssembly.IsInteractive) { // top-level or nested protected internal member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.FamilyOrAssembly; } default: throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility); } } internal sealed override Cci.IMethodReference Translate(MethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration) { return Translate(symbol, null, diagnostics, null, needDeclaration); } internal Cci.IMethodReference Translate( MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, BoundArgListOperator optArgList = null, bool needDeclaration = false) { Debug.Assert(!methodSymbol.IsDefaultValueTypeConstructor(requireZeroInit: true)); Debug.Assert(optArgList == null || (methodSymbol.IsVararg && !needDeclaration)); Cci.IMethodReference unexpandedMethodRef = Translate(methodSymbol, syntaxNodeOpt, diagnostics, needDeclaration); if (optArgList != null && optArgList.Arguments.Length > 0) { Cci.IParameterTypeInformation[] @params = new Cci.IParameterTypeInformation[optArgList.Arguments.Length]; int ordinal = methodSymbol.ParameterCount; for (int i = 0; i < @params.Length; i++) { @params[i] = new ArgListParameterTypeInformation(ordinal, !optArgList.ArgumentRefKindsOpt.IsDefaultOrEmpty && optArgList.ArgumentRefKindsOpt[i] != RefKind.None, Translate(optArgList.Arguments[i].Type, syntaxNodeOpt, diagnostics)); ordinal++; } return new ExpandedVarargsMethodReference(unexpandedMethodRef, @params.AsImmutableOrNull()); } else { return unexpandedMethodRef; } } private Cci.IMethodReference Translate( MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration) { object reference; Cci.IMethodReference methodRef; NamedTypeSymbol container = methodSymbol.ContainingType; // Method of anonymous type being translated if (container.IsAnonymousType) { Debug.Assert(!needDeclaration); methodSymbol = AnonymousTypeManager.TranslateAnonymousTypeMethodSymbol(methodSymbol); } Debug.Assert(methodSymbol.IsDefinitionOrDistinct()); if (!methodSymbol.IsDefinition) { Debug.Assert(!needDeclaration); Debug.Assert(!(methodSymbol.OriginalDefinition is NativeIntegerMethodSymbol)); Debug.Assert(!(methodSymbol.ConstructedFrom is NativeIntegerMethodSymbol)); return (Cci.IMethodReference)GetCciAdapter(methodSymbol); } else if (!needDeclaration) { bool methodIsGeneric = methodSymbol.IsGenericMethod; bool typeIsGeneric = IsGenericType(container); if (methodIsGeneric || typeIsGeneric) { if (_genericInstanceMap.TryGetValue(methodSymbol, out reference)) { return (Cci.IMethodReference)reference; } if (methodIsGeneric) { if (typeIsGeneric) { // Specialized and generic instance at the same time. methodRef = new SpecializedGenericMethodInstanceReference(methodSymbol); } else { methodRef = new GenericMethodInstanceReference(methodSymbol); } } else { Debug.Assert(typeIsGeneric); methodRef = new SpecializedMethodReference(methodSymbol); } methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef); return methodRef; } else if (methodSymbol is NativeIntegerMethodSymbol { UnderlyingMethod: MethodSymbol underlyingMethod }) { methodSymbol = underlyingMethod; } } if (_embeddedTypesManagerOpt != null) { return _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics); } return methodSymbol.GetCciAdapter(); } internal Cci.IMethodReference TranslateOverriddenMethodReference( MethodSymbol methodSymbol, CSharpSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Cci.IMethodReference methodRef; NamedTypeSymbol container = methodSymbol.ContainingType; if (IsGenericType(container)) { if (methodSymbol.IsDefinition) { object reference; if (_genericInstanceMap.TryGetValue(methodSymbol, out reference)) { methodRef = (Cci.IMethodReference)reference; } else { methodRef = new SpecializedMethodReference(methodSymbol); methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef); } } else { methodRef = new SpecializedMethodReference(methodSymbol); } } else { Debug.Assert(methodSymbol.IsDefinition); if (_embeddedTypesManagerOpt != null) { methodRef = _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics); } else { methodRef = methodSymbol.GetCciAdapter(); } } return methodRef; } internal ImmutableArray<Cci.IParameterTypeInformation> Translate(ImmutableArray<ParameterSymbol> @params) { Debug.Assert(@params.All(p => p.IsDefinitionOrDistinct())); bool mustBeTranslated = @params.Any() && MustBeWrapped(@params.First()); Debug.Assert(@params.All(p => mustBeTranslated == MustBeWrapped(p)), "either all or no parameters need translating"); if (!mustBeTranslated) { #if DEBUG return @params.SelectAsArray<ParameterSymbol, Cci.IParameterTypeInformation>(p => p.GetCciAdapter()); #else return StaticCast<Cci.IParameterTypeInformation>.From(@params); #endif } return TranslateAll(@params); } private static bool MustBeWrapped(ParameterSymbol param) { // we represent parameters of generic methods as definitions // CCI wants them represented as IParameterTypeInformation // so we need to create a wrapper of parameters iff // 1) parameters are definitions and // 2) container is generic // NOTE: all parameters must always agree on whether they need wrapping if (param.IsDefinition) { var container = param.ContainingSymbol; if (ContainerIsGeneric(container)) { return true; } } return false; } private ImmutableArray<Cci.IParameterTypeInformation> TranslateAll(ImmutableArray<ParameterSymbol> @params) { var builder = ArrayBuilder<Cci.IParameterTypeInformation>.GetInstance(); foreach (var param in @params) { builder.Add(CreateParameterTypeInformationWrapper(param)); } return builder.ToImmutableAndFree(); } private Cci.IParameterTypeInformation CreateParameterTypeInformationWrapper(ParameterSymbol param) { object reference; Cci.IParameterTypeInformation paramRef; if (_genericInstanceMap.TryGetValue(param, out reference)) { return (Cci.IParameterTypeInformation)reference; } paramRef = new ParameterTypeInformation(param); paramRef = (Cci.IParameterTypeInformation)_genericInstanceMap.GetOrAdd(param, paramRef); return paramRef; } private static bool ContainerIsGeneric(Symbol container) { return container.Kind == SymbolKind.Method && ((MethodSymbol)container).IsGenericMethod || IsGenericType(container.ContainingType); } internal Cci.ITypeReference Translate( DynamicTypeSymbol symbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { // Translate the dynamic type to System.Object special type to avoid duplicate entries in TypeRef table. // We don't need to recursively replace the dynamic type with Object since the DynamicTypeSymbol adapter // masquerades the TypeRef as System.Object when used to encode signatures. return GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics); } internal Cci.IArrayTypeReference Translate(ArrayTypeSymbol symbol) { return (Cci.IArrayTypeReference)GetCciAdapter(symbol); } internal Cci.IPointerTypeReference Translate(PointerTypeSymbol symbol) { return (Cci.IPointerTypeReference)GetCciAdapter(symbol); } internal Cci.IFunctionPointerTypeReference Translate(FunctionPointerTypeSymbol symbol) { return (Cci.IFunctionPointerTypeReference)GetCciAdapter(symbol); } /// <summary> /// Set the underlying implementation type for a given fixed-size buffer field. /// </summary> public NamedTypeSymbol SetFixedImplementationType(SourceMemberFieldSymbol field) { if (_fixedImplementationTypes == null) { Interlocked.CompareExchange(ref _fixedImplementationTypes, new Dictionary<FieldSymbol, NamedTypeSymbol>(), null); } lock (_fixedImplementationTypes) { NamedTypeSymbol result; if (_fixedImplementationTypes.TryGetValue(field, out result)) { return result; } result = new FixedFieldImplementationType(field); _fixedImplementationTypes.Add(field, result); AddSynthesizedDefinition(result.ContainingType, result.GetCciAdapter()); return result; } } internal NamedTypeSymbol GetFixedImplementationType(FieldSymbol field) { // Note that this method is called only after ALL fixed buffer types have been placed in the map. // At that point the map is all filled in and will not change further. Therefore it is safe to // pull values from the map without locking. NamedTypeSymbol result; var found = _fixedImplementationTypes.TryGetValue(field, out result); Debug.Assert(found); return result; } protected override Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, SyntaxNode syntaxOpt, DiagnosticBag diagnostics) { return new SynthesizedPrivateImplementationDetailsStaticConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter(); } internal abstract SynthesizedAttributeData SynthesizeEmbeddedAttribute(); internal SynthesizedAttributeData SynthesizeIsReadOnlyAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsReadOnlyAttribute(); } internal SynthesizedAttributeData SynthesizeIsUnmanagedAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsUnmanagedAttribute(); } internal SynthesizedAttributeData SynthesizeIsByRefLikeAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsByRefLikeAttribute(); } /// <summary> /// Given a type <paramref name="type"/>, which is either a nullable reference type OR /// is a constructed type with a nullable reference type present in its type argument tree, /// returns a synthesized NullableAttribute with encoded nullable transforms array. /// </summary> internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(Symbol symbol, byte? nullableContextValue, TypeWithAnnotations type) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } var flagsBuilder = ArrayBuilder<byte>.GetInstance(); type.AddNullableTransforms(flagsBuilder); SynthesizedAttributeData attribute; if (!flagsBuilder.Any()) { attribute = null; } else { Debug.Assert(flagsBuilder.All(f => f <= 2)); byte? commonValue = MostCommonNullableValueBuilder.GetCommonValue(flagsBuilder); if (commonValue != null) { attribute = SynthesizeNullableAttributeIfNecessary(nullableContextValue, commonValue.GetValueOrDefault()); } else { NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte); var byteArrayType = ArrayTypeSymbol.CreateSZArray(byteType.ContainingAssembly, TypeWithAnnotations.Create(byteType)); var value = flagsBuilder.SelectAsArray((flag, byteType) => new TypedConstant(byteType, TypedConstantKind.Primitive, flag), byteType); attribute = SynthesizeNullableAttribute( WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags, ImmutableArray.Create(new TypedConstant(byteArrayType, value))); } } flagsBuilder.Free(); return attribute; } internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(byte? nullableContextValue, byte nullableValue) { if (nullableValue == nullableContextValue || (nullableContextValue == null && nullableValue == 0)) { return null; } NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte); return SynthesizeNullableAttribute( WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, ImmutableArray.Create(new TypedConstant(byteType, TypedConstantKind.Primitive, nullableValue))); } internal virtual SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizeNullableContextAttribute(Symbol symbol, byte value) { var module = Compilation.SourceModule; if ((object)module != symbol && (object)module != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return SynthesizeNullableContextAttribute( ImmutableArray.Create(new TypedConstant(Compilation.GetSpecialType(SpecialType.System_Byte), TypedConstantKind.Primitive, value))); } internal virtual SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, arguments, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizePreserveBaseOverridesAttribute() { return Compilation.TrySynthesizeAttribute(SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizeNativeIntegerAttribute(Symbol symbol, TypeSymbol type) { Debug.Assert((object)type != null); Debug.Assert(type.ContainsNativeInteger()); if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } var builder = ArrayBuilder<bool>.GetInstance(); CSharpCompilation.NativeIntegerTransformsEncoder.Encode(builder, type); Debug.Assert(builder.Any()); Debug.Assert(builder.Contains(true)); SynthesizedAttributeData attribute; if (builder.Count == 1 && builder[0]) { attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, ImmutableArray<TypedConstant>.Empty); } else { NamedTypeSymbol booleanType = Compilation.GetSpecialType(SpecialType.System_Boolean); Debug.Assert((object)booleanType != null); var transformFlags = builder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType); var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType)); var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags)); attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, arguments); } builder.Free(); return attribute; } internal virtual SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true); } internal bool ShouldEmitNullablePublicOnlyAttribute() { // No need to look at this.GetNeedsGeneratedAttributes() since those bits are // only set for members generated by the rewriter which are not public. return Compilation.GetUsesNullableAttributes() && Compilation.EmitNullablePublicOnly; } internal virtual SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, arguments); } protected virtual SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor); } protected virtual SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor); } protected virtual SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor); } private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); if ((GetNeedsGeneratedAttributesInternal() & attribute) != 0) { return; } // Don't report any errors. They should be reported during binding. if (Compilation.CheckIfAttributeShouldBeEmbedded(attribute, diagnosticsOpt: null, locationOpt: null)) { SetNeedsGeneratedAttributes(attribute); } } internal void EnsureIsReadOnlyAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute); } internal void EnsureIsUnmanagedAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute); } internal void EnsureNullableAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute); } internal void EnsureNullableContextAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableContextAttribute); } internal void EnsureNativeIntegerAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute); } public override IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context) { return GetAdditionalTopLevelTypes() #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context) { return GetEmbeddedTypes(context.Diagnostics) #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics) { return GetEmbeddedTypes(new BindingDiagnosticBag(diagnostics)); } internal virtual ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics) { return base.GetEmbeddedTypes(diagnostics.DiagnosticBag); } } }
// 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. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.PortableExecutable; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal abstract class PEModuleBuilder : PEModuleBuilder<CSharpCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState> { // TODO: Need to estimate amount of elements for this map and pass that value to the constructor. protected readonly ConcurrentDictionary<Symbol, Cci.IModuleReference> AssemblyOrModuleSymbolToModuleRefMap = new ConcurrentDictionary<Symbol, Cci.IModuleReference>(); private readonly ConcurrentDictionary<Symbol, object> _genericInstanceMap = new ConcurrentDictionary<Symbol, object>(Symbols.SymbolEqualityComparer.ConsiderEverything); private readonly ConcurrentSet<TypeSymbol> _reportedErrorTypesMap = new ConcurrentSet<TypeSymbol>(); private readonly NoPia.EmbeddedTypesManager _embeddedTypesManagerOpt; public override NoPia.EmbeddedTypesManager EmbeddedTypesManagerOpt => _embeddedTypesManagerOpt; // Gives the name of this module (may not reflect the name of the underlying symbol). // See Assembly.MetadataName. private readonly string _metadataName; private ImmutableArray<Cci.ExportedType> _lazyExportedTypes; /// <summary> /// The compiler-generated implementation type for each fixed-size buffer. /// </summary> private Dictionary<FieldSymbol, NamedTypeSymbol> _fixedImplementationTypes; private int _needsGeneratedAttributes; private bool _needsGeneratedAttributes_IsFrozen; /// <summary> /// Returns a value indicating which embedded attributes should be generated during emit phase. /// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it. /// Freezing is needed to make sure that nothing tries to modify the value after the value is read. /// </summary> internal EmbeddableAttributes GetNeedsGeneratedAttributes() { _needsGeneratedAttributes_IsFrozen = true; return GetNeedsGeneratedAttributesInternal(); } private EmbeddableAttributes GetNeedsGeneratedAttributesInternal() { return (EmbeddableAttributes)_needsGeneratedAttributes | Compilation.GetNeedsGeneratedAttributes(); } private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes); } internal PEModuleBuilder( SourceModuleSymbol sourceModule, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources) : base(sourceModule.ContainingSourceAssembly.DeclaringCompilation, sourceModule, serializationProperties, manifestResources, outputKind, emitOptions, new ModuleCompilationState()) { var specifiedName = sourceModule.MetadataName; _metadataName = specifiedName != Microsoft.CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName ? specifiedName : emitOptions.OutputNameOverride ?? specifiedName; AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, this); if (sourceModule.AnyReferencedAssembliesAreLinked) { _embeddedTypesManagerOpt = new NoPia.EmbeddedTypesManager(this); } } public override string Name { get { return _metadataName; } } internal sealed override string ModuleName { get { return _metadataName; } } internal sealed override Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor) { return Compilation.TrySynthesizeAttribute(attributeConstructor); } public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly) { return SourceModule.ContainingSourceAssembly .GetCustomAttributesToEmit(this, isRefAssembly, emittingAssemblyAttributesInNetModule: OutputKind.IsNetModule()); } public sealed override IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes() { return SourceModule.ContainingSourceAssembly.GetSecurityAttributes(); } public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes() { return SourceModule.GetCustomAttributesToEmit(this); } internal sealed override AssemblySymbol CorLibrary { get { return SourceModule.ContainingSourceAssembly.CorLibrary; } } public sealed override bool GenerateVisualBasicStylePdb => false; // C# doesn't emit linked assembly names into PDBs. public sealed override IEnumerable<string> LinkedAssembliesDebugInfo => SpecializedCollections.EmptyEnumerable<string>(); // C# currently doesn't emit compilation level imports (TODO: scripting). public sealed override ImmutableArray<Cci.UsedNamespaceOrType> GetImports() => ImmutableArray<Cci.UsedNamespaceOrType>.Empty; // C# doesn't allow to define default namespace for compilation. public sealed override string DefaultNamespace => null; protected sealed override IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics) { ImmutableArray<ModuleSymbol> modules = SourceModule.ContainingAssembly.Modules; for (int i = 1; i < modules.Length; i++) { foreach (AssemblySymbol aRef in modules[i].GetReferencedAssemblySymbols()) { yield return Translate(aRef, diagnostics); } } } private void ValidateReferencedAssembly(AssemblySymbol assembly, AssemblyReference asmRef, DiagnosticBag diagnostics) { AssemblyIdentity asmIdentity = SourceModule.ContainingAssembly.Identity; AssemblyIdentity refIdentity = asmRef.Identity; if (asmIdentity.IsStrongName && !refIdentity.IsStrongName && asmRef.Identity.ContentType != AssemblyContentType.WindowsRuntime) { // Dev12 reported error, we have changed it to a warning to allow referencing libraries // built for platforms that don't support strong names. diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton); } if (OutputKind != OutputKind.NetModule && !string.IsNullOrEmpty(refIdentity.CultureName) && !string.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase)) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton); } var refMachine = assembly.Machine; // If other assembly is agnostic this is always safe // Also, if no mscorlib was specified for back compat we add a reference to mscorlib // that resolves to the current framework directory. If the compiler is 64-bit // this is a 64-bit mscorlib, which will produce a warning if /platform:x86 is // specified. A reference to the default mscorlib should always succeed without // warning so we ignore it here. if ((object)assembly != (object)assembly.CorLibrary && !(refMachine == Machine.I386 && !assembly.Bit32Required)) { var machine = SourceModule.Machine; if (!(machine == Machine.I386 && !SourceModule.Bit32Required) && machine != refMachine) { // Different machine types, and neither is agnostic diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton); } } if (_embeddedTypesManagerOpt != null && _embeddedTypesManagerOpt.IsFrozen) { _embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics); } } internal sealed override IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(NamedTypeSymbol container) { return null; } public sealed override MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap() { var result = new MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation>(); var namespacesAndTypesToProcess = new Stack<NamespaceOrTypeSymbol>(); namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace); Location location = null; while (namespacesAndTypesToProcess.Count > 0) { NamespaceOrTypeSymbol symbol = namespacesAndTypesToProcess.Pop(); switch (symbol.Kind) { case SymbolKind.Namespace: location = GetSmallestSourceLocationOrNull(symbol); // filtering out synthesized symbols not having real source // locations such as anonymous types, etc... if (location != null) { foreach (var member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.Namespace: case SymbolKind.NamedType: namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member); break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } break; case SymbolKind.NamedType: location = GetSmallestSourceLocationOrNull(symbol); if (location != null) { // add this named type location AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter()); foreach (var member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.NamedType: namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member); break; case SymbolKind.Method: // NOTE: Dev11 does not add synthesized static constructors to this map, // but adds synthesized instance constructors, Roslyn adds both var method = (MethodSymbol)member; if (!method.ShouldEmit()) { break; } AddSymbolLocation(result, member); break; case SymbolKind.Property: AddSymbolLocation(result, member); break; case SymbolKind.Field: if (member is TupleErrorFieldSymbol) { break; } // NOTE: Dev11 does not add synthesized backing fields for properties, // but adds backing fields for events, Roslyn adds both AddSymbolLocation(result, member); break; case SymbolKind.Event: AddSymbolLocation(result, member); // event backing fields do not show up in GetMembers { FieldSymbol field = ((EventSymbol)member).AssociatedField; if ((object)field != null) { AddSymbolLocation(result, field); } } break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } break; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } return result; } private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Symbol symbol) { var location = GetSmallestSourceLocationOrNull(symbol); if (location != null) { AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter()); } } private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Location location, Cci.IDefinition definition) { FileLinePositionSpan span = location.GetLineSpan(); Cci.DebugSourceDocument doc = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath: location.SourceTree.FilePath); if (doc != null) { result.Add(doc, new Cci.DefinitionWithLocation( definition, span.StartLinePosition.Line, span.StartLinePosition.Character, span.EndLinePosition.Line, span.EndLinePosition.Character)); } } private Location GetSmallestSourceLocationOrNull(Symbol symbol) { CSharpCompilation compilation = symbol.DeclaringCompilation; Debug.Assert(Compilation == compilation, "How did we get symbol from different compilation?"); Location result = null; foreach (var loc in symbol.Locations) { if (loc.IsInSource && (result == null || compilation.CompareSourceLocations(result, loc) > 0)) { result = loc; } } return result; } /// <summary> /// Ignore accessibility when resolving well-known type /// members, in particular for generic type arguments /// (e.g.: binding to internal types in the EE). /// </summary> internal virtual bool IgnoreAccessibility => false; /// <summary> /// Override the dynamic operation context type for all dynamic calls in the module. /// </summary> internal virtual NamedTypeSymbol GetDynamicOperationContextType(NamedTypeSymbol contextType) { return contextType; } internal virtual VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics) { return null; } internal virtual ImmutableArray<AnonymousTypeKey> GetPreviousAnonymousTypes() { return ImmutableArray<AnonymousTypeKey>.Empty; } internal virtual ImmutableArray<SynthesizedDelegateKey> GetPreviousSynthesizedDelegates() { return ImmutableArray<SynthesizedDelegateKey>.Empty; } internal virtual int GetNextAnonymousTypeIndex() { return 0; } internal virtual bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, out string name, out int index) { Debug.Assert(Compilation == template.DeclaringCompilation); name = null; index = -1; return false; } public sealed override IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context) { if (context.MetadataOnly) { return SpecializedCollections.EmptyEnumerable<Cci.INamespaceTypeDefinition>(); } return Compilation.AnonymousTypeManager.GetAllCreatedTemplates() #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context) { var namespacesToProcess = new Stack<NamespaceSymbol>(); namespacesToProcess.Push(SourceModule.GlobalNamespace); while (namespacesToProcess.Count > 0) { var ns = namespacesToProcess.Pop(); foreach (var member in ns.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { namespacesToProcess.Push((NamespaceSymbol)member); } else { yield return ((NamedTypeSymbol)member).GetCciAdapter(); } } } } private static void GetExportedTypes(NamespaceOrTypeSymbol symbol, int parentIndex, ArrayBuilder<Cci.ExportedType> builder) { int index; if (symbol.Kind == SymbolKind.NamedType) { if (symbol.DeclaredAccessibility != Accessibility.Public) { return; } Debug.Assert(symbol.IsDefinition); index = builder.Count; builder.Add(new Cci.ExportedType((Cci.ITypeReference)symbol.GetCciAdapter(), parentIndex, isForwarder: false)); } else { index = -1; } foreach (var member in symbol.GetMembers()) { var namespaceOrType = member as NamespaceOrTypeSymbol; if ((object)namespaceOrType != null) { GetExportedTypes(namespaceOrType, index, builder); } } } public sealed override ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics) { Debug.Assert(HaveDeterminedTopLevelTypes); if (_lazyExportedTypes.IsDefault) { _lazyExportedTypes = CalculateExportedTypes(); if (_lazyExportedTypes.Length > 0) { ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics); } } return _lazyExportedTypes; } /// <summary> /// Builds an array of public type symbols defined in netmodules included in the compilation /// and type forwarders defined in this compilation or any included netmodule (in this order). /// </summary> private ImmutableArray<Cci.ExportedType> CalculateExportedTypes() { SourceAssemblySymbol sourceAssembly = SourceModule.ContainingSourceAssembly; var builder = ArrayBuilder<Cci.ExportedType>.GetInstance(); if (!OutputKind.IsNetModule()) { var modules = sourceAssembly.Modules; for (int i = 1; i < modules.Length; i++) //NOTE: skipping modules[0] { GetExportedTypes(modules[i].GlobalNamespace, -1, builder); } } Debug.Assert(OutputKind.IsNetModule() == sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()); GetForwardedTypes(sourceAssembly, builder); return builder.ToImmutableAndFree(); } #nullable enable /// <summary> /// Returns a set of top-level forwarded types /// </summary> internal static HashSet<NamedTypeSymbol> GetForwardedTypes(SourceAssemblySymbol sourceAssembly, ArrayBuilder<Cci.ExportedType>? builder) { var seenTopLevelForwardedTypes = new HashSet<NamedTypeSymbol>(); GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder); if (!sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()) { GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder); } return seenTopLevelForwardedTypes; } #nullable disable private void ReportExportedTypeNameCollisions(ImmutableArray<Cci.ExportedType> exportedTypes, DiagnosticBag diagnostics) { var sourceAssembly = SourceModule.ContainingSourceAssembly; var exportedNamesMap = new Dictionary<string, NamedTypeSymbol>(StringOrdinalComparer.Instance); foreach (var exportedType in exportedTypes) { var type = (NamedTypeSymbol)exportedType.Type.GetInternalSymbol(); Debug.Assert(type.IsDefinition); if (!type.IsTopLevelType()) { continue; } // exported types are not emitted in EnC deltas (hence generation 0): string fullEmittedName = MetadataHelpers.BuildQualifiedName( ((Cci.INamespaceTypeReference)type.GetCciAdapter()).NamespaceName, Cci.MetadataWriter.GetMangledName(type.GetCciAdapter(), generation: 0)); // First check against types declared in the primary module if (ContainsTopLevelType(fullEmittedName)) { if ((object)type.ContainingAssembly == sourceAssembly) { diagnostics.Add(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule); } else { diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, type); } continue; } NamedTypeSymbol contender; // Now check against other exported types if (exportedNamesMap.TryGetValue(fullEmittedName, out contender)) { if ((object)type.ContainingAssembly == sourceAssembly) { // all exported types precede forwarded types, therefore contender cannot be a forwarded type. Debug.Assert(contender.ContainingAssembly == sourceAssembly); diagnostics.Add(ErrorCode.ERR_ExportedTypesConflict, NoLocation.Singleton, type, type.ContainingModule, contender, contender.ContainingModule); } else if ((object)contender.ContainingAssembly == sourceAssembly) { // Forwarded type conflicts with exported type diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingModule); } else { // Forwarded type conflicts with another forwarded type diagnostics.Add(ErrorCode.ERR_ForwardedTypesConflict, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingAssembly); } continue; } exportedNamesMap.Add(fullEmittedName, type); } } #nullable enable private static void GetForwardedTypes( HashSet<NamedTypeSymbol> seenTopLevelTypes, CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> wellKnownAttributeData, ArrayBuilder<Cci.ExportedType>? builder) { if (wellKnownAttributeData?.ForwardedTypes?.Count > 0) { // (type, index of the parent exported type in builder, or -1 if the type is a top-level type) var stack = ArrayBuilder<(NamedTypeSymbol type, int parentIndex)>.GetInstance(); // Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names. IEnumerable<NamedTypeSymbol> orderedForwardedTypes = wellKnownAttributeData.ForwardedTypes; if (builder is object) { orderedForwardedTypes = orderedForwardedTypes.OrderBy(t => t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); } foreach (NamedTypeSymbol forwardedType in orderedForwardedTypes) { NamedTypeSymbol originalDefinition = forwardedType.OriginalDefinition; Debug.Assert((object)originalDefinition.ContainingType == null, "How did a nested type get forwarded?"); // Since we need to allow multiple constructions of the same generic type at the source // level, we need to de-dup the original definitions before emitting. if (!seenTopLevelTypes.Add(originalDefinition)) continue; if (builder is object) { // Return all nested types. // Note the order: depth first, children in reverse order (to match dev10, not a requirement). Debug.Assert(stack.Count == 0); stack.Push((originalDefinition, -1)); while (stack.Count > 0) { var (type, parentIndex) = stack.Pop(); // In general, we don't want private types to appear in the ExportedTypes table. // BREAK: dev11 emits these types. The problem was discovered in dev10, but failed // to meet the bar Bug: Dev10/258038 and was left as-is. if (type.DeclaredAccessibility == Accessibility.Private) { // NOTE: this will also exclude nested types of type continue; } // NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection. int index = builder.Count; builder.Add(new Cci.ExportedType(type.GetCciAdapter(), parentIndex, isForwarder: true)); // Iterate backwards so they get popped in forward order. ImmutableArray<NamedTypeSymbol> nested = type.GetTypeMembers(); // Ordered. for (int i = nested.Length - 1; i >= 0; i--) { stack.Push((nested[i], index)); } } } } stack.Free(); } } #nullable disable internal IEnumerable<AssemblySymbol> GetReferencedAssembliesUsedSoFar() { foreach (AssemblySymbol a in SourceModule.GetReferencedAssemblySymbols()) { if (!a.IsLinked && !a.IsMissing && AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(a)) { yield return a; } } } private NamedTypeSymbol GetUntranslatedSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); var typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType); DiagnosticInfo info = typeSymbol.GetUseSiteInfo().DiagnosticInfo; if (info != null) { Symbol.ReportUseSiteDiagnostic(info, diagnostics, syntaxNodeOpt != null ? syntaxNodeOpt.Location : NoLocation.Singleton); } return typeSymbol; } internal sealed override Cci.INamedTypeReference GetSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics), diagnostics: diagnostics, syntaxNodeOpt: syntaxNodeOpt, needDeclaration: true); } public sealed override Cci.IMethodReference GetInitArrayHelper() { return ((MethodSymbol)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle))?.GetCciAdapter(); } public sealed override bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType) { var namedType = typeRef.GetInternalSymbol() as NamedTypeSymbol; if ((object)namedType != null) { if (platformType == Cci.PlatformType.SystemType) { return (object)namedType == (object)Compilation.GetWellKnownType(WellKnownType.System_Type); } return namedType.SpecialType == (SpecialType)platformType; } return false; } protected sealed override Cci.IAssemblyReference GetCorLibraryReferenceToEmit(CodeAnalysis.Emit.EmitContext context) { AssemblySymbol corLibrary = CorLibrary; if (!corLibrary.IsMissing && !corLibrary.IsLinked && !ReferenceEquals(corLibrary, SourceModule.ContainingAssembly)) { return Translate(corLibrary, context.Diagnostics); } return null; } internal sealed override Cci.IAssemblyReference Translate(AssemblySymbol assembly, DiagnosticBag diagnostics) { if (ReferenceEquals(SourceModule.ContainingAssembly, assembly)) { return (Cci.IAssemblyReference)this; } Cci.IModuleReference reference; if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(assembly, out reference)) { return (Cci.IAssemblyReference)reference; } AssemblyReference asmRef = new AssemblyReference(assembly); AssemblyReference cachedAsmRef = (AssemblyReference)AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(assembly, asmRef); if (cachedAsmRef == asmRef) { ValidateReferencedAssembly(assembly, cachedAsmRef, diagnostics); } // TryAdd because whatever is associated with assembly should be associated with Modules[0] AssemblyOrModuleSymbolToModuleRefMap.TryAdd(assembly.Modules[0], cachedAsmRef); return cachedAsmRef; } internal Cci.IModuleReference Translate(ModuleSymbol module, DiagnosticBag diagnostics) { if (ReferenceEquals(SourceModule, module)) { return this; } if ((object)module == null) { return null; } Cci.IModuleReference moduleRef; if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(module, out moduleRef)) { return moduleRef; } moduleRef = TranslateModule(module, diagnostics); moduleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(module, moduleRef); return moduleRef; } protected virtual Cci.IModuleReference TranslateModule(ModuleSymbol module, DiagnosticBag diagnostics) { AssemblySymbol container = module.ContainingAssembly; if ((object)container != null && ReferenceEquals(container.Modules[0], module)) { Cci.IModuleReference moduleRef = new AssemblyReference(container); Cci.IModuleReference cachedModuleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(container, moduleRef); if (cachedModuleRef == moduleRef) { ValidateReferencedAssembly(container, (AssemblyReference)moduleRef, diagnostics); } else { moduleRef = cachedModuleRef; } return moduleRef; } else { return new ModuleReference(this, module); } } internal Cci.INamedTypeReference Translate( NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool fromImplements = false, bool needDeclaration = false) { Debug.Assert(namedTypeSymbol.IsDefinitionOrDistinct()); Debug.Assert(diagnostics != null); // Anonymous type being translated if (namedTypeSymbol.IsAnonymousType) { Debug.Assert(!needDeclaration); namedTypeSymbol = AnonymousTypeManager.TranslateAnonymousTypeSymbol(namedTypeSymbol); } else if (namedTypeSymbol.IsTupleType) { CheckTupleUnderlyingType(namedTypeSymbol, syntaxNodeOpt, diagnostics); } // Substitute error types with a special singleton object. // Unreported bad types can come through NoPia embedding, for example. if (namedTypeSymbol.OriginalDefinition.Kind == SymbolKind.ErrorType) { ErrorTypeSymbol errorType = (ErrorTypeSymbol)namedTypeSymbol.OriginalDefinition; DiagnosticInfo diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo; if (diagInfo == null && namedTypeSymbol.Kind == SymbolKind.ErrorType) { errorType = (ErrorTypeSymbol)namedTypeSymbol; diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo; } // Try to decrease noise by not complaining about the same type over and over again. if (_reportedErrorTypesMap.Add(errorType)) { diagnostics.Add(new CSDiagnostic(diagInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty), syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location)); } return CodeAnalysis.Emit.ErrorType.Singleton; } if (!namedTypeSymbol.IsDefinition) { // generic instantiation for sure Debug.Assert(!needDeclaration); if (namedTypeSymbol.IsUnboundGenericType) { namedTypeSymbol = namedTypeSymbol.OriginalDefinition; } else { return (Cci.INamedTypeReference)GetCciAdapter(namedTypeSymbol); } } else if (!needDeclaration) { object reference; Cci.INamedTypeReference typeRef; NamedTypeSymbol container = namedTypeSymbol.ContainingType; if (namedTypeSymbol.Arity > 0) { if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference)) { return (Cci.INamedTypeReference)reference; } if ((object)container != null) { if (IsGenericType(container)) { // Container is a generic instance too. typeRef = new SpecializedGenericNestedTypeInstanceReference(namedTypeSymbol); } else { typeRef = new GenericNestedTypeInstanceReference(namedTypeSymbol); } } else { typeRef = new GenericNamespaceTypeInstanceReference(namedTypeSymbol); } typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef); return typeRef; } else if (IsGenericType(container)) { Debug.Assert((object)container != null); if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference)) { return (Cci.INamedTypeReference)reference; } typeRef = new SpecializedNestedTypeReference(namedTypeSymbol); typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef); return typeRef; } else if (namedTypeSymbol.NativeIntegerUnderlyingType is NamedTypeSymbol underlyingType) { namedTypeSymbol = underlyingType; } } // NoPia: See if this is a type, which definition we should copy into our assembly. Debug.Assert(namedTypeSymbol.IsDefinition); return _embeddedTypesManagerOpt?.EmbedTypeIfNeedTo(namedTypeSymbol, fromImplements, syntaxNodeOpt, diagnostics) ?? namedTypeSymbol.GetCciAdapter(); } private object GetCciAdapter(Symbol symbol) { return _genericInstanceMap.GetOrAdd(symbol, s => s.GetCciAdapter()); } private void CheckTupleUnderlyingType(NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { // check that underlying type of a ValueTuple is indeed a value type (or error) // this should never happen, in theory, // but if it does happen we should make it a failure. // NOTE: declaredBase could be null for interfaces var declaredBase = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics; if ((object)declaredBase != null && declaredBase.SpecialType == SpecialType.System_ValueType) { return; } // Try to decrease noise by not complaining about the same type over and over again. if (!_reportedErrorTypesMap.Add(namedTypeSymbol)) { return; } var location = syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location; if ((object)declaredBase != null) { var diagnosticInfo = declaredBase.GetUseSiteInfo().DiagnosticInfo; if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error) { diagnostics.Add(diagnosticInfo, location); return; } } diagnostics.Add( new CSDiagnostic( new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, namedTypeSymbol.MetadataName), location)); } public static bool IsGenericType(NamedTypeSymbol toCheck) { while ((object)toCheck != null) { if (toCheck.Arity > 0) { return true; } toCheck = toCheck.ContainingType; } return false; } internal static Cci.IGenericParameterReference Translate(TypeParameterSymbol param) { if (!param.IsDefinition) throw new InvalidOperationException(string.Format(CSharpResources.GenericParameterDefinition, param.Name)); return param.GetCciAdapter(); } internal sealed override Cci.ITypeReference Translate( TypeSymbol typeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); switch (typeSymbol.Kind) { case SymbolKind.DynamicType: return Translate((DynamicTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics); case SymbolKind.ArrayType: return Translate((ArrayTypeSymbol)typeSymbol); case SymbolKind.ErrorType: case SymbolKind.NamedType: return Translate((NamedTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics); case SymbolKind.PointerType: return Translate((PointerTypeSymbol)typeSymbol); case SymbolKind.TypeParameter: return Translate((TypeParameterSymbol)typeSymbol); case SymbolKind.FunctionPointerType: return Translate((FunctionPointerTypeSymbol)typeSymbol); } throw ExceptionUtilities.UnexpectedValue(typeSymbol.Kind); } internal Cci.IFieldReference Translate( FieldSymbol fieldSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration = false) { Debug.Assert(fieldSymbol.IsDefinitionOrDistinct()); Debug.Assert(!fieldSymbol.IsVirtualTupleField && (object)(fieldSymbol.TupleUnderlyingField ?? fieldSymbol) == fieldSymbol && fieldSymbol is not TupleErrorFieldSymbol, "tuple fields should be rewritten to underlying by now"); if (!fieldSymbol.IsDefinition) { Debug.Assert(!needDeclaration); return (Cci.IFieldReference)GetCciAdapter(fieldSymbol); } else if (!needDeclaration && IsGenericType(fieldSymbol.ContainingType)) { object reference; Cci.IFieldReference fieldRef; if (_genericInstanceMap.TryGetValue(fieldSymbol, out reference)) { return (Cci.IFieldReference)reference; } fieldRef = new SpecializedFieldReference(fieldSymbol); fieldRef = (Cci.IFieldReference)_genericInstanceMap.GetOrAdd(fieldSymbol, fieldRef); return fieldRef; } return _embeddedTypesManagerOpt?.EmbedFieldIfNeedTo(fieldSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics) ?? fieldSymbol.GetCciAdapter(); } public static Cci.TypeMemberVisibility MemberVisibility(Symbol symbol) { // // We need to relax visibility of members in interactive submissions since they might be emitted into multiple assemblies. // // Top-level: // private -> public // protected -> public (compiles with a warning) // public // internal -> public // // In a nested class: // // private // protected // public // internal -> public // switch (symbol.DeclaredAccessibility) { case Accessibility.Public: return Cci.TypeMemberVisibility.Public; case Accessibility.Private: if (symbol.ContainingType?.TypeKind == TypeKind.Submission) { // top-level private member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Private; } case Accessibility.Internal: if (symbol.ContainingAssembly.IsInteractive) { // top-level or nested internal member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Assembly; } case Accessibility.Protected: if (symbol.ContainingType.TypeKind == TypeKind.Submission) { // top-level protected member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Family; } case Accessibility.ProtectedAndInternal: Debug.Assert(symbol.ContainingType.TypeKind != TypeKind.Submission); return Cci.TypeMemberVisibility.FamilyAndAssembly; case Accessibility.ProtectedOrInternal: if (symbol.ContainingAssembly.IsInteractive) { // top-level or nested protected internal member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.FamilyOrAssembly; } default: throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility); } } internal sealed override Cci.IMethodReference Translate(MethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration) { return Translate(symbol, null, diagnostics, null, needDeclaration); } internal Cci.IMethodReference Translate( MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, BoundArgListOperator optArgList = null, bool needDeclaration = false) { Debug.Assert(!methodSymbol.IsDefaultValueTypeConstructor(requireZeroInit: true)); Debug.Assert(optArgList == null || (methodSymbol.IsVararg && !needDeclaration)); Cci.IMethodReference unexpandedMethodRef = Translate(methodSymbol, syntaxNodeOpt, diagnostics, needDeclaration); if (optArgList != null && optArgList.Arguments.Length > 0) { Cci.IParameterTypeInformation[] @params = new Cci.IParameterTypeInformation[optArgList.Arguments.Length]; int ordinal = methodSymbol.ParameterCount; for (int i = 0; i < @params.Length; i++) { @params[i] = new ArgListParameterTypeInformation(ordinal, !optArgList.ArgumentRefKindsOpt.IsDefaultOrEmpty && optArgList.ArgumentRefKindsOpt[i] != RefKind.None, Translate(optArgList.Arguments[i].Type, syntaxNodeOpt, diagnostics)); ordinal++; } return new ExpandedVarargsMethodReference(unexpandedMethodRef, @params.AsImmutableOrNull()); } else { return unexpandedMethodRef; } } private Cci.IMethodReference Translate( MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration) { object reference; Cci.IMethodReference methodRef; NamedTypeSymbol container = methodSymbol.ContainingType; // Method of anonymous type being translated if (container.IsAnonymousType) { Debug.Assert(!needDeclaration); methodSymbol = AnonymousTypeManager.TranslateAnonymousTypeMethodSymbol(methodSymbol); } Debug.Assert(methodSymbol.IsDefinitionOrDistinct()); if (!methodSymbol.IsDefinition) { Debug.Assert(!needDeclaration); Debug.Assert(!(methodSymbol.OriginalDefinition is NativeIntegerMethodSymbol)); Debug.Assert(!(methodSymbol.ConstructedFrom is NativeIntegerMethodSymbol)); return (Cci.IMethodReference)GetCciAdapter(methodSymbol); } else if (!needDeclaration) { bool methodIsGeneric = methodSymbol.IsGenericMethod; bool typeIsGeneric = IsGenericType(container); if (methodIsGeneric || typeIsGeneric) { if (_genericInstanceMap.TryGetValue(methodSymbol, out reference)) { return (Cci.IMethodReference)reference; } if (methodIsGeneric) { if (typeIsGeneric) { // Specialized and generic instance at the same time. methodRef = new SpecializedGenericMethodInstanceReference(methodSymbol); } else { methodRef = new GenericMethodInstanceReference(methodSymbol); } } else { Debug.Assert(typeIsGeneric); methodRef = new SpecializedMethodReference(methodSymbol); } methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef); return methodRef; } else if (methodSymbol is NativeIntegerMethodSymbol { UnderlyingMethod: MethodSymbol underlyingMethod }) { methodSymbol = underlyingMethod; } } if (_embeddedTypesManagerOpt != null) { return _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics); } return methodSymbol.GetCciAdapter(); } internal Cci.IMethodReference TranslateOverriddenMethodReference( MethodSymbol methodSymbol, CSharpSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Cci.IMethodReference methodRef; NamedTypeSymbol container = methodSymbol.ContainingType; if (IsGenericType(container)) { if (methodSymbol.IsDefinition) { object reference; if (_genericInstanceMap.TryGetValue(methodSymbol, out reference)) { methodRef = (Cci.IMethodReference)reference; } else { methodRef = new SpecializedMethodReference(methodSymbol); methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef); } } else { methodRef = new SpecializedMethodReference(methodSymbol); } } else { Debug.Assert(methodSymbol.IsDefinition); if (_embeddedTypesManagerOpt != null) { methodRef = _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics); } else { methodRef = methodSymbol.GetCciAdapter(); } } return methodRef; } internal ImmutableArray<Cci.IParameterTypeInformation> Translate(ImmutableArray<ParameterSymbol> @params) { Debug.Assert(@params.All(p => p.IsDefinitionOrDistinct())); bool mustBeTranslated = @params.Any() && MustBeWrapped(@params.First()); Debug.Assert(@params.All(p => mustBeTranslated == MustBeWrapped(p)), "either all or no parameters need translating"); if (!mustBeTranslated) { #if DEBUG return @params.SelectAsArray<ParameterSymbol, Cci.IParameterTypeInformation>(p => p.GetCciAdapter()); #else return StaticCast<Cci.IParameterTypeInformation>.From(@params); #endif } return TranslateAll(@params); } private static bool MustBeWrapped(ParameterSymbol param) { // we represent parameters of generic methods as definitions // CCI wants them represented as IParameterTypeInformation // so we need to create a wrapper of parameters iff // 1) parameters are definitions and // 2) container is generic // NOTE: all parameters must always agree on whether they need wrapping if (param.IsDefinition) { var container = param.ContainingSymbol; if (ContainerIsGeneric(container)) { return true; } } return false; } private ImmutableArray<Cci.IParameterTypeInformation> TranslateAll(ImmutableArray<ParameterSymbol> @params) { var builder = ArrayBuilder<Cci.IParameterTypeInformation>.GetInstance(); foreach (var param in @params) { builder.Add(CreateParameterTypeInformationWrapper(param)); } return builder.ToImmutableAndFree(); } private Cci.IParameterTypeInformation CreateParameterTypeInformationWrapper(ParameterSymbol param) { object reference; Cci.IParameterTypeInformation paramRef; if (_genericInstanceMap.TryGetValue(param, out reference)) { return (Cci.IParameterTypeInformation)reference; } paramRef = new ParameterTypeInformation(param); paramRef = (Cci.IParameterTypeInformation)_genericInstanceMap.GetOrAdd(param, paramRef); return paramRef; } private static bool ContainerIsGeneric(Symbol container) { return container.Kind == SymbolKind.Method && ((MethodSymbol)container).IsGenericMethod || IsGenericType(container.ContainingType); } internal Cci.ITypeReference Translate( DynamicTypeSymbol symbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { // Translate the dynamic type to System.Object special type to avoid duplicate entries in TypeRef table. // We don't need to recursively replace the dynamic type with Object since the DynamicTypeSymbol adapter // masquerades the TypeRef as System.Object when used to encode signatures. return GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics); } internal Cci.IArrayTypeReference Translate(ArrayTypeSymbol symbol) { return (Cci.IArrayTypeReference)GetCciAdapter(symbol); } internal Cci.IPointerTypeReference Translate(PointerTypeSymbol symbol) { return (Cci.IPointerTypeReference)GetCciAdapter(symbol); } internal Cci.IFunctionPointerTypeReference Translate(FunctionPointerTypeSymbol symbol) { return (Cci.IFunctionPointerTypeReference)GetCciAdapter(symbol); } /// <summary> /// Set the underlying implementation type for a given fixed-size buffer field. /// </summary> public NamedTypeSymbol SetFixedImplementationType(SourceMemberFieldSymbol field) { if (_fixedImplementationTypes == null) { Interlocked.CompareExchange(ref _fixedImplementationTypes, new Dictionary<FieldSymbol, NamedTypeSymbol>(), null); } lock (_fixedImplementationTypes) { NamedTypeSymbol result; if (_fixedImplementationTypes.TryGetValue(field, out result)) { return result; } result = new FixedFieldImplementationType(field); _fixedImplementationTypes.Add(field, result); AddSynthesizedDefinition(result.ContainingType, result.GetCciAdapter()); return result; } } internal NamedTypeSymbol GetFixedImplementationType(FieldSymbol field) { // Note that this method is called only after ALL fixed buffer types have been placed in the map. // At that point the map is all filled in and will not change further. Therefore it is safe to // pull values from the map without locking. NamedTypeSymbol result; var found = _fixedImplementationTypes.TryGetValue(field, out result); Debug.Assert(found); return result; } protected override Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, SyntaxNode syntaxOpt, DiagnosticBag diagnostics) { return new SynthesizedPrivateImplementationDetailsStaticConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter(); } internal abstract SynthesizedAttributeData SynthesizeEmbeddedAttribute(); internal SynthesizedAttributeData SynthesizeIsReadOnlyAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsReadOnlyAttribute(); } internal SynthesizedAttributeData SynthesizeIsUnmanagedAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsUnmanagedAttribute(); } internal SynthesizedAttributeData SynthesizeIsByRefLikeAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsByRefLikeAttribute(); } /// <summary> /// Given a type <paramref name="type"/>, which is either a nullable reference type OR /// is a constructed type with a nullable reference type present in its type argument tree, /// returns a synthesized NullableAttribute with encoded nullable transforms array. /// </summary> internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(Symbol symbol, byte? nullableContextValue, TypeWithAnnotations type) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } var flagsBuilder = ArrayBuilder<byte>.GetInstance(); type.AddNullableTransforms(flagsBuilder); SynthesizedAttributeData attribute; if (!flagsBuilder.Any()) { attribute = null; } else { Debug.Assert(flagsBuilder.All(f => f <= 2)); byte? commonValue = MostCommonNullableValueBuilder.GetCommonValue(flagsBuilder); if (commonValue != null) { attribute = SynthesizeNullableAttributeIfNecessary(nullableContextValue, commonValue.GetValueOrDefault()); } else { NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte); var byteArrayType = ArrayTypeSymbol.CreateSZArray(byteType.ContainingAssembly, TypeWithAnnotations.Create(byteType)); var value = flagsBuilder.SelectAsArray((flag, byteType) => new TypedConstant(byteType, TypedConstantKind.Primitive, flag), byteType); attribute = SynthesizeNullableAttribute( WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags, ImmutableArray.Create(new TypedConstant(byteArrayType, value))); } } flagsBuilder.Free(); return attribute; } internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(byte? nullableContextValue, byte nullableValue) { if (nullableValue == nullableContextValue || (nullableContextValue == null && nullableValue == 0)) { return null; } NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte); return SynthesizeNullableAttribute( WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, ImmutableArray.Create(new TypedConstant(byteType, TypedConstantKind.Primitive, nullableValue))); } internal virtual SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizeNullableContextAttribute(Symbol symbol, byte value) { var module = Compilation.SourceModule; if ((object)module != symbol && (object)module != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return SynthesizeNullableContextAttribute( ImmutableArray.Create(new TypedConstant(Compilation.GetSpecialType(SpecialType.System_Byte), TypedConstantKind.Primitive, value))); } internal virtual SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, arguments, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizePreserveBaseOverridesAttribute() { return Compilation.TrySynthesizeAttribute(SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizeNativeIntegerAttribute(Symbol symbol, TypeSymbol type) { Debug.Assert((object)type != null); Debug.Assert(type.ContainsNativeInteger()); if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } var builder = ArrayBuilder<bool>.GetInstance(); CSharpCompilation.NativeIntegerTransformsEncoder.Encode(builder, type); Debug.Assert(builder.Any()); Debug.Assert(builder.Contains(true)); SynthesizedAttributeData attribute; if (builder.Count == 1 && builder[0]) { attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, ImmutableArray<TypedConstant>.Empty); } else { NamedTypeSymbol booleanType = Compilation.GetSpecialType(SpecialType.System_Boolean); Debug.Assert((object)booleanType != null); var transformFlags = builder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType); var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType)); var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags)); attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, arguments); } builder.Free(); return attribute; } internal virtual SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true); } internal bool ShouldEmitNullablePublicOnlyAttribute() { // No need to look at this.GetNeedsGeneratedAttributes() since those bits are // only set for members generated by the rewriter which are not public. return Compilation.GetUsesNullableAttributes() && Compilation.EmitNullablePublicOnly; } internal virtual SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, arguments); } protected virtual SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor); } protected virtual SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor); } protected virtual SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor); } private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); if ((GetNeedsGeneratedAttributesInternal() & attribute) != 0) { return; } // Don't report any errors. They should be reported during binding. if (Compilation.CheckIfAttributeShouldBeEmbedded(attribute, diagnosticsOpt: null, locationOpt: null)) { SetNeedsGeneratedAttributes(attribute); } } internal void EnsureIsReadOnlyAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute); } internal void EnsureIsUnmanagedAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute); } internal void EnsureNullableAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute); } internal void EnsureNullableContextAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableContextAttribute); } internal void EnsureNativeIntegerAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute); } public override IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context) { return GetAdditionalTopLevelTypes() #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context) { return GetEmbeddedTypes(context.Diagnostics) #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics) { return GetEmbeddedTypes(new BindingDiagnosticBag(diagnostics)); } internal virtual ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics) { return base.GetEmbeddedTypes(diagnostics.DiagnosticBag); } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/AnonymousTypeManager.Templates.cs
// 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. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Manages anonymous types created on module level. All requests for anonymous type symbols /// go via the instance of this class, the symbol will be either created or returned from cache. /// </summary> internal sealed partial class AnonymousTypeManager { /// <summary> /// Cache of created anonymous type templates used as an implementation of anonymous /// types in emit phase. /// </summary> private ConcurrentDictionary<string, AnonymousTypeTemplateSymbol> _lazyAnonymousTypeTemplates; /// <summary> /// Maps delegate signature shape (number of parameters and their ref-ness) to a synthesized generic delegate symbol. /// Unlike anonymous types synthesized delegates are not available through symbol APIs. They are only used in lowered bound trees. /// Currently used for dynamic call-site sites whose signature doesn't match any of the well-known Func or Action types. /// </summary> private ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> _lazySynthesizedDelegates; private struct SynthesizedDelegateKey : IEquatable<SynthesizedDelegateKey> { private readonly RefKindVector _byRefs; private readonly ushort _parameterCount; private readonly bool _returnsVoid; private readonly int _generation; public SynthesizedDelegateKey(int parameterCount, RefKindVector byRefs, bool returnsVoid, int generation) { _parameterCount = (ushort)parameterCount; _returnsVoid = returnsVoid; _generation = generation; _byRefs = byRefs; } public string MakeTypeName() { return GeneratedNames.MakeDynamicCallSiteDelegateName(_byRefs, _returnsVoid, _generation); } public override bool Equals(object obj) { return obj is SynthesizedDelegateKey && Equals((SynthesizedDelegateKey)obj); } public bool Equals(SynthesizedDelegateKey other) { return _parameterCount == other._parameterCount && _returnsVoid == other._returnsVoid && _generation == other._generation && _byRefs.Equals(other._byRefs); } public override int GetHashCode() { return Hash.Combine( Hash.Combine((int)_parameterCount, _generation), Hash.Combine(_returnsVoid.GetHashCode(), _byRefs.GetHashCode())); } } private struct SynthesizedDelegateValue { public readonly SynthesizedDelegateSymbol Delegate; // the manager that created this delegate: public readonly AnonymousTypeManager Manager; public SynthesizedDelegateValue(AnonymousTypeManager manager, SynthesizedDelegateSymbol @delegate) { Debug.Assert(manager != null && (object)@delegate != null); this.Manager = manager; this.Delegate = @delegate; } } #if DEBUG /// <summary> /// Holds a collection of all the locations of anonymous types and delegates from source /// </summary> private readonly ConcurrentDictionary<Location, bool> _sourceLocationsSeen = new ConcurrentDictionary<Location, bool>(); #endif [Conditional("DEBUG")] private void CheckSourceLocationSeen(AnonymousTypePublicSymbol anonymous) { #if DEBUG Location location = anonymous.Locations[0]; if (location.IsInSource) { if (this.AreTemplatesSealed) { Debug.Assert(_sourceLocationsSeen.ContainsKey(location)); } else { _sourceLocationsSeen.TryAdd(location, true); } } #endif } private ConcurrentDictionary<string, AnonymousTypeTemplateSymbol> AnonymousTypeTemplates { get { // Lazily create a template types cache if (_lazyAnonymousTypeTemplates == null) { CSharpCompilation previousSubmission = this.Compilation.PreviousSubmission; // TODO (tomat): avoid recursion var previousCache = (previousSubmission == null) ? null : previousSubmission.AnonymousTypeManager.AnonymousTypeTemplates; Interlocked.CompareExchange(ref _lazyAnonymousTypeTemplates, previousCache == null ? new ConcurrentDictionary<string, AnonymousTypeTemplateSymbol>() : new ConcurrentDictionary<string, AnonymousTypeTemplateSymbol>(previousCache), null); } return _lazyAnonymousTypeTemplates; } } private ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> SynthesizedDelegates { get { if (_lazySynthesizedDelegates == null) { CSharpCompilation previousSubmission = this.Compilation.PreviousSubmission; // TODO (tomat): avoid recursion var previousCache = (previousSubmission == null) ? null : previousSubmission.AnonymousTypeManager._lazySynthesizedDelegates; Interlocked.CompareExchange(ref _lazySynthesizedDelegates, previousCache == null ? new ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>() : new ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>(previousCache), null); } return _lazySynthesizedDelegates; } } internal SynthesizedDelegateSymbol SynthesizeDelegate(int parameterCount, RefKindVector refKinds, bool returnsVoid, int generation) { // parameterCount doesn't include return type Debug.Assert(refKinds.IsNull || parameterCount == refKinds.Capacity - (returnsVoid ? 0 : 1)); var key = new SynthesizedDelegateKey(parameterCount, refKinds, returnsVoid, generation); SynthesizedDelegateValue result; if (this.SynthesizedDelegates.TryGetValue(key, out result)) { return result.Delegate; } // NOTE: the newly created template may be thrown away if another thread wins var synthesizedDelegate = new SynthesizedDelegateSymbol( this.Compilation.Assembly.GlobalNamespace, key.MakeTypeName(), this.System_Object, Compilation.GetSpecialType(SpecialType.System_IntPtr), returnsVoid ? Compilation.GetSpecialType(SpecialType.System_Void) : null, parameterCount, refKinds); return this.SynthesizedDelegates.GetOrAdd(key, new SynthesizedDelegateValue(this, synthesizedDelegate)).Delegate; } /// <summary> /// Given anonymous type provided constructs an implementation type symbol to be used in emit phase; /// if the anonymous type has at least one field the implementation type symbol will be created based on /// a generic type template generated for each 'unique' anonymous type structure, otherwise the template /// type will be non-generic. /// </summary> private NamedTypeSymbol ConstructAnonymousTypeImplementationSymbol(AnonymousTypePublicSymbol anonymous) { Debug.Assert(ReferenceEquals(this, anonymous.Manager)); CheckSourceLocationSeen(anonymous); AnonymousTypeDescriptor typeDescr = anonymous.TypeDescriptor; typeDescr.AssertIsGood(); // Get anonymous type template AnonymousTypeTemplateSymbol template; if (!this.AnonymousTypeTemplates.TryGetValue(typeDescr.Key, out template)) { // NOTE: the newly created template may be thrown away if another thread wins template = this.AnonymousTypeTemplates.GetOrAdd(typeDescr.Key, new AnonymousTypeTemplateSymbol(this, typeDescr)); } // Adjust template location if the template is owned by this manager if (ReferenceEquals(template.Manager, this)) { template.AdjustLocation(typeDescr.Location); } // In case template is not generic, just return it if (template.Arity == 0) { return template; } // otherwise construct type using the field types var typeArguments = typeDescr.Fields.SelectAsArray(f => f.Type); return template.Construct(typeArguments); } private AnonymousTypeTemplateSymbol CreatePlaceholderTemplate(Microsoft.CodeAnalysis.Emit.AnonymousTypeKey key) { var fields = key.Fields.SelectAsArray(f => new AnonymousTypeField(f.Name, Location.None, default)); var typeDescr = new AnonymousTypeDescriptor(fields, Location.None); return new AnonymousTypeTemplateSymbol(this, typeDescr); } /// <summary> /// Resets numbering in anonymous type names and compiles the /// anonymous type methods. Also seals the collection of templates. /// </summary> public void AssignTemplatesNamesAndCompile(MethodCompiler compiler, PEModuleBuilder moduleBeingBuilt, BindingDiagnosticBag diagnostics) { // Ensure all previous anonymous type templates are included so the // types are available for subsequent edit and continue generations. foreach (var key in moduleBeingBuilt.GetPreviousAnonymousTypes()) { var templateKey = AnonymousTypeDescriptor.ComputeKey(key.Fields, f => f.Name); this.AnonymousTypeTemplates.GetOrAdd(templateKey, k => this.CreatePlaceholderTemplate(key)); } // Get all anonymous types owned by this manager var builder = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); GetCreatedAnonymousTypeTemplates(builder); // If the collection is not sealed yet we should assign // new indexes to the created anonymous type templates if (!this.AreTemplatesSealed) { // If we are emitting .NET module, include module's name into type's name to ensure // uniqueness across added modules. string moduleId; if (moduleBeingBuilt.OutputKind == OutputKind.NetModule) { moduleId = moduleBeingBuilt.Name; string extension = OutputKind.NetModule.GetDefaultExtension(); if (moduleId.EndsWith(extension, StringComparison.OrdinalIgnoreCase)) { moduleId = moduleId.Substring(0, moduleId.Length - extension.Length); } moduleId = MetadataHelpers.MangleForTypeNameIfNeeded(moduleId); } else { moduleId = string.Empty; } int nextIndex = moduleBeingBuilt.GetNextAnonymousTypeIndex(); foreach (var template in builder) { string name; int index; if (!moduleBeingBuilt.TryGetAnonymousTypeName(template, out name, out index)) { index = nextIndex++; name = GeneratedNames.MakeAnonymousTypeTemplateName(index, this.Compilation.GetSubmissionSlotIndex(), moduleId); } // normally it should only happen once, but in case there is a race // NameAndIndex.set has an assert which guarantees that the // template name provided is the same as the one already assigned template.NameAndIndex = new NameAndIndex(name, index); } this.SealTemplates(); } if (builder.Count > 0 && !ReportMissingOrErroneousSymbols(diagnostics)) { // Process all the templates foreach (var template in builder) { foreach (var method in template.SpecialMembers) { moduleBeingBuilt.AddSynthesizedDefinition(template, method.GetCciAdapter()); } compiler.Visit(template, null); } } builder.Free(); var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); foreach (var synthesizedDelegate in synthesizedDelegates) { compiler.Visit(synthesizedDelegate, null); } synthesizedDelegates.Free(); } /// <summary> /// The set of anonymous type templates created by /// this AnonymousTypeManager, in fixed order. /// </summary> private void GetCreatedAnonymousTypeTemplates(ArrayBuilder<AnonymousTypeTemplateSymbol> builder) { Debug.Assert(!builder.Any()); var anonymousTypes = _lazyAnonymousTypeTemplates; if (anonymousTypes != null) { foreach (var template in anonymousTypes.Values) { if (ReferenceEquals(template.Manager, this)) { builder.Add(template); } } // Sort type templates using smallest location builder.Sort(new AnonymousTypeComparer(this.Compilation)); } } /// <summary> /// The set of synthesized delegates created by /// this AnonymousTypeManager. /// </summary> private void GetCreatedSynthesizedDelegates(ArrayBuilder<SynthesizedDelegateSymbol> builder) { Debug.Assert(!builder.Any()); var delegates = _lazySynthesizedDelegates; if (delegates != null) { foreach (var template in delegates.Values) { if (ReferenceEquals(template.Manager, this)) { builder.Add(template.Delegate); } } builder.Sort(SynthesizedDelegateSymbolComparer.Instance); } } private class SynthesizedDelegateSymbolComparer : IComparer<SynthesizedDelegateSymbol> { public static readonly SynthesizedDelegateSymbolComparer Instance = new SynthesizedDelegateSymbolComparer(); public int Compare(SynthesizedDelegateSymbol x, SynthesizedDelegateSymbol y) { return x.MetadataName.CompareTo(y.MetadataName); } } internal IReadOnlyDictionary<Microsoft.CodeAnalysis.Emit.AnonymousTypeKey, Microsoft.CodeAnalysis.Emit.AnonymousTypeValue> GetAnonymousTypeMap() { var result = new Dictionary<Microsoft.CodeAnalysis.Emit.AnonymousTypeKey, Microsoft.CodeAnalysis.Emit.AnonymousTypeValue>(); var templates = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); // Get anonymous types but not synthesized delegates. (Delegate types are // not reused across generations since reuse would add complexity (such // as parsing delegate type names from metadata) without a clear benefit.) GetCreatedAnonymousTypeTemplates(templates); foreach (var template in templates) { var nameAndIndex = template.NameAndIndex; var key = template.GetAnonymousTypeKey(); var value = new Microsoft.CodeAnalysis.Emit.AnonymousTypeValue(nameAndIndex.Name, nameAndIndex.Index, template.GetCciAdapter()); result.Add(key, value); } templates.Free(); return result; } /// <summary> /// Returns all templates owned by this type manager /// </summary> internal ImmutableArray<NamedTypeSymbol> GetAllCreatedTemplates() { // NOTE: templates may not be sealed in case metadata is being emitted without IL var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var anonymousTypes = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); GetCreatedAnonymousTypeTemplates(anonymousTypes); builder.AddRange(anonymousTypes); anonymousTypes.Free(); var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); builder.AddRange(synthesizedDelegates); synthesizedDelegates.Free(); return builder.ToImmutableAndFree(); } /// <summary> /// Returns true if the named type is an implementation template for an anonymous type /// </summary> internal static bool IsAnonymousTypeTemplate(NamedTypeSymbol type) { return type is AnonymousTypeTemplateSymbol; } /// <summary> /// Retrieves methods of anonymous type template which are not placed to symbol table. /// In current implementation those are overridden 'ToString', 'Equals' and 'GetHashCode' /// </summary> internal static ImmutableArray<MethodSymbol> GetAnonymousTypeHiddenMethods(NamedTypeSymbol type) { Debug.Assert((object)type != null); return ((AnonymousTypeTemplateSymbol)type).SpecialMembers; } /// <summary> /// Translates anonymous type public symbol into an implementation type symbol to be used in emit. /// </summary> internal static NamedTypeSymbol TranslateAnonymousTypeSymbol(NamedTypeSymbol type) { Debug.Assert((object)type != null); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Manager.ConstructAnonymousTypeImplementationSymbol(anonymous); } /// <summary> /// Translates anonymous type method symbol into an implementation method symbol to be used in emit. /// </summary> internal static MethodSymbol TranslateAnonymousTypeMethodSymbol(MethodSymbol method) { Debug.Assert((object)method != null); NamedTypeSymbol translatedType = TranslateAnonymousTypeSymbol(method.ContainingType); // find a method in anonymous type template by name foreach (var member in ((NamedTypeSymbol)translatedType.OriginalDefinition).GetMembers(method.Name)) { if (member.Kind == SymbolKind.Method) { // found a method definition, get a constructed method return ((MethodSymbol)member).AsMember(translatedType); } } throw ExceptionUtilities.Unreachable; } /// <summary> /// Comparator being used for stable ordering in anonymous type indices. /// </summary> private sealed class AnonymousTypeComparer : IComparer<AnonymousTypeTemplateSymbol> { private readonly CSharpCompilation _compilation; public AnonymousTypeComparer(CSharpCompilation compilation) { _compilation = compilation; } public int Compare(AnonymousTypeTemplateSymbol x, AnonymousTypeTemplateSymbol y) { if ((object)x == (object)y) { return 0; } // We compare two anonymous type templated by comparing their locations and descriptor keys // NOTE: If anonymous type got to this phase it must have the location set int result = this.CompareLocations(x.SmallestLocation, y.SmallestLocation); if (result == 0) { // It is still possible for two templates to have the same smallest location // in case they are implicitly created and use the same syntax for location result = string.CompareOrdinal(x.TypeDescriptorKey, y.TypeDescriptorKey); } return result; } private int CompareLocations(Location x, Location y) { if (x == y) { return 0; } else if (x == Location.None) { return -1; } else if (y == Location.None) { return 1; } else { return _compilation.CompareSourceLocations(x, y); } } } } }
// 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. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Manages anonymous types created on module level. All requests for anonymous type symbols /// go via the instance of this class, the symbol will be either created or returned from cache. /// </summary> internal sealed partial class AnonymousTypeManager { /// <summary> /// Cache of created anonymous type templates used as an implementation of anonymous /// types in emit phase. /// </summary> private ConcurrentDictionary<string, AnonymousTypeTemplateSymbol> _lazyAnonymousTypeTemplates; /// <summary> /// Maps delegate signature shape (number of parameters and their ref-ness) to a synthesized generic delegate symbol. /// Unlike anonymous types synthesized delegates are not available through symbol APIs. They are only used in lowered bound trees. /// Currently used for dynamic call-site sites whose signature doesn't match any of the well-known Func or Action types. /// </summary> private ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> _lazySynthesizedDelegates; private struct SynthesizedDelegateKey : IEquatable<SynthesizedDelegateKey> { private readonly RefKindVector _byRefs; private readonly ushort _parameterCount; private readonly bool _returnsVoid; private readonly int _generation; public SynthesizedDelegateKey(int parameterCount, RefKindVector byRefs, bool returnsVoid, int generation) { _parameterCount = (ushort)parameterCount; _returnsVoid = returnsVoid; _generation = generation; _byRefs = byRefs; } public string MakeTypeName() { return GeneratedNames.MakeSynthesizedDelegateName(_byRefs, _returnsVoid, _generation); } public override bool Equals(object obj) { return obj is SynthesizedDelegateKey && Equals((SynthesizedDelegateKey)obj); } public bool Equals(SynthesizedDelegateKey other) { return _parameterCount == other._parameterCount && _returnsVoid == other._returnsVoid && _generation == other._generation && _byRefs.Equals(other._byRefs); } public override int GetHashCode() { return Hash.Combine( Hash.Combine((int)_parameterCount, _generation), Hash.Combine(_returnsVoid.GetHashCode(), _byRefs.GetHashCode())); } } private struct SynthesizedDelegateValue { public readonly SynthesizedDelegateSymbol Delegate; // the manager that created this delegate: public readonly AnonymousTypeManager Manager; public SynthesizedDelegateValue(AnonymousTypeManager manager, SynthesizedDelegateSymbol @delegate) { Debug.Assert(manager != null && (object)@delegate != null); this.Manager = manager; this.Delegate = @delegate; } } #if DEBUG /// <summary> /// Holds a collection of all the locations of anonymous types and delegates from source /// </summary> private readonly ConcurrentDictionary<Location, bool> _sourceLocationsSeen = new ConcurrentDictionary<Location, bool>(); #endif [Conditional("DEBUG")] private void CheckSourceLocationSeen(AnonymousTypePublicSymbol anonymous) { #if DEBUG Location location = anonymous.Locations[0]; if (location.IsInSource) { if (this.AreTemplatesSealed) { Debug.Assert(_sourceLocationsSeen.ContainsKey(location)); } else { _sourceLocationsSeen.TryAdd(location, true); } } #endif } private ConcurrentDictionary<string, AnonymousTypeTemplateSymbol> AnonymousTypeTemplates { get { // Lazily create a template types cache if (_lazyAnonymousTypeTemplates == null) { CSharpCompilation previousSubmission = this.Compilation.PreviousSubmission; // TODO (tomat): avoid recursion var previousCache = (previousSubmission == null) ? null : previousSubmission.AnonymousTypeManager.AnonymousTypeTemplates; Interlocked.CompareExchange(ref _lazyAnonymousTypeTemplates, previousCache == null ? new ConcurrentDictionary<string, AnonymousTypeTemplateSymbol>() : new ConcurrentDictionary<string, AnonymousTypeTemplateSymbol>(previousCache), null); } return _lazyAnonymousTypeTemplates; } } private ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> SynthesizedDelegates { get { if (_lazySynthesizedDelegates == null) { CSharpCompilation previousSubmission = this.Compilation.PreviousSubmission; // TODO (tomat): avoid recursion var previousCache = (previousSubmission == null) ? null : previousSubmission.AnonymousTypeManager._lazySynthesizedDelegates; Interlocked.CompareExchange(ref _lazySynthesizedDelegates, previousCache == null ? new ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>() : new ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>(previousCache), null); } return _lazySynthesizedDelegates; } } internal SynthesizedDelegateSymbol SynthesizeDelegate(int parameterCount, RefKindVector refKinds, bool returnsVoid, int generation) { // parameterCount doesn't include return type Debug.Assert(refKinds.IsNull || parameterCount == refKinds.Capacity - (returnsVoid ? 0 : 1)); var key = new SynthesizedDelegateKey(parameterCount, refKinds, returnsVoid, generation); SynthesizedDelegateValue result; if (this.SynthesizedDelegates.TryGetValue(key, out result)) { return result.Delegate; } // NOTE: the newly created template may be thrown away if another thread wins var synthesizedDelegate = new SynthesizedDelegateSymbol( this.Compilation.Assembly.GlobalNamespace, key.MakeTypeName(), this.System_Object, Compilation.GetSpecialType(SpecialType.System_IntPtr), returnsVoid ? Compilation.GetSpecialType(SpecialType.System_Void) : null, parameterCount, refKinds); return this.SynthesizedDelegates.GetOrAdd(key, new SynthesizedDelegateValue(this, synthesizedDelegate)).Delegate; } /// <summary> /// Given anonymous type provided constructs an implementation type symbol to be used in emit phase; /// if the anonymous type has at least one field the implementation type symbol will be created based on /// a generic type template generated for each 'unique' anonymous type structure, otherwise the template /// type will be non-generic. /// </summary> private NamedTypeSymbol ConstructAnonymousTypeImplementationSymbol(AnonymousTypePublicSymbol anonymous) { Debug.Assert(ReferenceEquals(this, anonymous.Manager)); CheckSourceLocationSeen(anonymous); AnonymousTypeDescriptor typeDescr = anonymous.TypeDescriptor; typeDescr.AssertIsGood(); // Get anonymous type template AnonymousTypeTemplateSymbol template; if (!this.AnonymousTypeTemplates.TryGetValue(typeDescr.Key, out template)) { // NOTE: the newly created template may be thrown away if another thread wins template = this.AnonymousTypeTemplates.GetOrAdd(typeDescr.Key, new AnonymousTypeTemplateSymbol(this, typeDescr)); } // Adjust template location if the template is owned by this manager if (ReferenceEquals(template.Manager, this)) { template.AdjustLocation(typeDescr.Location); } // In case template is not generic, just return it if (template.Arity == 0) { return template; } // otherwise construct type using the field types var typeArguments = typeDescr.Fields.SelectAsArray(f => f.Type); return template.Construct(typeArguments); } private AnonymousTypeTemplateSymbol CreatePlaceholderTemplate(Microsoft.CodeAnalysis.Emit.AnonymousTypeKey key) { var fields = key.Fields.SelectAsArray(f => new AnonymousTypeField(f.Name, Location.None, default)); var typeDescr = new AnonymousTypeDescriptor(fields, Location.None); return new AnonymousTypeTemplateSymbol(this, typeDescr); } private SynthesizedDelegateValue CreatePlaceholderSynthesizedDelegateValue(string name, RefKindVector refKinds, bool returnsVoid, int parameterCount) { var symbol = new SynthesizedDelegateSymbol( this.Compilation.Assembly.GlobalNamespace, MetadataHelpers.InferTypeArityAndUnmangleMetadataName(name, out _), this.System_Object, Compilation.GetSpecialType(SpecialType.System_IntPtr), returnsVoid ? Compilation.GetSpecialType(SpecialType.System_Void) : null, parameterCount, refKinds); return new SynthesizedDelegateValue(this, symbol); } /// <summary> /// Resets numbering in anonymous type names and compiles the /// anonymous type methods. Also seals the collection of templates. /// </summary> public void AssignTemplatesNamesAndCompile(MethodCompiler compiler, PEModuleBuilder moduleBeingBuilt, BindingDiagnosticBag diagnostics) { // Ensure all previous anonymous type templates are included so the // types are available for subsequent edit and continue generations. foreach (var key in moduleBeingBuilt.GetPreviousAnonymousTypes()) { var templateKey = AnonymousTypeDescriptor.ComputeKey(key.Fields, f => f.Name); this.AnonymousTypeTemplates.GetOrAdd(templateKey, k => this.CreatePlaceholderTemplate(key)); } // Get all anonymous types owned by this manager var builder = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); GetCreatedAnonymousTypeTemplates(builder); // If the collection is not sealed yet we should assign // new indexes to the created anonymous type templates if (!this.AreTemplatesSealed) { // If we are emitting .NET module, include module's name into type's name to ensure // uniqueness across added modules. string moduleId; if (moduleBeingBuilt.OutputKind == OutputKind.NetModule) { moduleId = moduleBeingBuilt.Name; string extension = OutputKind.NetModule.GetDefaultExtension(); if (moduleId.EndsWith(extension, StringComparison.OrdinalIgnoreCase)) { moduleId = moduleId.Substring(0, moduleId.Length - extension.Length); } moduleId = MetadataHelpers.MangleForTypeNameIfNeeded(moduleId); } else { moduleId = string.Empty; } int nextIndex = moduleBeingBuilt.GetNextAnonymousTypeIndex(); foreach (var template in builder) { string name; int index; if (!moduleBeingBuilt.TryGetAnonymousTypeName(template, out name, out index)) { index = nextIndex++; name = GeneratedNames.MakeAnonymousTypeTemplateName(index, this.Compilation.GetSubmissionSlotIndex(), moduleId); } // normally it should only happen once, but in case there is a race // NameAndIndex.set has an assert which guarantees that the // template name provided is the same as the one already assigned template.NameAndIndex = new NameAndIndex(name, index); } this.SealTemplates(); } if (builder.Count > 0 && !ReportMissingOrErroneousSymbols(diagnostics)) { // Process all the templates foreach (var template in builder) { foreach (var method in template.SpecialMembers) { moduleBeingBuilt.AddSynthesizedDefinition(template, method.GetCciAdapter()); } compiler.Visit(template, null); } } builder.Free(); // Ensure all previous synthesized delegates are included so the // types are available for subsequent edit and continue generations. foreach (var key in moduleBeingBuilt.GetPreviousSynthesizedDelegates()) { if (GeneratedNames.TryParseSynthesizedDelegateName(key.Name, out var refKinds, out var returnsVoid, out var generation, out var parameterCount)) { var delegateKey = new SynthesizedDelegateKey(parameterCount, refKinds, returnsVoid, generation); this.SynthesizedDelegates.GetOrAdd(delegateKey, (k, args) => CreatePlaceholderSynthesizedDelegateValue(key.Name, args.refKinds, args.returnsVoid, args.parameterCount), (refKinds, returnsVoid, parameterCount)); } } var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); foreach (var synthesizedDelegate in synthesizedDelegates) { compiler.Visit(synthesizedDelegate, null); } synthesizedDelegates.Free(); } /// <summary> /// The set of anonymous type templates created by /// this AnonymousTypeManager, in fixed order. /// </summary> private void GetCreatedAnonymousTypeTemplates(ArrayBuilder<AnonymousTypeTemplateSymbol> builder) { Debug.Assert(!builder.Any()); var anonymousTypes = _lazyAnonymousTypeTemplates; if (anonymousTypes != null) { foreach (var template in anonymousTypes.Values) { if (ReferenceEquals(template.Manager, this)) { builder.Add(template); } } // Sort type templates using smallest location builder.Sort(new AnonymousTypeComparer(this.Compilation)); } } /// <summary> /// The set of synthesized delegates created by /// this AnonymousTypeManager. /// </summary> private void GetCreatedSynthesizedDelegates(ArrayBuilder<SynthesizedDelegateSymbol> builder) { Debug.Assert(!builder.Any()); var delegates = _lazySynthesizedDelegates; if (delegates != null) { foreach (var template in delegates.Values) { if (ReferenceEquals(template.Manager, this)) { builder.Add(template.Delegate); } } builder.Sort(SynthesizedDelegateSymbolComparer.Instance); } } private class SynthesizedDelegateSymbolComparer : IComparer<SynthesizedDelegateSymbol> { public static readonly SynthesizedDelegateSymbolComparer Instance = new SynthesizedDelegateSymbolComparer(); public int Compare(SynthesizedDelegateSymbol x, SynthesizedDelegateSymbol y) { return x.MetadataName.CompareTo(y.MetadataName); } } internal IReadOnlyDictionary<CodeAnalysis.Emit.SynthesizedDelegateKey, CodeAnalysis.Emit.SynthesizedDelegateValue> GetSynthesizedDelegates() { var result = new Dictionary<CodeAnalysis.Emit.SynthesizedDelegateKey, CodeAnalysis.Emit.SynthesizedDelegateValue>(); var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); foreach (var delegateSymbol in synthesizedDelegates) { var key = new CodeAnalysis.Emit.SynthesizedDelegateKey(delegateSymbol.MetadataName); var value = new CodeAnalysis.Emit.SynthesizedDelegateValue(delegateSymbol.GetCciAdapter()); result.Add(key, value); } synthesizedDelegates.Free(); return result; } internal IReadOnlyDictionary<Microsoft.CodeAnalysis.Emit.AnonymousTypeKey, Microsoft.CodeAnalysis.Emit.AnonymousTypeValue> GetAnonymousTypeMap() { var result = new Dictionary<Microsoft.CodeAnalysis.Emit.AnonymousTypeKey, Microsoft.CodeAnalysis.Emit.AnonymousTypeValue>(); var templates = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); // Get anonymous types but not synthesized delegates. (Delegate types are // not reused across generations since reuse would add complexity (such // as parsing delegate type names from metadata) without a clear benefit.) GetCreatedAnonymousTypeTemplates(templates); foreach (var template in templates) { var nameAndIndex = template.NameAndIndex; var key = template.GetAnonymousTypeKey(); var value = new Microsoft.CodeAnalysis.Emit.AnonymousTypeValue(nameAndIndex.Name, nameAndIndex.Index, template.GetCciAdapter()); result.Add(key, value); } templates.Free(); return result; } /// <summary> /// Returns all templates owned by this type manager /// </summary> internal ImmutableArray<NamedTypeSymbol> GetAllCreatedTemplates() { // NOTE: templates may not be sealed in case metadata is being emitted without IL var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var anonymousTypes = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); GetCreatedAnonymousTypeTemplates(anonymousTypes); builder.AddRange(anonymousTypes); anonymousTypes.Free(); var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); builder.AddRange(synthesizedDelegates); synthesizedDelegates.Free(); return builder.ToImmutableAndFree(); } /// <summary> /// Returns true if the named type is an implementation template for an anonymous type /// </summary> internal static bool IsAnonymousTypeTemplate(NamedTypeSymbol type) { return type is AnonymousTypeTemplateSymbol; } /// <summary> /// Retrieves methods of anonymous type template which are not placed to symbol table. /// In current implementation those are overridden 'ToString', 'Equals' and 'GetHashCode' /// </summary> internal static ImmutableArray<MethodSymbol> GetAnonymousTypeHiddenMethods(NamedTypeSymbol type) { Debug.Assert((object)type != null); return ((AnonymousTypeTemplateSymbol)type).SpecialMembers; } /// <summary> /// Translates anonymous type public symbol into an implementation type symbol to be used in emit. /// </summary> internal static NamedTypeSymbol TranslateAnonymousTypeSymbol(NamedTypeSymbol type) { Debug.Assert((object)type != null); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Manager.ConstructAnonymousTypeImplementationSymbol(anonymous); } /// <summary> /// Translates anonymous type method symbol into an implementation method symbol to be used in emit. /// </summary> internal static MethodSymbol TranslateAnonymousTypeMethodSymbol(MethodSymbol method) { Debug.Assert((object)method != null); NamedTypeSymbol translatedType = TranslateAnonymousTypeSymbol(method.ContainingType); // find a method in anonymous type template by name foreach (var member in ((NamedTypeSymbol)translatedType.OriginalDefinition).GetMembers(method.Name)) { if (member.Kind == SymbolKind.Method) { // found a method definition, get a constructed method return ((MethodSymbol)member).AsMember(translatedType); } } throw ExceptionUtilities.Unreachable; } /// <summary> /// Comparator being used for stable ordering in anonymous type indices. /// </summary> private sealed class AnonymousTypeComparer : IComparer<AnonymousTypeTemplateSymbol> { private readonly CSharpCompilation _compilation; public AnonymousTypeComparer(CSharpCompilation compilation) { _compilation = compilation; } public int Compare(AnonymousTypeTemplateSymbol x, AnonymousTypeTemplateSymbol y) { if ((object)x == (object)y) { return 0; } // We compare two anonymous type templated by comparing their locations and descriptor keys // NOTE: If anonymous type got to this phase it must have the location set int result = this.CompareLocations(x.SmallestLocation, y.SmallestLocation); if (result == 0) { // It is still possible for two templates to have the same smallest location // in case they are implicitly created and use the same syntax for location result = string.CompareOrdinal(x.TypeDescriptorKey, y.TypeDescriptorKey); } return result; } private int CompareLocations(Location x, Location y) { if (x == y) { return 0; } else if (x == Location.None) { return -1; } else if (y == Location.None) { return 1; } else { return _compilation.CompareSourceLocations(x, y); } } } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Portable/Symbols/Synthesized/GeneratedNames.cs
// 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 System; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class GeneratedNames { private const char IdSeparator = '_'; private const char GenerationSeparator = '#'; internal static bool IsGeneratedMemberName(string memberName) { return memberName.Length > 0 && memberName[0] == '<'; } internal static string MakeBackingFieldName(string propertyName) { Debug.Assert((char)GeneratedNameKind.AutoPropertyBackingField == 'k'); return "<" + propertyName + ">k__BackingField"; } internal static string MakeIteratorFinallyMethodName(int iteratorState) { // we can pick any name, but we will try to do // <>m__Finally1 // <>m__Finally2 // <>m__Finally3 // . . . // that will roughly match native naming scheme and may also be easier when need to debug. Debug.Assert((char)GeneratedNameKind.IteratorFinallyMethod == 'm'); return "<>m__Finally" + StringExtensions.GetNumeral(Math.Abs(iteratorState + 2)); } internal static string MakeStaticLambdaDisplayClassName(int methodOrdinal, int generation) { return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaDisplayClass, methodOrdinal, generation); } internal static string MakeLambdaDisplayClassName(int methodOrdinal, int generation, int closureOrdinal, int closureGeneration) { // -1 for singleton static lambdas Debug.Assert(closureOrdinal >= -1); Debug.Assert(methodOrdinal >= 0); return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaDisplayClass, methodOrdinal, generation, suffix: "DisplayClass", entityOrdinal: closureOrdinal, entityGeneration: closureGeneration); } internal static string MakeAnonymousTypeTemplateName(int index, int submissionSlotIndex, string moduleId) { var name = "<" + moduleId + ">f__AnonymousType" + StringExtensions.GetNumeral(index); if (submissionSlotIndex >= 0) { name += "#" + StringExtensions.GetNumeral(submissionSlotIndex); } return name; } internal static string MakeAnonymousTypeBackingFieldName(string propertyName) { return "<" + propertyName + ">i__Field"; } internal static string MakeAnonymousTypeParameterName(string propertyName) { return "<" + propertyName + ">j__TPar"; } internal static string MakeStateMachineTypeName(string methodName, int methodOrdinal, int generation) { Debug.Assert(generation >= 0); Debug.Assert(methodOrdinal >= -1); return MakeMethodScopedSynthesizedName(GeneratedNameKind.StateMachineType, methodOrdinal, generation, methodName); } internal static string MakeBaseMethodWrapperName(int uniqueId) { Debug.Assert((char)GeneratedNameKind.BaseMethodWrapper == 'n'); return "<>n__" + StringExtensions.GetNumeral(uniqueId); } internal static string MakeLambdaMethodName(string methodName, int methodOrdinal, int methodGeneration, int lambdaOrdinal, int lambdaGeneration) { Debug.Assert(methodOrdinal >= -1); Debug.Assert(methodGeneration >= 0); Debug.Assert(lambdaOrdinal >= 0); Debug.Assert(lambdaGeneration >= 0); // The EE displays the containing method name and unique id in the stack trace, // and uses it to find the original binding context. return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaMethod, methodOrdinal, methodGeneration, methodName, entityOrdinal: lambdaOrdinal, entityGeneration: lambdaGeneration); } internal static string MakeLambdaCacheFieldName(int methodOrdinal, int generation, int lambdaOrdinal, int lambdaGeneration) { Debug.Assert(methodOrdinal >= -1); Debug.Assert(lambdaOrdinal >= 0); return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaCacheField, methodOrdinal, generation, entityOrdinal: lambdaOrdinal, entityGeneration: lambdaGeneration); } internal static string MakeLocalFunctionName(string methodName, string localFunctionName, int methodOrdinal, int methodGeneration, int lambdaOrdinal, int lambdaGeneration) { Debug.Assert(methodOrdinal >= -1); Debug.Assert(methodGeneration >= 0); Debug.Assert(lambdaOrdinal >= 0); Debug.Assert(lambdaGeneration >= 0); return MakeMethodScopedSynthesizedName(GeneratedNameKind.LocalFunction, methodOrdinal, methodGeneration, methodName, localFunctionName, GeneratedNameConstants.LocalFunctionNameTerminator, lambdaOrdinal, lambdaGeneration); } private static string MakeMethodScopedSynthesizedName( GeneratedNameKind kind, int methodOrdinal, int methodGeneration, string? methodName = null, string? suffix = null, char suffixTerminator = default, int entityOrdinal = -1, int entityGeneration = -1) { Debug.Assert(methodOrdinal >= -1); Debug.Assert(methodGeneration >= 0 || methodGeneration == -1 && methodOrdinal == -1); Debug.Assert(entityOrdinal >= -1); Debug.Assert(entityGeneration >= 0 || entityGeneration == -1 && entityOrdinal == -1); Debug.Assert(entityGeneration == -1 || entityGeneration >= methodGeneration); var result = PooledStringBuilder.GetInstance(); var builder = result.Builder; builder.Append('<'); if (methodName != null) { builder.Append(methodName); // CLR generally allows names with dots, however some APIs like IMetaDataImport // can only return full type names combined with namespaces. // see: http://msdn.microsoft.com/en-us/library/ms230143.aspx (IMetaDataImport::GetTypeDefProps) // When working with such APIs, names with dots become ambiguous since metadata // consumer cannot figure where namespace ends and actual type name starts. // Therefore it is a good practice to avoid type names with dots. // As a replacement use a character not allowed in C# identifier to avoid conflicts. if (kind.IsTypeName()) { builder.Replace('.', GeneratedNameConstants.DotReplacementInTypeNames); } } builder.Append('>'); builder.Append((char)kind); if (suffix != null || methodOrdinal >= 0 || entityOrdinal >= 0) { builder.Append(GeneratedNameConstants.SuffixSeparator); builder.Append(suffix); if (suffixTerminator != default) { builder.Append(suffixTerminator); } if (methodOrdinal >= 0) { builder.Append(methodOrdinal); AppendOptionalGeneration(builder, methodGeneration); } if (entityOrdinal >= 0) { if (methodOrdinal >= 0) { builder.Append(IdSeparator); } builder.Append(entityOrdinal); AppendOptionalGeneration(builder, entityGeneration); } } return result.ToStringAndFree(); } private static void AppendOptionalGeneration(StringBuilder builder, int generation) { if (generation > 0) { builder.Append(GenerationSeparator); builder.Append(generation); } } internal static string MakeHoistedLocalFieldName(SynthesizedLocalKind kind, int slotIndex, string? localName = null) { Debug.Assert((localName != null) == (kind == SynthesizedLocalKind.UserDefined)); Debug.Assert(slotIndex >= 0); Debug.Assert(kind.IsLongLived()); // Lambda display class local follows a different naming pattern. // EE depends on the name format. // There's logic in the EE to recognize locals that have been captured by a lambda // and would have been hoisted for the state machine. Basically, we just hoist the local containing // the instance of the lambda display class and retain its original name (rather than using an // iterator local name). See FUNCBRECEE::ImportIteratorMethodInheritedLocals. var result = PooledStringBuilder.GetInstance(); var builder = result.Builder; builder.Append('<'); if (localName != null) { Debug.Assert(localName.IndexOf('.') == -1); builder.Append(localName); } builder.Append('>'); if (kind == SynthesizedLocalKind.LambdaDisplayClass) { builder.Append((char)GeneratedNameKind.DisplayClassLocalOrField); } else if (kind == SynthesizedLocalKind.UserDefined) { builder.Append((char)GeneratedNameKind.HoistedLocalField); } else { builder.Append((char)GeneratedNameKind.HoistedSynthesizedLocalField); } builder.Append("__"); builder.Append(slotIndex + 1); return result.ToStringAndFree(); } internal static string AsyncAwaiterFieldName(int slotIndex) { Debug.Assert((char)GeneratedNameKind.AwaiterField == 'u'); return "<>u__" + StringExtensions.GetNumeral(slotIndex + 1); } internal static string MakeCachedFrameInstanceFieldName() { Debug.Assert((char)GeneratedNameKind.LambdaCacheField == '9'); return "<>9"; } internal static string? MakeSynthesizedLocalName(SynthesizedLocalKind kind, ref int uniqueId) { Debug.Assert(kind.IsLongLived()); // Lambda display class local has to be named. EE depends on the name format. if (kind == SynthesizedLocalKind.LambdaDisplayClass) { return MakeLambdaDisplayLocalName(uniqueId++); } return null; } internal static string MakeSynthesizedInstrumentationPayloadLocalFieldName(int uniqueId) { return GeneratedNameConstants.SynthesizedLocalNamePrefix + "InstrumentationPayload" + StringExtensions.GetNumeral(uniqueId); } internal static string MakeLambdaDisplayLocalName(int uniqueId) { Debug.Assert((char)GeneratedNameKind.DisplayClassLocalOrField == '8'); return GeneratedNameConstants.SynthesizedLocalNamePrefix + "<>8__locals" + StringExtensions.GetNumeral(uniqueId); } internal static string MakeFixedFieldImplementationName(string fieldName) { // the native compiler adds numeric digits at the end. Roslyn does not. Debug.Assert((char)GeneratedNameKind.FixedBufferField == 'e'); return "<" + fieldName + ">e__FixedBuffer"; } internal static string MakeStateMachineStateFieldName() { // Microsoft.VisualStudio.VIL.VisualStudioHost.AsyncReturnStackFrame depends on this name. Debug.Assert((char)GeneratedNameKind.StateMachineStateField == '1'); return "<>1__state"; } internal static string MakeAsyncIteratorPromiseOfValueOrEndFieldName() { Debug.Assert((char)GeneratedNameKind.AsyncIteratorPromiseOfValueOrEndBackingField == 'v'); return "<>v__promiseOfValueOrEnd"; } internal static string MakeAsyncIteratorCombinedTokensFieldName() { Debug.Assert((char)GeneratedNameKind.CombinedTokensField == 'x'); return "<>x__combinedTokens"; } internal static string MakeIteratorCurrentFieldName() { Debug.Assert((char)GeneratedNameKind.IteratorCurrentBackingField == '2'); return "<>2__current"; } internal static string MakeDisposeModeFieldName() { Debug.Assert((char)GeneratedNameKind.DisposeModeField == 'w'); return "<>w__disposeMode"; } internal static string MakeIteratorCurrentThreadIdFieldName() { Debug.Assert((char)GeneratedNameKind.IteratorCurrentThreadIdField == 'l'); return "<>l__initialThreadId"; } internal static string ThisProxyFieldName() { Debug.Assert((char)GeneratedNameKind.ThisProxyField == '4'); return "<>4__this"; } internal static string StateMachineThisParameterProxyName() { return StateMachineParameterProxyFieldName(ThisProxyFieldName()); } internal static string StateMachineParameterProxyFieldName(string parameterName) { Debug.Assert((char)GeneratedNameKind.StateMachineParameterProxyField == '3'); return "<>3__" + parameterName; } internal static string MakeDynamicCallSiteContainerName(int methodOrdinal, int localFunctionOrdinal, int generation) { return MakeMethodScopedSynthesizedName(GeneratedNameKind.DynamicCallSiteContainerType, methodOrdinal, generation, suffix: localFunctionOrdinal != -1 ? localFunctionOrdinal.ToString() : null, suffixTerminator: localFunctionOrdinal != -1 ? '_' : default); } internal static string MakeDynamicCallSiteFieldName(int uniqueId) { Debug.Assert((char)GeneratedNameKind.DynamicCallSiteField == 'p'); return "<>p__" + StringExtensions.GetNumeral(uniqueId); } /// <summary> /// 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> internal static string MakeDynamicCallSiteDelegateName(RefKindVector byRefs, bool returnsVoid, int generation) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(returnsVoid ? "<>A" : "<>F"); if (!byRefs.IsNull) { builder.Append("{"); int i = 0; foreach (int byRefIndex in byRefs.Words()) { if (i > 0) { builder.Append(","); } builder.AppendFormat("{0:x8}", byRefIndex); i++; } builder.Append("}"); Debug.Assert(i > 0); } AppendOptionalGeneration(builder, generation); return pooledBuilder.ToStringAndFree(); } internal static string AsyncBuilderFieldName() { // Microsoft.VisualStudio.VIL.VisualStudioHost.AsyncReturnStackFrame depends on this name. Debug.Assert((char)GeneratedNameKind.AsyncBuilderField == 't'); return "<>t__builder"; } internal static string ReusableHoistedLocalFieldName(int number) { Debug.Assert((char)GeneratedNameKind.ReusableHoistedLocalField == '7'); return "<>7__wrap" + StringExtensions.GetNumeral(number); } internal static string LambdaCopyParameterName(int ordinal) { return "<p" + StringExtensions.GetNumeral(ordinal) + ">"; } } }
// 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 System; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class GeneratedNames { private const char IdSeparator = '_'; private const char GenerationSeparator = '#'; internal static bool IsGeneratedMemberName(string memberName) { return memberName.Length > 0 && memberName[0] == '<'; } internal static string MakeBackingFieldName(string propertyName) { Debug.Assert((char)GeneratedNameKind.AutoPropertyBackingField == 'k'); return "<" + propertyName + ">k__BackingField"; } internal static string MakeIteratorFinallyMethodName(int iteratorState) { // we can pick any name, but we will try to do // <>m__Finally1 // <>m__Finally2 // <>m__Finally3 // . . . // that will roughly match native naming scheme and may also be easier when need to debug. Debug.Assert((char)GeneratedNameKind.IteratorFinallyMethod == 'm'); return "<>m__Finally" + StringExtensions.GetNumeral(Math.Abs(iteratorState + 2)); } internal static string MakeStaticLambdaDisplayClassName(int methodOrdinal, int generation) { return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaDisplayClass, methodOrdinal, generation); } internal static string MakeLambdaDisplayClassName(int methodOrdinal, int generation, int closureOrdinal, int closureGeneration) { // -1 for singleton static lambdas Debug.Assert(closureOrdinal >= -1); Debug.Assert(methodOrdinal >= 0); return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaDisplayClass, methodOrdinal, generation, suffix: "DisplayClass", entityOrdinal: closureOrdinal, entityGeneration: closureGeneration); } internal static string MakeAnonymousTypeTemplateName(int index, int submissionSlotIndex, string moduleId) { var name = "<" + moduleId + ">f__AnonymousType" + StringExtensions.GetNumeral(index); if (submissionSlotIndex >= 0) { name += "#" + StringExtensions.GetNumeral(submissionSlotIndex); } return name; } internal static string MakeAnonymousTypeBackingFieldName(string propertyName) { return "<" + propertyName + ">i__Field"; } internal static string MakeAnonymousTypeParameterName(string propertyName) { return "<" + propertyName + ">j__TPar"; } internal static string MakeStateMachineTypeName(string methodName, int methodOrdinal, int generation) { Debug.Assert(generation >= 0); Debug.Assert(methodOrdinal >= -1); return MakeMethodScopedSynthesizedName(GeneratedNameKind.StateMachineType, methodOrdinal, generation, methodName); } internal static string MakeBaseMethodWrapperName(int uniqueId) { Debug.Assert((char)GeneratedNameKind.BaseMethodWrapper == 'n'); return "<>n__" + StringExtensions.GetNumeral(uniqueId); } internal static string MakeLambdaMethodName(string methodName, int methodOrdinal, int methodGeneration, int lambdaOrdinal, int lambdaGeneration) { Debug.Assert(methodOrdinal >= -1); Debug.Assert(methodGeneration >= 0); Debug.Assert(lambdaOrdinal >= 0); Debug.Assert(lambdaGeneration >= 0); // The EE displays the containing method name and unique id in the stack trace, // and uses it to find the original binding context. return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaMethod, methodOrdinal, methodGeneration, methodName, entityOrdinal: lambdaOrdinal, entityGeneration: lambdaGeneration); } internal static string MakeLambdaCacheFieldName(int methodOrdinal, int generation, int lambdaOrdinal, int lambdaGeneration) { Debug.Assert(methodOrdinal >= -1); Debug.Assert(lambdaOrdinal >= 0); return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaCacheField, methodOrdinal, generation, entityOrdinal: lambdaOrdinal, entityGeneration: lambdaGeneration); } internal static string MakeLocalFunctionName(string methodName, string localFunctionName, int methodOrdinal, int methodGeneration, int lambdaOrdinal, int lambdaGeneration) { Debug.Assert(methodOrdinal >= -1); Debug.Assert(methodGeneration >= 0); Debug.Assert(lambdaOrdinal >= 0); Debug.Assert(lambdaGeneration >= 0); return MakeMethodScopedSynthesizedName(GeneratedNameKind.LocalFunction, methodOrdinal, methodGeneration, methodName, localFunctionName, GeneratedNameConstants.LocalFunctionNameTerminator, lambdaOrdinal, lambdaGeneration); } private static string MakeMethodScopedSynthesizedName( GeneratedNameKind kind, int methodOrdinal, int methodGeneration, string? methodName = null, string? suffix = null, char suffixTerminator = default, int entityOrdinal = -1, int entityGeneration = -1) { Debug.Assert(methodOrdinal >= -1); Debug.Assert(methodGeneration >= 0 || methodGeneration == -1 && methodOrdinal == -1); Debug.Assert(entityOrdinal >= -1); Debug.Assert(entityGeneration >= 0 || entityGeneration == -1 && entityOrdinal == -1); Debug.Assert(entityGeneration == -1 || entityGeneration >= methodGeneration); var result = PooledStringBuilder.GetInstance(); var builder = result.Builder; builder.Append('<'); if (methodName != null) { builder.Append(methodName); // CLR generally allows names with dots, however some APIs like IMetaDataImport // can only return full type names combined with namespaces. // see: http://msdn.microsoft.com/en-us/library/ms230143.aspx (IMetaDataImport::GetTypeDefProps) // When working with such APIs, names with dots become ambiguous since metadata // consumer cannot figure where namespace ends and actual type name starts. // Therefore it is a good practice to avoid type names with dots. // As a replacement use a character not allowed in C# identifier to avoid conflicts. if (kind.IsTypeName()) { builder.Replace('.', GeneratedNameConstants.DotReplacementInTypeNames); } } builder.Append('>'); builder.Append((char)kind); if (suffix != null || methodOrdinal >= 0 || entityOrdinal >= 0) { builder.Append(GeneratedNameConstants.SuffixSeparator); builder.Append(suffix); if (suffixTerminator != default) { builder.Append(suffixTerminator); } if (methodOrdinal >= 0) { builder.Append(methodOrdinal); AppendOptionalGeneration(builder, methodGeneration); } if (entityOrdinal >= 0) { if (methodOrdinal >= 0) { builder.Append(IdSeparator); } builder.Append(entityOrdinal); AppendOptionalGeneration(builder, entityGeneration); } } return result.ToStringAndFree(); } private static void AppendOptionalGeneration(StringBuilder builder, int generation) { if (generation > 0) { builder.Append(GenerationSeparator); builder.Append(generation); } } internal static string MakeHoistedLocalFieldName(SynthesizedLocalKind kind, int slotIndex, string? localName = null) { Debug.Assert((localName != null) == (kind == SynthesizedLocalKind.UserDefined)); Debug.Assert(slotIndex >= 0); Debug.Assert(kind.IsLongLived()); // Lambda display class local follows a different naming pattern. // EE depends on the name format. // There's logic in the EE to recognize locals that have been captured by a lambda // and would have been hoisted for the state machine. Basically, we just hoist the local containing // the instance of the lambda display class and retain its original name (rather than using an // iterator local name). See FUNCBRECEE::ImportIteratorMethodInheritedLocals. var result = PooledStringBuilder.GetInstance(); var builder = result.Builder; builder.Append('<'); if (localName != null) { Debug.Assert(localName.IndexOf('.') == -1); builder.Append(localName); } builder.Append('>'); if (kind == SynthesizedLocalKind.LambdaDisplayClass) { builder.Append((char)GeneratedNameKind.DisplayClassLocalOrField); } else if (kind == SynthesizedLocalKind.UserDefined) { builder.Append((char)GeneratedNameKind.HoistedLocalField); } else { builder.Append((char)GeneratedNameKind.HoistedSynthesizedLocalField); } builder.Append("__"); builder.Append(slotIndex + 1); return result.ToStringAndFree(); } internal static string AsyncAwaiterFieldName(int slotIndex) { Debug.Assert((char)GeneratedNameKind.AwaiterField == 'u'); return "<>u__" + StringExtensions.GetNumeral(slotIndex + 1); } internal static string MakeCachedFrameInstanceFieldName() { Debug.Assert((char)GeneratedNameKind.LambdaCacheField == '9'); return "<>9"; } internal static string? MakeSynthesizedLocalName(SynthesizedLocalKind kind, ref int uniqueId) { Debug.Assert(kind.IsLongLived()); // Lambda display class local has to be named. EE depends on the name format. if (kind == SynthesizedLocalKind.LambdaDisplayClass) { return MakeLambdaDisplayLocalName(uniqueId++); } return null; } internal static string MakeSynthesizedInstrumentationPayloadLocalFieldName(int uniqueId) { return GeneratedNameConstants.SynthesizedLocalNamePrefix + "InstrumentationPayload" + StringExtensions.GetNumeral(uniqueId); } internal static string MakeLambdaDisplayLocalName(int uniqueId) { Debug.Assert((char)GeneratedNameKind.DisplayClassLocalOrField == '8'); return GeneratedNameConstants.SynthesizedLocalNamePrefix + "<>8__locals" + StringExtensions.GetNumeral(uniqueId); } internal static string MakeFixedFieldImplementationName(string fieldName) { // the native compiler adds numeric digits at the end. Roslyn does not. Debug.Assert((char)GeneratedNameKind.FixedBufferField == 'e'); return "<" + fieldName + ">e__FixedBuffer"; } internal static string MakeStateMachineStateFieldName() { // Microsoft.VisualStudio.VIL.VisualStudioHost.AsyncReturnStackFrame depends on this name. Debug.Assert((char)GeneratedNameKind.StateMachineStateField == '1'); return "<>1__state"; } internal static string MakeAsyncIteratorPromiseOfValueOrEndFieldName() { Debug.Assert((char)GeneratedNameKind.AsyncIteratorPromiseOfValueOrEndBackingField == 'v'); return "<>v__promiseOfValueOrEnd"; } internal static string MakeAsyncIteratorCombinedTokensFieldName() { Debug.Assert((char)GeneratedNameKind.CombinedTokensField == 'x'); return "<>x__combinedTokens"; } internal static string MakeIteratorCurrentFieldName() { Debug.Assert((char)GeneratedNameKind.IteratorCurrentBackingField == '2'); return "<>2__current"; } internal static string MakeDisposeModeFieldName() { Debug.Assert((char)GeneratedNameKind.DisposeModeField == 'w'); return "<>w__disposeMode"; } internal static string MakeIteratorCurrentThreadIdFieldName() { Debug.Assert((char)GeneratedNameKind.IteratorCurrentThreadIdField == 'l'); return "<>l__initialThreadId"; } internal static string ThisProxyFieldName() { Debug.Assert((char)GeneratedNameKind.ThisProxyField == '4'); return "<>4__this"; } internal static string StateMachineThisParameterProxyName() { return StateMachineParameterProxyFieldName(ThisProxyFieldName()); } internal static string StateMachineParameterProxyFieldName(string parameterName) { Debug.Assert((char)GeneratedNameKind.StateMachineParameterProxyField == '3'); return "<>3__" + parameterName; } internal static string MakeDynamicCallSiteContainerName(int methodOrdinal, int localFunctionOrdinal, int generation) { return MakeMethodScopedSynthesizedName(GeneratedNameKind.DynamicCallSiteContainerType, methodOrdinal, generation, suffix: localFunctionOrdinal != -1 ? localFunctionOrdinal.ToString() : null, suffixTerminator: localFunctionOrdinal != -1 ? '_' : default); } internal static string MakeDynamicCallSiteFieldName(int uniqueId) { Debug.Assert((char)GeneratedNameKind.DynamicCallSiteField == 'p'); return "<>p__" + StringExtensions.GetNumeral(uniqueId); } internal const string ActionDelegateNamePrefix = "<>A"; internal const string FuncDelegateNamePrefix = "<>F"; private const int DelegateNamePrefixLength = 3; private const int DelegateNamePrefixLengthWithOpenBrace = 4; /// <summary> /// 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> internal static string MakeSynthesizedDelegateName(RefKindVector byRefs, bool returnsVoid, int generation) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(returnsVoid ? ActionDelegateNamePrefix : FuncDelegateNamePrefix); if (!byRefs.IsNull) { builder.Append(byRefs.ToRefKindString()); } AppendOptionalGeneration(builder, generation); return pooledBuilder.ToStringAndFree(); } internal static bool TryParseSynthesizedDelegateName(string name, out RefKindVector byRefs, out bool returnsVoid, out int generation, out int parameterCount) { byRefs = default; parameterCount = 0; generation = 0; name = MetadataHelpers.InferTypeArityAndUnmangleMetadataName(name, out var arity); returnsVoid = name.StartsWith(ActionDelegateNamePrefix); if (!returnsVoid && !name.StartsWith(FuncDelegateNamePrefix)) { 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) { return false; } // The ref kind string is between the two braces var refKindString = name[DelegateNamePrefixLengthWithOpenBrace..lastBraceIndex]; 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) { // Format is a '#' followed by the generation number if (name[lastBraceIndex + 1] != '#') { return false; } if (!int.TryParse(name[(lastBraceIndex + 2)..], out generation)) { return false; } } Debug.Assert(name == MakeSynthesizedDelegateName(byRefs, returnsVoid, generation)); return true; } internal static string AsyncBuilderFieldName() { // Microsoft.VisualStudio.VIL.VisualStudioHost.AsyncReturnStackFrame depends on this name. Debug.Assert((char)GeneratedNameKind.AsyncBuilderField == 't'); return "<>t__builder"; } internal static string ReusableHoistedLocalFieldName(int number) { Debug.Assert((char)GeneratedNameKind.ReusableHoistedLocalField == '7'); return "<>7__wrap" + StringExtensions.GetNumeral(number); } internal static string LambdaCopyParameterName(int ordinal) { return "<p" + StringExtensions.GetNumeral(ordinal) + ">"; } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Portable/Symbols/Synthesized/RefKindVector.cs
// 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 System; using System.Collections.Generic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal struct RefKindVector : IEquatable<RefKindVector> { private BitVector _bits; internal static RefKindVector Create(int capacity) { return new RefKindVector(capacity); } private RefKindVector(int capacity) { _bits = BitVector.Create(capacity * 2); } internal bool IsNull => _bits.IsNull; internal int Capacity => _bits.Capacity / 2; internal IEnumerable<ulong> Words() => _bits.Words(); internal RefKind this[int index] { get { index *= 2; return (_bits[index + 1], _bits[index]) switch { (false, false) => RefKind.None, (false, true) => RefKind.Ref, (true, false) => RefKind.Out, (true, true) => RefKind.RefReadOnly, }; } set { index *= 2; (_bits[index + 1], _bits[index]) = value switch { RefKind.None => (false, false), RefKind.Ref => (false, true), RefKind.Out => (true, false), RefKind.RefReadOnly => (true, true), _ => throw ExceptionUtilities.UnexpectedValue(value) }; } } public bool Equals(RefKindVector other) { return _bits.Equals(other._bits); } public override bool Equals(object? obj) { return obj is RefKindVector other && this.Equals(other); } public override int GetHashCode() { return _bits.GetHashCode(); } } }
// 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 System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal struct RefKindVector : IEquatable<RefKindVector> { private BitVector _bits; internal static RefKindVector Create(int capacity) { return new RefKindVector(capacity); } private RefKindVector(int capacity) { _bits = BitVector.Create(capacity * 2); } private RefKindVector(BitVector bits) { _bits = bits; } internal bool IsNull => _bits.IsNull; internal int Capacity => _bits.Capacity / 2; internal IEnumerable<ulong> Words() => _bits.Words(); internal RefKind this[int index] { get { index *= 2; return (_bits[index + 1], _bits[index]) switch { (false, false) => RefKind.None, (false, true) => RefKind.Ref, (true, false) => RefKind.Out, (true, true) => RefKind.RefReadOnly, }; } set { index *= 2; (_bits[index + 1], _bits[index]) = value switch { RefKind.None => (false, false), RefKind.Ref => (false, true), RefKind.Out => (true, false), RefKind.RefReadOnly => (true, true), _ => throw ExceptionUtilities.UnexpectedValue(value) }; } } public bool Equals(RefKindVector other) { return _bits.Equals(other._bits); } public override bool Equals(object? obj) { return obj is RefKindVector other && this.Equals(other); } public override int GetHashCode() { return _bits.GetHashCode(); } public string ToRefKindString() { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append("{"); int i = 0; foreach (int byRefIndex in this.Words()) { if (i > 0) { builder.Append(","); } builder.AppendFormat("{0:x8}", byRefIndex); i++; } builder.Append("}"); Debug.Assert(i > 0); return pooledBuilder.ToStringAndFree(); } public static bool TryParse(string refKindString, int capacity, out RefKindVector result) { ulong? firstWord = null; ArrayBuilder<ulong>? otherWords = null; foreach (var word in refKindString.Split(',')) { ulong value; try { value = Convert.ToUInt64(word, 16); } catch (Exception) { result = default; return false; } if (firstWord is null) { firstWord = value; } else { otherWords ??= ArrayBuilder<ulong>.GetInstance(); otherWords.Add(value); } } Debug.Assert(firstWord is not null); var bitVector = BitVector.FromWords(firstWord.Value, otherWords?.ToArrayAndFree() ?? Array.Empty<ulong>(), capacity * 2); result = new RefKindVector(bitVector); return true; } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { /// <summary> /// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test. /// </summary> public class EditAndContinueTests : EditAndContinueTestBase { private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers) { var currentGenerationReader = readers.Last(); foreach (var typeRefHandle in currentGenerationReader.TypeReferences) { var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle); yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}"; } } [Fact] public void DeltaHeapsStartWithEmptyItem() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { return ""a""; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var s = MetadataTokens.StringHandle(0); Assert.Equal("", reader1.GetString(s)); var b = MetadataTokens.BlobHandle(0); Assert.Equal(0, reader1.GetBlobBytes(b).Length); var us = MetadataTokens.UserStringHandle(0); Assert.Equal("", reader1.GetUserString(us)); } [Fact] public void Delta_AssemblyDefTable() { var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }"; var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); // AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed: Assert.True(md0.MetadataReader.IsAssembly); Assert.False(diff1.GetMetadata().Reader.IsAssembly); } [Fact] public void SemanticErrors_MethodBody() { var source0 = MarkedSource(@" class C { static void E() { int x = 1; System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void E() { int x = Unknown(2); System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(2); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Semantic errors are reported only for the bodies of members being emitted. var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (6,17): error CS0103: The name 'Unknown' does not exist in the current context // int x = Unknown(2); Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17)); var diffGood = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffGood.EmitResult.Diagnostics.Verify(); diffGood.VerifyIL(@"C.G", @" { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.2 IL_0002: call ""void System.Console.WriteLine(int)"" IL_0007: nop IL_0008: ret } "); } [Fact] public void SemanticErrors_Declaration() { var source0 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(1); } } "); var source1 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(2); } } class Bad : Bad { } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // All declaration errors are reported regardless of what member do we emit. diff.EmitResult.Diagnostics.Verify( // (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad' // class Bad : Bad Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7)); } [Fact] public void ModifyMethod() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // 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"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_RenameParameter() { var source0 = @"class C { static string F(int a) { return a.ToString(); } }"; var source1 = @"class C { static string F(int x) { return x.ToString(); } }"; var source2 = @"class C { static string F(int b) { return b.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "a"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // 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"); CheckNames(readers, reader1.GetParameterDefNames(), "x"); CheckEncLogDefinitions(reader1, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.StandAloneSig)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), "ToString"); CheckNames(readers, reader2.GetParameterDefNames(), "b"); CheckEncLogDefinitions(reader2, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(3, TableIndex.StandAloneSig)); } [CompilerTrait(CompilerFeature.Tuples)] [Fact] public void ModifyMethod_WithTuples() { var source0 = @"class C { static void Main() { } static (int, int) F() { return (1, 2); } }"; var source1 = @"class C { static void Main() { } static (int, int) F() { return (2, 3); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // 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"); CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes1() { using var _ = new EditAndContinueTest(options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20) .AddGeneration( source: @" class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }", validator: g => { g.VerifyTypeDefNames("<Module>", "C"); g.VerifyMethodDefNames("Main", "F", ".ctor"); g.VerifyMemberRefNames(/*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); g.VerifyTableSize(TableIndex.CustomAttribute, 4); }) .AddGeneration( source: @" class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }", edits: new[] { Edit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, validator: g => { g.VerifyTypeDefNames(); g.VerifyMethodDefNames("F"); g.VerifyMemberRefNames( /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); g.VerifyTableSize(TableIndex.CustomAttribute, 1); g.VerifyEncLog(new[] { Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default) // Row 4, so updating existing CustomAttribute }); g.VerifyEncMap(new[] { Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef) }); }) // Add attribute to method, and to class .AddGeneration( source: @" [System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }", edits: new[] { Edit(SemanticEditKind.Update, c => c.GetMember("C")), Edit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, validator: g => { g.VerifyTypeDefNames("C"); g.VerifyMethodDefNames("F"); g.VerifyMemberRefNames( /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); g.VerifyTableSize(TableIndex.CustomAttribute, 3); g.VerifyEncLog(new[] { Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default) // Row 6 adding a new CustomAttribute }); g.VerifyEncMap(new[] { Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(2, TableIndex.TypeDef), Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(10, TableIndex.MemberRef), Handle(11, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef) }); }) // Add attribute before existing attributes .AddGeneration( source: @" [System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }", edits: new[] { Edit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, validator: g => { g.VerifyTypeDefNames(); g.VerifyMethodDefNames("F"); g.VerifyMemberRefNames( /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); g.VerifyTableSize(TableIndex.CustomAttribute, 3); g.VerifyEncLog(new[] { Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2 Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default) // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted }); g.VerifyEncMap(new[] { Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(19, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(12, TableIndex.MemberRef), Handle(13, TableIndex.MemberRef), Handle(14, TableIndex.MemberRef), Handle(15, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef) }); }) .Verify(); } [Fact] public void ModifyMethod_WithAttributes2() { var source0 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A"")] static string A() { return null; } } "; var source1 = @" [System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")] static string A() { return null; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0_1 = compilation0.GetMember<MethodSymbol>("C.F"); var method0_2 = compilation0.GetMember<MethodSymbol>("D.A"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1_1 = compilation1.GetMember<MethodSymbol>("C.F"); var method1_2 = compilation1.GetMember<MethodSymbol>("D.A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1), SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2))); // 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", "A"); CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var source2 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // 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"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader2, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes2() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = source0; // Remove the attribute we just added var source3 = source1; // Add the attribute back again var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation1.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // 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"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames()); CheckAttributes(reader2, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader3, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row CheckEncMap(reader3, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")] [Fact] public void PartialMethod() { var source = @"partial class C { static partial void M1(); static partial void M2(); static partial void M3(); static partial void M1() { } static partial void M2() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor"); var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); var methods = diff1.TestData.GetMethodsByName(); Assert.Equal(1, methods.Count); Assert.True(methods.ContainsKey("C.M2()")); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "M2"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Method_WithAttributes_Add() { var source0 = @"class C { static void Main() { } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); // 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"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_ParameterAttributes() { var source0 = @"class C { static void Main() { } static string F(string input, int a) { return input; } }"; var source1 = @"class C { static void Main() { } static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; } static void G(string input) { } }"; var source2 = @"class C { static void Main() { } static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; } static void G([System.ComponentModel.Description(""input"")]string input) { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var methodF0 = compilation0.GetMember<MethodSymbol>("C.F"); var methodF1 = compilation1.GetMember<MethodSymbol>("C.F"); var methodG1 = compilation1.GetMember<MethodSymbol>("C.G"); var methodG2 = compilation2.GetMember<MethodSymbol>("C.G"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "input", "a"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodF0, methodF1), SemanticEdit.Create(SemanticEditKind.Insert, null, methodG1))); // 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", "G"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor"); CheckNames(readers, reader1.GetParameterDefNames(), "input", "a", "input"); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.Param), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), // New method, G Row(1, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param Row(2, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), // New param on method, G Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Support for the above Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param), Handle(5, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodG1, methodG2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "G"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor"); CheckNames(readers, reader2.GetParameterDefNames(), "input"); CheckAttributes(reader2, new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param, from the first delta Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(4, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef), Handle(5, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyDelegateInvokeMethod_AddAttributes() { var source0 = @" class A : System.Attribute { } delegate void D(int x); "; var source1 = @" class A : System.Attribute { } delegate void D([A]int x); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var invoke0 = compilation0.GetMember<MethodSymbol>("D.Invoke"); var beginInvoke0 = compilation0.GetMember<MethodSymbol>("D.BeginInvoke"); var invoke1 = compilation1.GetMember<MethodSymbol>("D.Invoke"); var beginInvoke1 = compilation1.GetMember<MethodSymbol>("D.BeginInvoke"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, invoke0, invoke1), SemanticEdit.Create(SemanticEditKind.Update, beginInvoke0, beginInvoke1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "Invoke", "BeginInvoke"); CheckNames(readers, reader1.GetParameterDefNames(), "x", "x", "callback", "object"); CheckAttributes(reader1, new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Param), Handle(1, TableIndex.MethodDef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Updating existing parameter defs Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Adding new custom attribute rows Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param), Handle(6, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(2, TableIndex.AssemblyRef)); } /// <summary> /// Add a method that requires entries in the ParameterDefs table. /// Specifically, normal parameters or return types with attributes. /// Add the method in the first edit, then modify the method in the second. /// </summary> [Fact] public void Method_WithParameterAttributes_AddThenUpdate() { var source0 = @"class A : System.Attribute { } class C { }"; var source1 = @"class A : System.Attribute { } class C { [return:A]static object F(int arg = 1) => arg; }"; var source2 = @"class A : System.Attribute { } class C { [return:A]static object F(int arg = 1) => null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetParameterDefNames(), "", "arg"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(1, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetParameterDefNames(), "", "arg"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C"); CheckNames(readers, diff2.EmitResult.UpdatedMethods, "F"); CheckEncLogDefinitions(reader2, Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), // C.F2 Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(2, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void Method_WithEmbeddedAttributes_AndThenUpdate() { var source0 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { class C { static void Main() { } } } "; var source1 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 1 }[0]; } }"; var source2 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} } }"; var source3 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} readonly ref readonly string?[]? F() => throw null; } }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main"); var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id"); var g1 = compilation1.GetMember<MethodSymbol>("N.C.G"); var g2 = compilation2.GetMember<MethodSymbol>("N.C.G"); var h2 = compilation2.GetMember<MethodSymbol>("N.C.H"); var f3 = compilation3.GetMember<MethodSymbol>("N.C.F"); // Verify full metadata contains expected rows. using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, id1), SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute}"); diff1.VerifyIL("N.C.Main", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: nop IL_0001: call ""ref readonly int N.C.G()"" IL_0006: call ""ref readonly int N.C.Id(in int)"" IL_000b: pop IL_000c: ret } "); diff1.VerifyIL("N.C.Id", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } "); diff1.VerifyIL("N.C.G", @" { // Code size 17 (0x11) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.1 IL_0009: stelem.i4 IL_000a: ldc.i4.0 IL_000b: ldelema ""int"" IL_0010: ret } "); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader0 = md0.MetadataReader; var reader1 = md1.Reader; var readers = new List<MetadataReader>() { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute"); CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g1, g2), SemanticEdit.Create(SemanticEditKind.Insert, null, h2))); // synthesized member for nullable annotations added: diff2.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); // note: NullableAttribute has 2 ctors, NullableContextAttribute has one CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute"); CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H"); // two new TypeDefs emitted for the attributes: CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(6, TableIndex.TypeDef), Handle(7, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(2, TableIndex.Field), Handle(7, TableIndex.MethodDef), Handle(8, TableIndex.MethodDef), Handle(9, TableIndex.MethodDef), Handle(10, TableIndex.MethodDef), Handle(11, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(6, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(12, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3))); // no change in synthesized members: diff3.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); // no new type defs: CheckNames(readers, reader3.GetTypeDefFullNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); } [Fact] public void Field_Add() { var source0 = @"class C { string F = ""F""; }"; var source1 = @"class C { string F = ""F""; string G = ""G""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetFieldDefNames(), "F"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var method1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "G"); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Property_Accessor_Update() { var source0 = @"class C { object P { get { return 1; } } }"; var source1 = @"class C { object P { get { return 2; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P"); var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetPropertyDefNames(), "P"); CheckNames(readers, reader1.GetMethodDefNames(), "get_P"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Property_Add() { var source0 = @" class C { } "; var source1 = @" class C { object R { get { return null; } } } "; var source2 = @" class C { object R { get { return null; } } object Q { get; set; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var r1 = compilation1.GetMember<PropertySymbol>("C.R"); var q2 = compilation2.GetMember<PropertySymbol>("C.Q"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, r1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetPropertyDefNames(), "R"); CheckNames(readers, reader1.GetMethodDefNames(), "get_R"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.MethodDef), Handle(1, TableIndex.StandAloneSig), Handle(1, TableIndex.PropertyMap), Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodSemantics)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, q2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField"); CheckNames(readers, reader2.GetPropertyDefNames(), "Q"); CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(1, TableIndex.Field), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(3, TableIndex.MethodSemantics)); } [Fact] public void Event_Add() { var source0 = @" class C { }"; var source1 = @" class C { event System.Action E; }"; var source2 = @" class C { event System.Action E; event System.Action G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var e1 = compilation1.GetMember<EventSymbol>("C.E"); var g2 = compilation2.GetMember<EventSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, e1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "E"); CheckNames(readers, reader1.GetMethodDefNames(), "add_E", "remove_E"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(1, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(1, TableIndex.EventMap), Handle(1, TableIndex.Event), Handle(1, TableIndex.MethodSemantics), Handle(2, TableIndex.MethodSemantics)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "G"); CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader2, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.Field), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics)); } [WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")] [Fact] public void EventFields() { var source0 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 1; } } "); var source1 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 10; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 3 .locals init (int V_0) IL_0000: nop IL_0001: ldsfld ""System.EventHandler C.handler"" IL_0006: ldnull IL_0007: ldnull IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)"" IL_000d: nop IL_000e: ldc.i4.s 10 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); } [Fact] public void UpdateType_AddAttributes() { var source0 = @" class C { }"; var source1 = @" [System.ComponentModel.Description(""C"")] class C { }"; var source2 = @" [System.ComponentModel.Description(""C"")] [System.ObsoleteAttribute] class C { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); Assert.Equal(2, reader2.CustomAttributes.Count); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute)); } [Fact] public void ReplaceType() { var source0 = @" class C { void F(int x) {} } "; var source1 = @" class C { void F(int x, int y) { } }"; var source2 = @" class C { void F(int x, int y) { System.Console.WriteLine(1); } }"; var source3 = @" [System.Obsolete] class C { void F(int x, int y) { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var c3 = compilation3.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); var f3 = c3.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C#1"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param)); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C#2"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2"); CheckEncLogDefinitions(reader2, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param)); // This update is an EnC update - even reloadable types are update in-place var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, c2, c3), SemanticEdit.Create(SemanticEditKind.Update, f2, f3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames(), "C#2"); CheckNames(readers, diff3.EmitResult.ChangedTypes, "C#2"); CheckEncLogDefinitions(reader3, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader3, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void EventFields_Attributes() { var source0 = MarkedSource(@" using System; class C { static event EventHandler E; } "); var source1 = MarkedSource(@" using System; class C { [System.Obsolete] static event EventHandler E; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var event0 = compilation0.GetMember<EventSymbol>("C.E"); var event1 = compilation1.GetMember<EventSymbol>("C.E"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "add_E", "remove_E", ".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, event0, event1))); // 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()); CheckNames(readers, reader1.GetEventDefNames(), "E"); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(10, TableIndex.MemberRef))); CheckEncLogDefinitions(reader1, Row(1, TableIndex.Event, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(8, TableIndex.CustomAttribute), Handle(1, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics)); } [Fact] public void ReplaceType_AsyncLambda() { var source0 = @" using System.Threading.Tasks; class C { void F(int x) { Task.Run(async() => {}); } } "; var source1 = @" using System.Threading.Tasks; class C { void F(bool y) { Task.Run(async() => {}); } } "; var source2 = @" using System.Threading.Tasks; class C { void F(uint z) { Task.Run(async() => {}); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c", "<<F>b__0_0>d"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; // A new nested type <>c is generated in C#1 CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "<>c", "<<F>b__0#1_0#1>d"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "<>c", "<<F>b__0#1_0#1>d"); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; // A new nested type <>c is generated in C#2 CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "<>c", "<<F>b__0#2_0#2>d"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "<>c", "<<F>b__0#2_0#2>d"); } [Fact] public void ReplaceType_AsyncLambda_InNestedType() { var source0 = @" using System.Threading.Tasks; class C { class D { void F(int x) { Task.Run(async() => {}); } } } "; var source1 = @" using System.Threading.Tasks; class C { class D { void F(bool y) { Task.Run(async() => {}); } } } "; var source2 = @" using System.Threading.Tasks; class C { class D { void F(uint z) { Task.Run(async() => {}); } } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D", "<>c", "<<F>b__0_0>d"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; // A new nested type <>c is generated in C#1 CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "D", "<>c", "<<F>b__0#1_0#1>d"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "D", "<>c", "<<F>b__0#1_0#1>d"); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; // A new nested type <>c is generated in C#2 CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "D", "<>c", "<<F>b__0#2_0#2>d"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "D", "<>c", "<<F>b__0#2_0#2>d"); } [Fact] public void AddNestedTypeAndMembers() { var source0 = @"class A { class B { } static object F() { return new B(); } }"; var source1 = @"class A { class B { } class C { class D { } static object F; internal static object G() { return F; } } static object F() { return C.G(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C"); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C", "D"); CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor"); CheckNames(readers, diff1.EmitResult.UpdatedMethods, "F"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "C", "D"); Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(3, TableIndex.NestedClass)); } /// <summary> /// Nested types should be emitted in the /// same order as full emit. /// </summary> [Fact] public void AddNestedTypesOrder() { var source0 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } }"; var source1 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } class B3 { class C3 { } } class B4 { class C4 { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2"); Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4"); Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass)); } [Fact] public void AddNestedGenericType() { var source0 = @"class A { class B<T> { } static object F() { return null; } }"; var source1 = @"class A { class B<T> { internal class C<U> { internal object F<V>() where V : T, new() { return new C<V>(); } } } static object F() { return new B<A>.C<B<object>>().F<A>(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "B`1", "C`1"); CheckNames(readers, reader1.GetTypeDefNames(), "C`1"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.TypeSpec), Handle(2, TableIndex.TypeSpec), Handle(3, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(2, TableIndex.GenericParam), Handle(3, TableIndex.GenericParam), Handle(4, TableIndex.GenericParam), Handle(1, TableIndex.MethodSpec), Handle(1, TableIndex.GenericParamConstraint)); } [Fact] [WorkItem(54939, "https://github.com/dotnet/roslyn/issues/54939")] public void AddNamespace() { var source0 = @" class C { static void Main() { } }"; var source1 = @" namespace N1.N2 { class D { public static void F() { } } } class C { static void Main() => N1.N2.D.F(); }"; var source2 = @" namespace N1.N2 { class D { public static void F() { } } namespace M1.M2 { class E { public static void G() { } } } } class C { static void Main() => N1.N2.M1.M2.E.G(); }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var main0 = compilation0.GetMember<MethodSymbol>("C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("C.Main"); var main2 = compilation2.GetMember<MethodSymbol>("C.Main"); var d1 = compilation1.GetMember<NamedTypeSymbol>("N1.N2.D"); var e2 = compilation2.GetMember<NamedTypeSymbol>("N1.N2.M1.M2.E"); using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, d1))); diff1.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N1.N2.D.F()"" IL_0005: nop IL_0006: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main1, main2), SemanticEdit.Create(SemanticEditKind.Insert, null, e2))); diff2.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N1.N2.M1.M2.E.G()"" IL_0005: nop IL_0006: ret }"); } [Fact] public void ModifyExplicitImplementation() { var source = @"interface I { void M(); } class C : I { void I.M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddThenModifyExplicitImplementation() { var source0 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } }"; var source1 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } void I.M() { } }"; var source2 = source1; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(2, TableIndex.MethodImpl), Handle(2, TableIndex.AssemblyRef)); var generation1 = diff1.NextGeneration; var diff2 = compilation2.EmitDifference( generation1, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetMethodDefNames(), "I.M"); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(7, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(3, TableIndex.AssemblyRef)); } [WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")] [Fact] public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation() { var source = @" interface I { void M(); } class C : I { public C() { } void I.M() { } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddAndModifyInterfaceMembers() { var source0 = @" using System; interface I { }"; var source1 = @" using System; interface I { static int X = 10; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } interface J { } }"; var source2 = @" using System; interface I { static int X = 2; static event Action Y; static I() { X--; } static void M() { X++; } void N() { X++; } static int P { get => 3; set { X++; } } int Q { get => 3; set { X++; } } static event Action E { add { X++; } remove { X++; } } event Action F { add { X++; } remove { X++; } } interface J { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J"); var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P"); var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P"); var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q"); var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q"); var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E"); var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E"); var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F"); var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F"); var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var x2 = compilation2.GetMember<FieldSymbol>("I.X"); var m2 = compilation2.GetMember<MethodSymbol>("I.M"); var n2 = compilation2.GetMember<MethodSymbol>("I.N"); var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P"); var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P"); var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q"); var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q"); var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E"); var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E"); var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F"); var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F"); var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, x1), SemanticEdit.Create(SemanticEditKind.Insert, null, y1), SemanticEdit.Create(SemanticEditKind.Insert, null, m1), SemanticEdit.Create(SemanticEditKind.Insert, null, n1), SemanticEdit.Create(SemanticEditKind.Insert, null, p1), SemanticEdit.Create(SemanticEditKind.Insert, null, q1), SemanticEdit.Create(SemanticEditKind.Insert, null, e1), SemanticEdit.Create(SemanticEditKind.Insert, null, f1), SemanticEdit.Create(SemanticEditKind.Insert, null, j1), SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J"); CheckNames(readers, reader1.GetTypeDefNames(), "J"); CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y"); CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, x1, x2), SemanticEdit.Create(SemanticEditKind.Update, m1, m2), SemanticEdit.Create(SemanticEditKind.Update, n1, n2), SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2), SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2), SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2), SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2), SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2), SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2), SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2), SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2), SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "X"); CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(3, TableIndex.Event, EditAndContinueOperation.Default), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); diff2.VerifyIL(@" { // Code size 14 (0xe) .maxstack 8 IL_0000: nop IL_0001: ldsfld 0x04000001 IL_0006: ldc.i4.1 IL_0007: add IL_0008: stsfld 0x04000001 IL_000d: ret } { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.3 IL_0001: ret } { // Code size 20 (0x14) .maxstack 8 IL_0000: ldc.i4.2 IL_0001: stsfld 0x04000001 IL_0006: nop IL_0007: ldsfld 0x04000001 IL_000c: ldc.i4.1 IL_000d: sub IL_000e: stsfld 0x04000001 IL_0013: ret } "); } [Fact] public void AddAttributeReferences() { var source0 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static object F1; [A] static object P1 { get { return null; } } [B] static event D E1; } delegate void D(); "; var source1 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static void M2<[A]T>() { } [B] static object F1; [A] static object F2; [A] static object P1 { get { return null; } } [B] static object P2 { get { return null; } } [B] static event D E1; [A] static event D E2; } delegate void D(); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(9, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(12, TableIndex.MethodDef), Handle(13, TableIndex.MethodDef), Handle(14, TableIndex.MethodDef), Handle(15, TableIndex.MethodDef), Handle(8, TableIndex.Param), Handle(9, TableIndex.Param), Handle(7, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(18, TableIndex.CustomAttribute), Handle(19, TableIndex.CustomAttribute), Handle(20, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(2, TableIndex.Property), Handle(4, TableIndex.MethodSemantics), Handle(5, TableIndex.MethodSemantics), Handle(6, TableIndex.MethodSemantics), Handle(2, TableIndex.GenericParam)); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)), new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef))); } /// <summary> /// [assembly: ...] and [module: ...] attributes should /// not be included in delta metadata. /// </summary> [Fact] public void AssemblyAndModuleAttributeReferences() { var source0 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { }"; var source1 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { static void M() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var readers = new[] { reader0, md1.Reader }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, md1.Reader.GetTypeDefNames()); CheckNames(readers, md1.Reader.GetMethodDefNames(), "M"); CheckEncLog(md1.Reader, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M CheckEncMap(md1.Reader, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void OtherReferences() { var source0 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { } }"; var source1 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { object o; o = typeof(D); o = F; o = P; E += null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C"); CheckNames(reader0, reader0.GetEventDefNames(), "E"); CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor"); CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); // Emit delta metadata. var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetEventDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M"); CheckNames(readers, reader1.GetPropertyDefNames()); } [Fact] public void ArrayInitializer() { var source0 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3 }; } }"); var source1 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3, 4 }; } }"); var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll); var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs")); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M")))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL( @"{ // Code size 25 (0x19) .maxstack 4 IL_0000: nop IL_0001: ldc.i4.4 IL_0002: newarr 0x0100000D IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.4 IL_0016: stelem.i4 IL_0017: stloc.0 IL_0018: ret }"); diff1.VerifyPdb(new[] { 0x06000001 }, @"<symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" /> </files> <methods> <method token=""0x6000001""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""40"" document=""1"" /> <entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x19""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void PInvokeModuleRefAndImplMap() { var source0 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); }"; var source1 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); [DllImport(""msvcrt.dll"")] public static extern int puts(string s); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.ImplMap)); } /// <summary> /// ClassLayout and FieldLayout tables. /// </summary> [Fact] public void ClassAndFieldLayout() { var source0 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; }"; var source1 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; } [StructLayout(LayoutKind.Explicit, Pack=4)] class B { [FieldOffset(0)]internal short F; [FieldOffset(4)]internal short G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default), Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default), Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.ClassLayout), Handle(3, TableIndex.FieldLayout), Handle(4, TableIndex.FieldLayout), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void NamespacesAndOverloads() { var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source: @"class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); } } }"); var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2"); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var compilation1 = compilation0.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); } } }"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2]))); diff1.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret }"); var compilation2 = compilation1.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); M1(c); } } }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"), compilation2.GetMember<MethodSymbol>("M.C.M2")))); diff2.VerifyIL( @"{ // Code size 26 (0x1a) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000002 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000003 IL_0010: nop IL_0011: ldarg.0 IL_0012: ldarg.3 IL_0013: call 0x06000007 IL_0018: nop IL_0019: ret }"); } [Fact] public void TypesAndOverloads() { const string source = @"using System; struct A<T> { internal class B<U> { } } class B { } class C { static void M(A<B>.B<object> a) { M(a); M((A<B>.B<B>)null); } static void M(A<B>.B<B> a) { M(a); M((A<B>.B<object>)null); } static void M(A<B> a) { M(a); M((A<B>?)a); } static void M(Nullable<A<B>> a) { M(a); M(a.Value); } unsafe static void M(int* p) { M(p); M((byte*)p); } unsafe static void M(byte* p) { M(p); M((int*)p); } static void M(B[][] b) { M(b); M((object[][])b); } static void M(object[][] b) { M(b); M((B[][])b); } static void M(A<B[]>.B<object> b) { M(b); M((A<B[, ,]>.B<object>)null); } static void M(A<B[, ,]>.B<object> b) { M(b); M((A<B[]>.B<object>)null); } static void M(dynamic d) { M(d); M((dynamic[])d); } static void M(dynamic[] d) { M(d); M((dynamic)d); } static void M<T>(A<int>.B<T> t) where T : B { M(t); M((A<double>.B<int>)null); } static void M<T>(A<double>.B<T> t) where T : struct { M(t); M((A<int>.B<B>)null); } }"; var options = TestOptions.UnsafeDebugDll; var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef }); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var n = compilation0.GetMembers("C.M").Length; Assert.Equal(14, n); //static void M(A<B>.B<object> a) //{ // M(a); // M((A<B>.B<B>)null); //} var compilation1 = compilation0.WithSource(source); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0]))); diff1.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(A<B>.B<B> a) //{ // M(a); // M((A<B>.B<object>)null); //} var compilation2 = compilation1.WithSource(source); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1]))); diff2.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000003 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000002 IL_000e: nop IL_000f: ret }"); //static void M(A<B> a) //{ // M(a); // M((A<B>?)a); //} var compilation3 = compilation2.WithSource(source); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2]))); diff3.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000004 IL_0007: nop IL_0008: ldarg.0 IL_0009: newobj 0x0A000016 IL_000e: call 0x06000005 IL_0013: nop IL_0014: ret }"); //static void M(Nullable<A<B>> a) //{ // M(a); // M(a.Value); //} var compilation4 = compilation3.WithSource(source); var diff4 = compilation4.EmitDifference( diff3.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3]))); diff4.VerifyIL( @"{ // Code size 22 (0x16) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000005 IL_0007: nop IL_0008: ldarga.s V_0 IL_000a: call 0x0A000017 IL_000f: call 0x06000004 IL_0014: nop IL_0015: ret }"); //unsafe static void M(int* p) //{ // M(p); // M((byte*)p); //} var compilation5 = compilation4.WithSource(source); var diff5 = compilation5.EmitDifference( diff4.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4]))); diff5.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000006 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000007 IL_000e: nop IL_000f: ret }"); //unsafe static void M(byte* p) //{ // M(p); // M((int*)p); //} var compilation6 = compilation5.WithSource(source); var diff6 = compilation6.EmitDifference( diff5.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5]))); diff6.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000007 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000006 IL_000e: nop IL_000f: ret }"); //static void M(B[][] b) //{ // M(b); // M((object[][])b); //} var compilation7 = compilation6.WithSource(source); var diff7 = compilation7.EmitDifference( diff6.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6]))); diff7.VerifyIL( @"{ // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000008 IL_0007: nop IL_0008: ldarg.0 IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: call 0x06000009 IL_0010: nop IL_0011: ret }"); //static void M(object[][] b) //{ // M(b); // M((B[][])b); //} var compilation8 = compilation7.WithSource(source); var diff8 = compilation8.EmitDifference( diff7.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7]))); diff8.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000009 IL_0007: nop IL_0008: ldarg.0 IL_0009: castclass 0x1B00000A IL_000e: call 0x06000008 IL_0013: nop IL_0014: ret }"); //static void M(A<B[]>.B<object> b) //{ // M(b); // M((A<B[,,]>.B<object>)null); //} var compilation9 = compilation8.WithSource(source); var diff9 = compilation9.EmitDifference( diff8.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8]))); diff9.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000A IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000B IL_000e: nop IL_000f: ret }"); //static void M(A<B[,,]>.B<object> b) //{ // M(b); // M((A<B[]>.B<object>)null); //} var compilation10 = compilation9.WithSource(source); var diff10 = compilation10.EmitDifference( diff9.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9]))); diff10.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000B IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000A IL_000e: nop IL_000f: ret }"); // TODO: dynamic #if false //static void M(dynamic d) //{ // M(d); // M((dynamic[])d); //} previousMethod = compilation.GetMembers("C.M")[10]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(dynamic[] d) //{ // M(d); // M((dynamic)d); //} previousMethod = compilation.GetMembers("C.M")[11]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); #endif //static void M<T>(A<int>.B<T> t) where T : B //{ // M(t); // M((A<double>.B<int>)null); //} var compilation11 = compilation10.WithSource(source); var diff11 = compilation11.EmitDifference( diff10.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12]))); diff11.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000005 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000006 IL_000e: nop IL_000f: ret }"); //static void M<T>(A<double>.B<T> t) where T : struct //{ // M(t); // M((A<int>.B<B>)null); //} var compilation12 = compilation11.WithSource(source); var diff12 = compilation12.EmitDifference( diff11.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13]))); diff12.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000007 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000008 IL_000e: nop IL_000f: ret }"); } [Fact] public void Struct_ImplementSynthesizedConstructor() { var source0 = @" struct S { int a = 1; int b; } "; var source1 = @" struct S { int a = 1; int b; public S() { b = 2; } } "; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var ctor0 = compilation0.GetMember<MethodSymbol>("S..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("S..ctor"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); // Verify full metadata contains expected rows. var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "S"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1))); // 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(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } /// <summary> /// Types should be retained in deleted locals /// for correct alignment of remaining locals. /// </summary> [Fact] public void DeletedValueTypeLocal() { var source0 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var x = new S1(1, 2); var y = new S2(3); System.Console.WriteLine(y.C); } }"; var source1 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var y = new S2(3); System.Console.WriteLine(y.C); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.Main"); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); testData0.GetMethodData("C.Main").VerifyIL( @" { // Code size 31 (0x1f) .maxstack 3 .locals init (S1 V_0, //x S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""S1..ctor(int, int)"" IL_000a: ldloca.s V_1 IL_000c: ldc.i4.3 IL_000d: call ""S2..ctor(int)"" IL_0012: ldloc.1 IL_0013: ldfld ""int S2.C"" IL_0018: call ""void System.Console.WriteLine(int)"" IL_001d: nop IL_001e: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @"{ // Code size 22 (0x16) .maxstack 2 .locals init ([unchanged] V_0, S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_1 IL_0003: ldc.i4.3 IL_0004: call ""S2..ctor(int)"" IL_0009: ldloc.1 IL_000a: ldfld ""int S2.C"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret }"); } /// <summary> /// Instance and static constructors synthesized for /// PrivateImplementationDetails should not be /// generated for delta. /// </summary> [Fact] public void PrivateImplementationDetails() { var source = @"class C { static int[] F = new int[] { 1, 2, 3 }; int[] G = new int[] { 4, 5, 6 }; int M(int index) { return F[index] + G[index]; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var reader0 = md0.MetadataReader; var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames()); Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal))); } var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 3 .locals init ([int] V_0, int V_1) IL_0000: nop IL_0001: ldsfld ""int[] C.F"" IL_0006: ldarg.1 IL_0007: ldelem.i4 IL_0008: ldarg.0 IL_0009: ldfld ""int[] C.G"" IL_000e: ldarg.1 IL_000f: ldelem.i4 IL_0010: add IL_0011: stloc.1 IL_0012: br.s IL_0014 IL_0014: ldloc.1 IL_0015: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromMetadata() { var source0 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[0]); } }"; var source1 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[1]); } }"; var source2 = @"class C { static void M() { int[] a = { 4, 5, 6, 7, 8, 9, 10 }; System.Console.WriteLine(a[1]); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE")); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); methodData0.VerifyIL( @" { // Code size 29 (0x1d) .maxstack 3 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: ldelem.i4 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop IL_001c: ret } "); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 30 (0x1e) .maxstack 4 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: nop IL_001d: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 48 (0x30) .maxstack 4 .locals init ([unchanged] V_0, int[] V_1) //a IL_0000: nop IL_0001: ldc.i4.7 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.4 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.5 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.6 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.7 IL_0016: stelem.i4 IL_0017: dup IL_0018: ldc.i4.4 IL_0019: ldc.i4.8 IL_001a: stelem.i4 IL_001b: dup IL_001c: ldc.i4.5 IL_001d: ldc.i4.s 9 IL_001f: stelem.i4 IL_0020: dup IL_0021: ldc.i4.6 IL_0022: ldc.i4.s 10 IL_0024: stelem.i4 IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldc.i4.1 IL_0028: ldelem.i4 IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromSource() { // PrivateImplementationDetails not needed initially. var source0 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } }"; var source1 = @"class C { static object F1() { return new[] { 1, 2, 3 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return null; } static object F4() { return new[] { 7, 8, 9 }; } }"; var source2 = @"class C { static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return new[] { 13, 14, 15 }; } static object F4() { return new[] { 7, 8, 9 }; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4")))); diff1.VerifyIL("C.F1", @"{ // Code size 24 (0x18) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret }"); diff1.VerifyIL("C.F4", @"{ // Code size 25 (0x19) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.7 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.8 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.s 9 IL_0013: stelem.i4 IL_0014: stloc.0 IL_0015: br.s IL_0017 IL_0017: ldloc.0 IL_0018: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3")))); diff2.VerifyIL("C.F1", @"{ // Code size 49 (0x31) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: brtrue.s IL_002c IL_0016: pop IL_0017: ldc.i4.3 IL_0018: newarr ""int"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.s 10 IL_0021: stelem.i4 IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.s 11 IL_0026: stelem.i4 IL_0027: dup IL_0028: ldc.i4.2 IL_0029: ldc.i4.s 12 IL_002b: stelem.i4 IL_002c: stloc.0 IL_002d: br.s IL_002f IL_002f: ldloc.0 IL_0030: ret }"); diff2.VerifyIL("C.F3", @"{ // Code size 27 (0x1b) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.s 13 IL_000b: stelem.i4 IL_000c: dup IL_000d: ldc.i4.1 IL_000e: ldc.i4.s 14 IL_0010: stelem.i4 IL_0011: dup IL_0012: ldc.i4.2 IL_0013: ldc.i4.s 15 IL_0015: stelem.i4 IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret }"); } /// <summary> /// Should not generate method for string switch since /// the CLR only allows adding private members. /// </summary> [WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")] [Fact] public void PrivateImplementationDetails_ComputeStringHash() { var source = @"class C { static int F(string s) { switch (s) { case ""1"": return 1; case ""2"": return 2; case ""3"": return 3; case ""4"": return 4; case ""5"": return 5; case ""6"": return 6; case ""7"": return 7; default: return 0; } } }"; const string ComputeStringHashName = "ComputeStringHash"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); // Should have generated call to ComputeStringHash and // added the method to <PrivateImplementationDetails>. var actualIL0 = methodData0.GetMethodIL(); Assert.True(actualIL0.Contains(ComputeStringHashName)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Should not have generated call to ComputeStringHash nor // added the method to <PrivateImplementationDetails>. var actualIL1 = diff1.GetMethodIL("C.F"); Assert.False(actualIL1.Contains(ComputeStringHashName)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "F"); } /// <summary> /// Unique ids should not conflict with ids /// from previous generation. /// </summary> [WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")] public void UniqueIds() { var source0 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; System.Func<int> g = () => 2; return (b ? f : g)(); } }"; var source1 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; return f(); } }"; var source2 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> g = () => 2; return g(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1]))); diff1.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //f int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__5()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1]))); diff2.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //g int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__7()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); } /// <summary> /// Avoid adding references from method bodies /// other than the changed methods. /// </summary> [Fact] public void ReferencesInIL() { var source0 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.WriteLine(2); } }"; var source1 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.Write(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create( SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // "Write" should be included in string table, but "WriteLine" should not. Assert.True(diff1.MetadataDelta.IsIncluded("Write")); Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine")); } /// <summary> /// Local slots must be preserved based on signature. /// </summary> [Fact] public void PreserveLocalSlots() { var source0 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); A<B> y = F(); object z = F(); M(x); M(y); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" }; var source1 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { B z = F(); A<B> y = F(); object w = F(); M(w); M(y); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source2 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source3 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object c = F(); object b = F(); M(c); M(b); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("B.M"); var methodN = compilation0.GetMember<MethodSymbol>("B.N"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo()); #region Gen1 var method1 = compilation1.GetMember<MethodSymbol>("B.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL( @"{ // Code size 36 (0x24) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.3 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: call 0x06000002 IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: call 0x06000003 IL_001b: nop IL_001c: ldloc.1 IL_001d: call 0x06000003 IL_0022: nop IL_0023: ret }"); diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" /> <entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" /> <entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x24""> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen2 var method2 = compilation2.GetMember<MethodSymbol>("B.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL( @"{ // Code size 30 (0x1e) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.s V_5 IL_0008: call 0x06000002 IL_000d: stloc.3 IL_000e: ldloc.s V_5 IL_0010: call 0x06000003 IL_0015: nop IL_0016: ldloc.3 IL_0017: call 0x06000003 IL_001c: nop IL_001d: ret }"); diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" /> <entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1e""> <local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen3 // Modify different method. (Previous generations // have not referenced method.) method2 = compilation2.GetMember<MethodSymbol>("B.N"); var method3 = compilation3.GetMember<MethodSymbol>("B.N"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL( @"{ // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.2 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: ldloc.2 IL_000e: call 0x06000003 IL_0013: nop IL_0014: ldloc.1 IL_0015: call 0x06000003 IL_001a: nop IL_001b: ret }"); diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000004""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""24"" document=""1"" /> <entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" /> <entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" /> <entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" /> <entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion } /// <summary> /// Preserve locals for method added after initial compilation. /// </summary> [Fact] public void PreserveLocalSlots_NewMethod() { var source0 = @"class C { }"; var source1 = @"class C { static void M() { var a = new object(); var b = string.Empty; } }"; var source2 = @"class C { static void M() { var a = 1; var b = string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 10 (0xa) .maxstack 1 .locals init ([object] V_0, string V_1, //b int V_2) //a IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldsfld ""string string.Empty"" IL_0008: stloc.1 IL_0009: ret }"); diff2.VerifyPdb(new[] { 0x06000002 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" /> <entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } /// <summary> /// Local types should be retained, even if the local is no longer /// used by the method body, since there may be existing /// references to that slot, in a Watch window for instance. /// </summary> [WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")] [Fact] public void PreserveLocalTypes() { var source0 = @"class C { static void Main() { var x = true; var y = x; System.Console.WriteLine(y); } }"; var source1 = @"class C { static void Main() { var x = ""A""; var y = x; System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @" { // Code size 17 (0x11) .maxstack 1 .locals init ([bool] V_0, [bool] V_1, string V_2, //x string V_3) //y IL_0000: nop IL_0001: ldstr ""A"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: stloc.3 IL_0009: ldloc.3 IL_000a: call ""void System.Console.WriteLine(string)"" IL_000f: nop IL_0010: ret }"); } /// <summary> /// Preserve locals if SemanticEdit.PreserveLocalVariables is set. /// </summary> [Fact] public void PreserveLocalVariablesFlag() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (F()) { } using (var x = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1a = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false))); diff1a.VerifyIL("C.M", @" { // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret } "); var diff1b = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true))); diff1b.VerifyIL("C.M", @"{ // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret }"); } [WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")] [Fact] public void ChangeLocalType() { var source0 = @"enum E { } class C { static void M1() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in one method to type added. var source1 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in another method. var source2 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in same method. var source3 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(A); System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M1"); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M2"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M2", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method3 = compilation3.GetMember<MethodSymbol>("C.M2"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL("C.M2", @"{ // Code size 18 (0x12) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [unchanged] V_2, A V_3, //x A V_4, //y A V_5) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldnull IL_0007: stloc.s V_5 IL_0009: ldloc.s V_4 IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret }"); } [Fact] public void AnonymousTypes_Update() { var source0 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 1 }</N:0>; } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md1 = diff1.GetMetadata(); AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader })); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } [Fact] public void AnonymousTypes_UpdateAfterAdd() { var source0 = MarkedSource(@" class C { static void F() { } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } /// <summary> /// Reuse existing anonymous types. /// </summary> [WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")] [Fact] public void AnonymousTypes() { var source0 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = x.A; var z = new { }; } } }"; var source1 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = new { A = x.A }; var z = new { }; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var m0 = compilation0.GetMember<MethodSymbol>("M.B.M"); var m1 = compilation1.GetMember<MethodSymbol>("M.B.M"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider()); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type diff1.VerifyIL("M.B.M", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (<>f__AnonymousType1<int, int> V_0, //x [int] V_1, <>f__AnonymousType2 V_2, //z <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.3 IL_0002: ldc.i4.4 IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get"" IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_0014: stloc.3 IL_0015: newobj ""<>f__AnonymousType2..ctor()"" IL_001a: stloc.2 IL_001b: ret }"); } /// <summary> /// Anonymous type names with module ids /// and gaps in indices. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")] [WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")] public void AnonymousTypes_OtherTypeNames() { var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } // Valid signature, although not sequential index .class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object { .field public !'<A>j__TPar' A .field public !'<B>j__TPar' B } // Invalid signature, unexpected type parameter names .class '<>f__AnonymousType1'<A, B> extends object { .field public !A A .field public !B B } // Module id, duplicate index .class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object { .field public !'<A>j__TPar' A } // Module id .class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object { .field public !'<B>j__TPar' B } .class public C extends object { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F() { ldnull ret } }"; var source0 = @"class C { static object F() { return 0; } }"; var source1 = @"class C { static object F() { var x = new { A = new object(), B = 1 }; var y = new { A = x.A }; return y; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); diff1.VerifyIL("C.F", @"{ // Code size 31 (0x1f) .maxstack 2 .locals init (<>f__AnonymousType2<object, int> V_0, //x <>f__AnonymousType3<object> V_1, //y object V_2) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: ldc.i4.1 IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get"" IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)"" IL_0018: stloc.1 IL_0019: ldloc.1 IL_001a: stloc.2 IL_001b: br.s IL_001d IL_001d: ldloc.2 IL_001e: ret }"); } /// <summary> /// Update method with anonymous type that was /// not directly referenced in previous generation. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration() { var source0 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x; } }"); var source1 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x + 1; } }"); var source2 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 2 }</N:2>; return x.A; } }"); var source3 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 3 }</N:2>; return y.B; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var compilation3 = compilation2.WithSource(source3.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var method0 = compilation0.GetMember<MethodSymbol>("B.G"); var method1 = compilation1.GetMember<MethodSymbol>("B.G"); var method2 = compilation2.GetMember<MethodSymbol>("B.G"); var method3 = compilation3.GetMember<MethodSymbol>("B.G"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types diff1.VerifyIL("B.G", @" { // Code size 16 (0x10) .maxstack 2 .locals init (int V_0, //x [object] V_1, object V_2) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: add IL_0006: box ""int"" IL_000b: stloc.2 IL_000c: br.s IL_000e IL_000e: ldloc.2 IL_000f: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type diff2.VerifyIL("B.G", @" { // Code size 33 (0x21) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y object V_5) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.2 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.3 IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get"" IL_001a: stloc.s V_5 IL_001c: br.s IL_001e IL_001e: ldloc.s V_5 IL_0020: ret }"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true))); var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types diff3.VerifyIL("B.G", @" { // Code size 39 (0x27) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y [object] V_5, object V_6) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.3 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get"" IL_001b: box ""int"" IL_0020: stloc.s V_6 IL_0022: br.s IL_0024 IL_0024: ldloc.s V_6 IL_0026: ret }"); } /// <summary> /// Update another method (without directly referencing /// anonymous type) after updating method with anonymous type. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration_2() { var source0 = @"class C { static object F() { var x = new { A = 1 }; return x.A; } static object G() { var x = 1; return x; } }"; var source1 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x; } }"; var source2 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x + 1; } }"; var source3 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = new { A = (object)null }; var y = new { A = 'a', B = 'b' }; return x; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( md0, m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch { "F" => testData0.GetMethodData("C.F").GetEncDebugInfo(), "G" => testData0.GetMethodData("C.G").GetEncDebugInfo(), _ => default, }); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); // no additional types var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true))); using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); CheckNames(readers, reader3.GetTypeDefNames()); // no additional types } /// <summary> /// Local from previous generation is of an anonymous /// type not available in next generation. /// </summary> [Fact] public void AnonymousTypes_AddThenDelete() { var source0 = @"class C { object A; static object F() { var x = new C(); var y = x.A; return y; } }"; var source1 = @"class C { static object F() { var x = new { A = new object() }; var y = x.A; return y; } }"; var source2 = @"class C { static object F() { var x = new { A = new object(), B = 2 }; var y = x.A; y = new { B = new object() }.B; return y; } }"; var source3 = @"class C { static object F() { var x = new { A = new object(), B = 3 }; var y = x.A; return y; } }"; var source4 = @"class C { static object F() { var x = new { B = 4, A = new object() }; var y = x.A; return y; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var compilation4 = compilation3.WithSource(source4); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type diff1.VerifyIL("C.F", @" { // Code size 27 (0x1b) .maxstack 1 .locals init ([unchanged] V_0, object V_1, //y [object] V_2, <>f__AnonymousType0<object> V_3, //x object V_4) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)"" IL_000b: stloc.3 IL_000c: ldloc.3 IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get"" IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: stloc.s V_4 IL_0016: br.s IL_0018 IL_0018: ldloc.s V_4 IL_001a: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); } [Fact] public void AnonymousTypes_DifferentCase() { var source0 = MarkedSource(@" class C { static void M() { var <N:0>x = new { A = 1, B = 2 }</N:0>; var <N:1>y = new { a = 3, b = 4 }</N:1>; } }"); var source1 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { AB = 3 }</N:1>; } }"); var source2 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { Ab = 5 }</N:1>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var reader1 = diff1.GetMetadata().Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1"); // the first two slots can't be reused since the type changed diff1.VerifyIL("C.M", @"{ // Code size 17 (0x11) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.3 IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_000f: stloc.3 IL_0010: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var reader2 = diff2.GetMetadata().Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1"); // we can reuse slot for "x", it's type haven't changed diff2.VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x [unchanged] V_3, <>f__AnonymousType4<int> V_4) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)"" IL_000f: stloc.s V_4 IL_0011: ret }"); } [Fact] public void AnonymousTypes_Nested1() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Nested2() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Query1() { var source0 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> <N:3>select new { Value = a, Length = a.Length }</N:3></N:4>; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value</N:8>; args = args.Concat(newArgs).ToArray(); System.Diagnostics.Debugger.Break(); result.ToString(); } } "); var source1 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }; for (int i = 0; i < 10; i++) { var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby a.Length ascending, a descending <N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>; var linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, (total, curr) => new { Head = curr.Value, Tail = (dynamic)total }); var str = linked?.Tail?.Head; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value + value</N:8>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1) //newArgs "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>o__0#1: {<>p__0}", "C: {<>o__0#1, <>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}", "<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1, //newArgs <>f__AnonymousType5<dynamic, dynamic> V_2, //list int V_3, //i <>f__AnonymousType5<string, dynamic> V_4, //linked object V_5, //str <>f__AnonymousType5<string, dynamic> V_6, object V_7, bool V_8) "); } [Fact] public void AnonymousTypes_Dynamic1() { var template = @" using System; class C { public void F() { var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>; Console.WriteLine(x.B + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL0 = @" { // Code size 22 (0x16) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret } "; v0.VerifyIL("C.F", baselineIL0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); var baselineIL = @" { // Code size 24 (0x18) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: ldc.i4.<<VALUE>> IL_0010: add IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: nop IL_0017: ret } "; diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2")); } /// <summary> /// Should not re-use locals if the method metadata /// signature is unsupported. /// </summary> [WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")] public void LocalType_UnsupportedSignatureContent() { // Equivalent to C#, but with extra local and required modifier on // expected local. Used to generate initial (unsupported) metadata. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class C { .method public specialname rtspecialname instance void .ctor() { ret } .method private static object F() { ldnull ret } .method private static void M1() { .locals init ([0] object other, [1] object modreq(int32) o) call object C::F() stloc.1 ldloc.1 call void C::M2(object) ret } .method private static void M2(object o) { ret } }"; var source = @"class C { static object F() { return null; } static void M1() { object o = F(); M2(o); } static void M2(object o) { } }"; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 15 (0xf) .maxstack 1 .locals init (object V_0) //o IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void C.M2(object)"" IL_000d: nop IL_000e: ret }"); } /// <summary> /// Should not re-use locals with custom modifiers. /// </summary> [WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")] public void LocalType_CustomModifiers() { // Equivalent method signature to C#, but // with optional modifier on locals. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public C { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F(class [mscorlib]System.IDisposable d) { .locals init ([0] class C modopt(int32) c, [1] class [mscorlib]System.IDisposable modopt(object), [2] bool V_2, [3] object V_3) ldnull ret } }"; var source = @"class C { static object F(System.IDisposable d) { C c; using (d) { c = (C)d; } return c; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( moduleMetadata0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [bool] V_2, [object] V_3, C V_4, //c System.IDisposable V_5, object V_6) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: stloc.s V_5 .try { -IL_0004: nop -IL_0005: ldarg.0 IL_0006: castclass ""C"" IL_000b: stloc.s V_4 -IL_000d: nop IL_000e: leave.s IL_001d } finally { ~IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_001c IL_0014: ldloc.s V_5 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop IL_001c: endfinally } -IL_001d: ldloc.s V_4 IL_001f: stloc.s V_6 IL_0021: br.s IL_0023 -IL_0023: ldloc.s V_6 IL_0025: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } /// <summary> /// Temporaries for locals used within a single /// statement should not be preserved. /// </summary> [Fact] public void TemporaryLocals_Other() { // Use increment as an example of a compiler generated // temporary that does not span multiple statements. var source = @"class C { int P { get; set; } static int M() { var c = new C(); return c.P++; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 32 (0x20) .maxstack 3 .locals init (C V_0, //c [int] V_1, [int] V_2, int V_3, int V_4) IL_0000: nop IL_0001: newobj ""C..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: dup IL_0009: callvirt ""int C.P.get"" IL_000e: stloc.3 IL_000f: ldloc.3 IL_0010: ldc.i4.1 IL_0011: add IL_0012: callvirt ""void C.P.set"" IL_0017: nop IL_0018: ldloc.3 IL_0019: stloc.s V_4 IL_001b: br.s IL_001d IL_001d: ldloc.s V_4 IL_001f: ret }"); } /// <summary> /// Local names array (from PDB) may have fewer slots than method /// signature (from metadata) when the trailing slots are unnamed. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); testData0.GetMethodData("C.M").VerifyIL(@" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); } /// <summary> /// Similar to above test but with no named locals in original. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270_NoNamedLocals() { // Equivalent to C#, but with unnamed locals. // Used to generate initial metadata. var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } .assembly '<<GeneratedFileName>>' { } .class C extends object { .method private static class [netstandard]System.IDisposable F() { ldnull ret } .method private static void M() { .locals init ([0] object, [1] object) ret } }"; var source0 = @"class C { static System.IDisposable F() { return null; } static void M() { } }"; var source1 = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init ([object] V_0, [object] V_1, System.IDisposable V_2) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.2 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.2 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.2 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret } "); } [Fact] public void TemporaryLocals_ReferencedType() { var source = @"class C { static object F() { return null; } static void M() { var x = new System.Collections.Generic.HashSet<int>(); x.Add(1); } }"; var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var modMeta = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( modMeta, methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.HashSet<int> V_0) //x IL_0000: nop IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)"" IL_000e: pop IL_000f: ret } "); } [WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")] [WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")] [Fact] public void DynamicOperations() { var source = @"class A { static object F = null; object x = ((dynamic)F) + 1; static A() { ((dynamic)F).F(); } A() { } static void M(object o) { ((dynamic)o).x = 1; } static void N(A o) { o.x = 1; } } class B { static object F = null; static object G = ((dynamic)F).F(); object x = ((dynamic)F) + 1; }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); // Source method with dynamic operations. var methodData0 = testData0.GetMethodData("A.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("A.M"); var method1 = compilation1.GetMember<MethodSymbol>("A.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Source method with no dynamic operations. methodData0 = testData0.GetMethodData("A.N"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A.N"); method1 = compilation1.GetMember<MethodSymbol>("A.N"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("A..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..ctor"); method1 = compilation1.GetMember<MethodSymbol>("A..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("A..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..cctor"); method1 = compilation1.GetMember<MethodSymbol>("A..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("B..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..ctor"); method1 = compilation1.GetMember<MethodSymbol>("B..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("B..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..cctor"); method1 = compilation1.GetMember<MethodSymbol>("B..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void DynamicLocals() { var template = @" using System; class C { public void F() { dynamic <N:0>x = 1</N:0>; Console.WriteLine((int)x + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 82 (0x52) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: call ""void System.Console.WriteLine(int)"" IL_0050: nop IL_0051: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>o__0#1}", "C.<>o__0#1: {<>p__0}"); diff1.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.1 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>o__0#2, <>o__0#1}", "C.<>o__0#1: {<>p__0}", "C.<>o__0#2: {<>p__0}"); diff2.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.2 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); } [Fact] public void ExceptionFilters() { var source0 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } } } "); var source1 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } Console.WriteLine(1); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 90 (0x5a) .maxstack 2 .locals init (System.IO.IOException V_0, //e bool V_1, System.Exception V_2, //e bool V_3) IL_0000: nop .try { IL_0001: nop IL_0002: newobj ""System.InvalidOperationException..ctor()"" IL_0007: throw } filter { IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_0020 IL_0014: stloc.0 IL_0015: ldloc.0 IL_0016: call ""bool C.G(System.Exception)"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: ldc.i4.0 IL_001e: cgt.un IL_0020: endfilter } // end filter { // handler IL_0022: pop IL_0023: nop IL_0024: call ""void System.Console.WriteLine()"" IL_0029: nop IL_002a: nop IL_002b: leave.s IL_0052 } filter { IL_002d: isinst ""System.Exception"" IL_0032: dup IL_0033: brtrue.s IL_0039 IL_0035: pop IL_0036: ldc.i4.0 IL_0037: br.s IL_0045 IL_0039: stloc.2 IL_003a: ldloc.2 IL_003b: call ""bool C.G(System.Exception)"" IL_0040: stloc.3 IL_0041: ldloc.3 IL_0042: ldc.i4.0 IL_0043: cgt.un IL_0045: endfilter } // end filter { // handler IL_0047: pop IL_0048: nop IL_0049: call ""void System.Console.WriteLine()"" IL_004e: nop IL_004f: nop IL_0050: leave.s IL_0052 } IL_0052: ldc.i4.1 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void MethodSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(2); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } [WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void LocalSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(null); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(x); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,16): warning CS0219: The variable 'y' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"), // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } /// <summary> /// Disallow edits that require NoPIA references. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIAReferences() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")] public interface IA { void M(); int P { get; } event Action E; } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")] public interface IB { } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")] public interface IC { } public struct S { public object F; }"; var source0 = @"class C<T> { static object F = typeof(IC); static void M1() { var o = default(IA); o.M(); M2(o.P); o.E += M1; M2(C<IA>.F); M2(new S()); } static void M2(object o) { } }"; var source1A = source0; var source1B = @"class C<T> { static object F = typeof(IC); static void M1() { M2(null); } static void M2(object o) { } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1A = compilation0.WithSource(source1A); var compilation1B = compilation0.WithSource(source1B); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var method1B = compilation1B.GetMember<MethodSymbol>("C.M1"); var method1A = compilation1A.GetMember<MethodSymbol>("C.M1"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C<T>.M1"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); // Disallow edits that require NoPIA references. var diff1A = compilation1A.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true))); diff1A.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA")); // Allow edits that do not require NoPIA references, // even if the previous code included references. var diff1B = compilation1B.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true))); diff1B.VerifyIL("C<T>.M1", @"{ // Code size 9 (0x9) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1) IL_0000: nop IL_0001: ldnull IL_0002: call ""void C<T>.M2(object)"" IL_0007: nop IL_0008: ret }"); using var md1 = diff1B.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); } [WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIATypeInNamespace() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")] namespace N { [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")] public interface IA { } } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")] public interface IB { }"; var source = @"class C<T> { static void M(object o) { M(C<N.IA>.E.X); M(C<IB>.E.X); } enum E { X } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB")); diff1.VerifyIL("C<T>.M", @"{ // Code size 26 (0x1a) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""C<N.IA>.E"" IL_0007: call ""void C<T>.M(object)"" IL_000c: nop IL_000d: ldc.i4.0 IL_000e: box ""C<IB>.E"" IL_0013: call ""void C<T>.M(object)"" IL_0018: nop IL_0019: ret }"); } /// <summary> /// Should use TypeDef rather than TypeRef for unrecognized /// local of a type defined in the original assembly. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfTypeFromAssembly() { var source = @"class E : System.Exception { } class C { static void M() { try { } catch (E e) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeRefNames(), "Object"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL("C.M", @" { // Code size 11 (0xb) .maxstack 1 .locals init (E V_0) //e IL_0000: nop .try { IL_0001: nop IL_0002: nop IL_0003: leave.s IL_000a } catch E { IL_0005: stloc.0 IL_0006: nop IL_0007: nop IL_0008: leave.s IL_000a } IL_000a: ret }"); } /// <summary> /// Similar to above test but with anonymous type /// added in subsequent generation. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfAnonymousTypeFromAssembly() { var source0 = @"class C { static string F() { return null; } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source2 = @"class C { static string F() { return null; } static string G() { return null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var method1G = compilation1.GetMember<MethodSymbol>("C.G"); var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var method2G = compilation2.GetMember<MethodSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); // Use empty LocalVariableNameProvider for original locals and // use preserveLocalVariables: true for the edit so that existing // locals are retained even though all are unrecognized. var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1"); CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider"); // Change method updated in generation 1. var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetTypeRefNames(), "Object"); // Change method unchanged since generation 0. var diff2G = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true))); } [Fact] public void BrokenOutputStreams() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, badStream, ilStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, badStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [Fact] public void BrokenPortablePdbStream() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors() { var source0 = @"class C { }"; var source1 = @"class C { static void Main() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))), testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() }); diff1.EmitResult.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message")); Assert.False(diff1.EmitResult.Success); } [WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")] [Fact] public void BlobContainsInvalidValues() { var source0 = @"class C { static void F() { string goo = ""abc""; } }"; var source1 = @"class C { static void F() { float goo = 10; } }"; var source2 = @"class C { static void F() { bool goo = true; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); var handle = MetadataTokens.BlobHandle(1); byte[] value0 = reader0.GetBlobBytes(handle); Assert.Equal("20-01-01-08", BitConverter.ToString(value0)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); byte[] value1 = reader1.GetBlobBytes(handle); Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1)); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; byte[] value2 = reader2.GetBlobBytes(handle); Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly1() { var sourceA0 = @" public class A { } "; var sourceA1 = @" public class A { public void M() { System.Console.WriteLine(1);} } public class X {} "; var sourceB0 = @" public class B { public static void F() { } }"; var sourceB1 = @" public class B { public static void F() { new A().M(); } } public class Y : X { } "; var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA"); var compilationA1 = compilationA0.WithSource(sourceA1); var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var bytesA0 = compilationA0.EmitToArray(); var bytesB0 = compilationB0.EmitToArray(); var mdA0 = ModuleMetadata.CreateFromImage(bytesA0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider); var mA1 = compilationA1.GetMember<MethodSymbol>("A.M"); var mX1 = compilationA1.GetMember<TypeSymbol>("X"); var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() }; var diffA1 = compilationA1.EmitDifference( generationA0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, mA1), SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)), allAddedSymbols); diffA1.EmitResult.Diagnostics.Verify(); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))), allAddedSymbols); diffB1.EmitResult.Diagnostics.Verify( // (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public class X {} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14), // (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public void M() { System.Console.WriteLine(1);} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly2() { var sourceA = @" public class A { public void M() { } }"; var sourceB0 = @" public class B { public static void F() { var a = new A(); } }"; var sourceB1 = @" public class B { public static void F() { var a = new A(); a.M(); } }"; var sourceB2 = @" public class B { public static void F() { var a = new A(); } }"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA"); var aRef = compilationA.ToMetadataReference(); var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB"); var compilationB1 = compilationB0.WithSource(sourceB1); var compilationB2 = compilationB1.WithSource(sourceB2); var testDataB0 = new CompilationTestData(); var bytesB0 = compilationB0.EmitToArray(testData: testDataB0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider()); var f0 = compilationB0.GetMember<MethodSymbol>("B.F"); var f1 = compilationB1.GetMember<MethodSymbol>("B.F"); var f2 = compilationB2.GetMember<MethodSymbol>("B.F"); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); diffB1.VerifyIL("B.F", @" { // Code size 15 (0xf) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: callvirt ""void A.M()"" IL_000d: nop IL_000e: ret } "); var diffB2 = compilationB2.EmitDifference( diffB1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true))); diffB2.VerifyIL("B.F", @" { // Code size 8 (0x8) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void UniqueSynthesizedNames_DynamicSiteContainer() { var source0 = @" public class C { public static void F(dynamic d) { d.Goo(); } }"; var source1 = @" public class C { public static void F(dynamic d) { d.Bar(); } }"; var source2 = @" public class C { public static void F(dynamic d, byte b) { d.Bar(); } public static void F(dynamic d) { d.Bar(); } }"; var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2))); diff2.EmitResult.Diagnostics.Verify(); var reader0 = md0.MetadataReader; var reader1 = diff1.GetMetadata().Reader; var reader2 = diff2.GetMetadata().Reader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0"); CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1"); CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2"); } [WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")] [Fact] public void ManyGenerations() { var source = @"class C {{ static int F() {{ return {0}; }} }}"; var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll); var bytes0 = compilation0.EmitToArray(); var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); for (int i = 2; i <= 50; i++) { var compilation1 = compilation0.WithSource(String.Format(source, i)); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); compilation0 = compilation1; method0 = method1; generation0 = diff1.NextGeneration; } } [WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")] [Fact] public void PdbReadingErrors() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new InvalidDataException("Bad PDB!"); }); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''. Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14)); } [Fact] public void PdbReadingErrors_PassThruExceptions() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new ArgumentOutOfRangeException(); }); // the compiler should't swallow any exceptions but InvalidDataException Assert.Throws<ArgumentOutOfRangeException>(() => compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)))); } [Fact] public void PatternVariable_TypeChange() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 46 (0x2e) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, //i bool V_4, int V_5) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""bool"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""bool"" IL_000f: stloc.3 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.s V_4 IL_0016: ldloc.s V_4 IL_0018: brfalse.s IL_0026 IL_001a: nop IL_001b: ldloc.3 IL_001c: brtrue.s IL_0021 IL_001e: ldc.i4.0 IL_001f: br.s IL_0022 IL_0021: ldc.i4.1 IL_0022: stloc.s V_5 IL_0024: br.s IL_002b IL_0026: ldc.i4.0 IL_0027: stloc.s V_5 IL_0029: br.s IL_002b IL_002b: ldloc.s V_5 IL_002d: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [bool] V_4, [int] V_5, int V_6, //j bool V_7, int V_8) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_6 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_7 IL_0017: ldloc.s V_7 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_6 IL_001e: stloc.s V_8 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_8 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_8 IL_0029: ret }"); } [Fact] public void PatternVariable_DeleteInsert() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is int) { return 1; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 28 (0x1c) .maxstack 2 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, int V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: ldnull IL_0008: cgt.un IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: brfalse.s IL_0014 IL_000e: nop IL_000f: ldc.i4.1 IL_0010: stloc.s V_4 IL_0012: br.s IL_0019 IL_0014: ldc.i4.0 IL_0015: stloc.s V_4 IL_0017: br.s IL_0019 IL_0019: ldloc.s V_4 IL_001b: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [int] V_4, int V_5, //i bool V_6, int V_7) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_5 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_6 IL_0017: ldloc.s V_6 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_5 IL_001e: stloc.s V_7 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_7 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_7 IL_0029: ret }"); } [Fact] public void PatternVariable_InConstructorInitializer() { var baseClass = "public class Base { public Base(bool x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; } }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { } }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.1 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.1 IL_0015: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 15 (0xf) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.0 IL_0005: ceq IL_0007: call ""Base..ctor(bool)"" IL_000c: nop IL_000d: nop IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.2 IL_0015: ret } "); } [Fact] public void PatternVariable_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>; }"); var source1 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.1 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 24 (0x18) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ceq IL_000b: stfld ""bool C.field"" IL_0010: ldarg.0 IL_0011: call ""object..ctor()"" IL_0016: nop IL_0017: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.2 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); } [Fact] public void PatternVariable_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.1 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 7 (0x7) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ceq IL_0006: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.2 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); } [Fact] public void Tuple_Parenthesized() { var source0 = MarkedSource(@" class C { static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"); var source1 = MarkedSource(@" class C { static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; } }"); var source2 = MarkedSource(@" class C { static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 51 (0x33) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_0010: ldloc.0 IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0016: ldloc.0 IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0021: add IL_0022: ldloc.0 IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: add IL_002e: stloc.1 IL_002f: br.s IL_0031 IL_0031: ldloc.1 IL_0032: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 36 (0x24) .maxstack 4 .locals init ([unchanged] V_0, [int] V_1, System.ValueTuple<int, int, int> V_2, //x int V_3) IL_0000: nop IL_0001: ldloca.s V_2 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)"" IL_000b: ldloc.2 IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1"" IL_0011: ldloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2"" IL_0017: add IL_0018: ldloc.2 IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3"" IL_001e: add IL_001f: stloc.3 IL_0020: br.s IL_0022 IL_0022: ldloc.3 IL_0023: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 32 (0x20) .maxstack 3 .locals init ([unchanged] V_0, [int] V_1, [unchanged] V_2, [int] V_3, System.ValueTuple<int, int> V_4, //x int V_5) IL_0000: nop IL_0001: ldloca.s V_4 IL_0003: ldc.i4.1 IL_0004: ldc.i4.3 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.s V_4 IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: ldloc.s V_4 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: add IL_0019: stloc.s V_5 IL_001b: br.s IL_001d IL_001d: ldloc.s V_5 IL_001f: ret } "); } [Fact] public void Tuple_Decomposition() { var source0 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var source1 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; } }"); var source2 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 17 (0x11) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2, //z int V_3) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldc.i4.3 IL_0006: stloc.2 IL_0007: ldloc.0 IL_0008: ldloc.1 IL_0009: add IL_000a: ldloc.2 IL_000b: add IL_000c: stloc.3 IL_000d: br.s IL_000f IL_000f: ldloc.3 IL_0010: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, int V_4) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.3 IL_0004: stloc.2 IL_0005: ldloc.0 IL_0006: ldloc.2 IL_0007: add IL_0008: stloc.s V_4 IL_000a: br.s IL_000c IL_000c: ldloc.s V_4 IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, [int] V_4, int V_5, //y int V_6) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.s V_5 IL_0006: ldc.i4.3 IL_0007: stloc.2 IL_0008: ldloc.0 IL_0009: ldloc.s V_5 IL_000b: add IL_000c: ldloc.2 IL_000d: add IL_000e: stloc.s V_6 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_6 IL_0014: ret } "); } [Fact] public void ForeachStatement() { var source0 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x); } } }"); var source1 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x1); } } }"); var source2 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F()) { System.Console.WriteLine(x1); } } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 70 (0x46) .maxstack 2 .locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0, int V_1, int V_2, //x bool V_3, //y double V_4, //z System.ValueTuple<bool, double> V_5) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 IL_000a: br.s IL_003f IL_000c: ldloc.0 IL_000d: ldloc.1 IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0013: dup IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0019: stloc.s V_5 IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0020: stloc.2 IL_0021: ldloc.s V_5 IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_0028: stloc.3 IL_0029: ldloc.s V_5 IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0030: stloc.s V_4 IL_0032: nop IL_0033: ldloc.2 IL_0034: call ""void System.Console.WriteLine(int)"" IL_0039: nop IL_003a: nop IL_003b: ldloc.1 IL_003c: ldc.i4.1 IL_003d: add IL_003e: stloc.1 IL_003f: ldloc.1 IL_0040: ldloc.0 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_000c IL_0045: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 78 (0x4e) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 bool V_3, //y double V_4, //z [unchanged] V_5, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6, int V_7, System.ValueTuple<bool, double> V_8) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_6 IL_0009: ldc.i4.0 IL_000a: stloc.s V_7 IL_000c: br.s IL_0045 IL_000e: ldloc.s V_6 IL_0010: ldloc.s V_7 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_001d: stloc.s V_8 IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0024: stloc.2 IL_0025: ldloc.s V_8 IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_002c: stloc.3 IL_002d: ldloc.s V_8 IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0034: stloc.s V_4 IL_0036: nop IL_0037: ldloc.2 IL_0038: call ""void System.Console.WriteLine(int)"" IL_003d: nop IL_003e: nop IL_003f: ldloc.s V_7 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.s V_7 IL_0045: ldloc.s V_7 IL_0047: ldloc.s V_6 IL_0049: ldlen IL_004a: conv.i4 IL_004b: blt.s IL_000e IL_004d: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 61 (0x3d) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 [bool] V_3, [unchanged] V_4, [unchanged] V_5, [unchanged] V_6, [int] V_7, [unchanged] V_8, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9, int V_10, System.ValueTuple<bool, double> V_11) //yz IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_9 IL_0009: ldc.i4.0 IL_000a: stloc.s V_10 IL_000c: br.s IL_0034 IL_000e: ldloc.s V_9 IL_0010: ldloc.s V_10 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_001d: stloc.2 IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0023: stloc.s V_11 IL_0025: nop IL_0026: ldloc.2 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop IL_002d: nop IL_002e: ldloc.s V_10 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stloc.s V_10 IL_0034: ldloc.s V_10 IL_0036: ldloc.s V_9 IL_0038: ldlen IL_0039: conv.i4 IL_003a: blt.s IL_000e IL_003c: ret } "); } [Fact] public void OutVar() { var source0 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; } }"); var source1 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; } }"); var source2 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.2 IL_000f: br.s IL_0011 IL_0011: ldloc.2 IL_0012: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //z [int] V_2, int V_3) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.3 IL_000f: br.s IL_0011 IL_0011: ldloc.3 IL_0012: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x int V_1, //y [int] V_2, [int] V_3, int V_4) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.s V_4 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_4 IL_0014: ret } "); } [Fact] public void OutVar_InConstructorInitializer() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); } static int M(out int x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x) { } static int M(out int x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.1 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 18 (0x12) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: call ""Base..ctor(int)"" IL_000f: nop IL_0010: nop IL_0011: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.2 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); } [Fact] public void OutVar_InConstructorInitializer_WithLambda() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0"); diff1.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff1.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0"); diff2.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff2.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InMethodBody_WithLambda() { var source0 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method"); var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method"); var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.1 IL_0025: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff1.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, int V_2) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.2 IL_0025: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff2.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, [int] V_2, int V_3) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.3 IL_0025: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>); static int M(out int x) => throw null; }"); var source1 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x; static int M(out int x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 23 (0x17) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: stfld ""int C.field"" IL_000f: ldarg.0 IL_0010: call ""object..ctor()"" IL_0015: nop IL_0016: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); } [Fact] public void OutVar_InFieldInitializer_WithLambda() { var source0 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff1.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff2.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_1 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 11 (0xb) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_2 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); } [Fact] public void OutVar_InQuery_WithLambda() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InSwitchExpression() { var source0 = MarkedSource(@" public class Program { static object G(int i) { return i switch { 0 => 0, _ => 1 }; } static object N(out int x) { x = 1; return null; } }"); var source1 = MarkedSource(@" public class Program { static object G(int i) { return i + N(out var x) switch { 0 => 0, _ => 1 }; } static int N(out int x) { x = 1; return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.G"); var n1 = compilation1.GetMember<MethodSymbol>("Program.G"); var n2 = compilation2.GetMember<MethodSymbol>("Program.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.G(int)", @" { // Code size 33 (0x21) .maxstack 1 .locals init (int V_0, object V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000e IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_0012 IL_000e: ldc.i4.1 IL_000f: stloc.0 IL_0010: br.s IL_0012 IL_0012: ldc.i4.1 IL_0013: brtrue.s IL_0016 IL_0015: nop IL_0016: ldloc.0 IL_0017: box ""int"" IL_001c: stloc.1 IL_001d: br.s IL_001f IL_001f: ldloc.1 IL_0020: ret } "); v0.VerifyIL("Program.N(out int)", @" { // Code size 10 (0xa) .maxstack 2 .locals init (object V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: stind.i4 IL_0004: ldnull IL_0005: stloc.0 IL_0006: br.s IL_0008 IL_0008: ldloc.0 IL_0009: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers(); diff1.VerifyIL("Program.G(int)", @" { // Code size 52 (0x34) .maxstack 2 .locals init ([int] V_0, [object] V_1, int V_2, //x int V_3, int V_4, int V_5, object V_6) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.3 IL_0003: ldloca.s V_2 IL_0005: call ""int Program.N(out int)"" IL_000a: stloc.s V_5 IL_000c: ldc.i4.1 IL_000d: brtrue.s IL_0010 IL_000f: nop IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_0016 IL_0014: br.s IL_001b IL_0016: ldc.i4.0 IL_0017: stloc.s V_4 IL_0019: br.s IL_0020 IL_001b: ldc.i4.1 IL_001c: stloc.s V_4 IL_001e: br.s IL_0020 IL_0020: ldc.i4.1 IL_0021: brtrue.s IL_0024 IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.s V_4 IL_0027: add IL_0028: box ""int"" IL_002d: stloc.s V_6 IL_002f: br.s IL_0031 IL_0031: ldloc.s V_6 IL_0033: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers(); diff2.VerifyIL("Program.G(int)", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([int] V_0, [object] V_1, [int] V_2, [int] V_3, [int] V_4, [int] V_5, [object] V_6, int V_7, object V_8) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000f IL_000a: ldc.i4.0 IL_000b: stloc.s V_7 IL_000d: br.s IL_0014 IL_000f: ldc.i4.1 IL_0010: stloc.s V_7 IL_0012: br.s IL_0014 IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 IL_0017: nop IL_0018: ldloc.s V_7 IL_001a: box ""int"" IL_001f: stloc.s V_8 IL_0021: br.s IL_0023 IL_0023: ldloc.s V_8 IL_0025: ret } "); } [Fact] public void AddUsing_AmbiguousCode() { var source0 = MarkedSource(@" using System.Threading; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } }"); var source1 = MarkedSource(@" using System.Threading; using System.Timers; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } static void G() { System.Console.WriteLine(new TimersDescriptionAttribute("""")); } }"); var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Pretend there was an update to C.E to ensure we haven't invalidated the test var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer' // var t = new Timer(s => System.Console.WriteLine(s)); Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21)); // Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff.EmitResult.Diagnostics.Verify(); diff.VerifyIL(@"C.G", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldstr """" IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)"" IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret } "); } [Fact] public void Records_AddWellKnownMember() { var source0 = @" #nullable enable namespace N { record R(int X) { } } "; var source1 = @" #nullable enable namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); // Verify full metadata contains expected rows. var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R"); CheckNames(reader0, reader0.GetMethodDefNames(), /* EmbeddedAttribute */".ctor", /* NullableAttribute */ ".ctor", /* NullableContextAttribute */".ctor", /* IsExternalInit */".ctor", /* R: */ ".ctor", "get_EqualityContract", "get_X", "set_X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); // 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(), "PrintMembers"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default), 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)); CheckEncMap(reader1, Handle(20, TableIndex.TypeRef), Handle(21, TableIndex.TypeRef), Handle(22, TableIndex.TypeRef), Handle(10, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Records_RemoveWellKnownMember() { var source0 = @" namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var source1 = @" namespace N { record R(int X) { } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); } [Fact] public void TopLevelStatement_Update() { var source0 = @" using System; Console.WriteLine(""Hello""); "; var source1 = @" using System; Console.WriteLine(""Hello World""); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("Program.<Main>$"); var method1 = compilation1.GetMember<MethodSymbol>("Program.<Main>$"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "Program"); CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine", /*Program.*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // 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(), "<Main>$"); CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), // Synthesized Main method Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void LambdaParameterToDiscard() { var source0 = MarkedSource(@" using System; class C { void M() { var x = new Func<int, int, int>(<N:0>(a, b) => a + b + 1</N:0>); Console.WriteLine(x(1, 2)); } }"); var source1 = MarkedSource(@" using System; class C { void M() { var x = new Func<int, int, int>(<N:0>(_, _) => 10</N:0>); Console.WriteLine(x(1, 2)); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // There should be no diagnostics from rude edits diff.EmitResult.Diagnostics.Verify(); diff.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <M>b__0_0}"); diff.VerifyIL("C.M", @" { // Code size 48 (0x30) .maxstack 3 .locals init ([unchanged] V_0, System.Func<int, int, int> V_1) //x IL_0000: nop IL_0001: ldsfld ""System.Func<int, int, int> C.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""C.<>c C.<>c.<>9"" IL_000f: ldftn ""int C.<>c.<M>b__0_0(int, int)"" IL_0015: newobj ""System.Func<int, int, int>..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""System.Func<int, int, int> C.<>c.<>9__0_0"" IL_0020: stloc.1 IL_0021: ldloc.1 IL_0022: ldc.i4.1 IL_0023: ldc.i4.2 IL_0024: callvirt ""int System.Func<int, int, int>.Invoke(int, int)"" IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); diff.VerifyIL("C.<>c.<M>b__0_0(int, int)", @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 10 IL_0002: ret }"); } } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { /// <summary> /// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test. /// </summary> public class EditAndContinueTests : EditAndContinueTestBase { private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers) { var currentGenerationReader = readers.Last(); foreach (var typeRefHandle in currentGenerationReader.TypeReferences) { var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle); yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}"; } } [Fact] public void DeltaHeapsStartWithEmptyItem() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { return ""a""; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var s = MetadataTokens.StringHandle(0); Assert.Equal("", reader1.GetString(s)); var b = MetadataTokens.BlobHandle(0); Assert.Equal(0, reader1.GetBlobBytes(b).Length); var us = MetadataTokens.UserStringHandle(0); Assert.Equal("", reader1.GetUserString(us)); } [Fact] public void Delta_AssemblyDefTable() { var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }"; var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); // AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed: Assert.True(md0.MetadataReader.IsAssembly); Assert.False(diff1.GetMetadata().Reader.IsAssembly); } [Fact] public void SemanticErrors_MethodBody() { var source0 = MarkedSource(@" class C { static void E() { int x = 1; System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void E() { int x = Unknown(2); System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(2); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Semantic errors are reported only for the bodies of members being emitted. var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (6,17): error CS0103: The name 'Unknown' does not exist in the current context // int x = Unknown(2); Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17)); var diffGood = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffGood.EmitResult.Diagnostics.Verify(); diffGood.VerifyIL(@"C.G", @" { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.2 IL_0002: call ""void System.Console.WriteLine(int)"" IL_0007: nop IL_0008: ret } "); } [Fact] public void SemanticErrors_Declaration() { var source0 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(1); } } "); var source1 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(2); } } class Bad : Bad { } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // All declaration errors are reported regardless of what member do we emit. diff.EmitResult.Diagnostics.Verify( // (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad' // class Bad : Bad Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7)); } [Fact] public void ModifyMethod() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // 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"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_RenameParameter() { var source0 = @"class C { static string F(int a) { return a.ToString(); } }"; var source1 = @"class C { static string F(int x) { return x.ToString(); } }"; var source2 = @"class C { static string F(int b) { return b.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "a"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // 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"); CheckNames(readers, reader1.GetParameterDefNames(), "x"); CheckEncLogDefinitions(reader1, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.StandAloneSig)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), "ToString"); CheckNames(readers, reader2.GetParameterDefNames(), "b"); CheckEncLogDefinitions(reader2, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(3, TableIndex.StandAloneSig)); } [CompilerTrait(CompilerFeature.Tuples)] [Fact] public void ModifyMethod_WithTuples() { var source0 = @"class C { static void Main() { } static (int, int) F() { return (1, 2); } }"; var source1 = @"class C { static void Main() { } static (int, int) F() { return (2, 3); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // 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"); CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes1() { using var _ = new EditAndContinueTest(options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20) .AddGeneration( source: @" class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }", validator: g => { g.VerifyTypeDefNames("<Module>", "C"); g.VerifyMethodDefNames("Main", "F", ".ctor"); g.VerifyMemberRefNames(/*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); g.VerifyTableSize(TableIndex.CustomAttribute, 4); }) .AddGeneration( source: @" class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }", edits: new[] { Edit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, validator: g => { g.VerifyTypeDefNames(); g.VerifyMethodDefNames("F"); g.VerifyMemberRefNames( /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); g.VerifyTableSize(TableIndex.CustomAttribute, 1); g.VerifyEncLog(new[] { Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default) // Row 4, so updating existing CustomAttribute }); g.VerifyEncMap(new[] { Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef) }); }) // Add attribute to method, and to class .AddGeneration( source: @" [System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }", edits: new[] { Edit(SemanticEditKind.Update, c => c.GetMember("C")), Edit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, validator: g => { g.VerifyTypeDefNames("C"); g.VerifyMethodDefNames("F"); g.VerifyMemberRefNames( /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); g.VerifyTableSize(TableIndex.CustomAttribute, 3); g.VerifyEncLog(new[] { Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default) // Row 6 adding a new CustomAttribute }); g.VerifyEncMap(new[] { Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(2, TableIndex.TypeDef), Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(10, TableIndex.MemberRef), Handle(11, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef) }); }) // Add attribute before existing attributes .AddGeneration( source: @" [System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }", edits: new[] { Edit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, validator: g => { g.VerifyTypeDefNames(); g.VerifyMethodDefNames("F"); g.VerifyMemberRefNames( /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); g.VerifyTableSize(TableIndex.CustomAttribute, 3); g.VerifyEncLog(new[] { Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2 Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default) // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted }); g.VerifyEncMap(new[] { Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(19, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(12, TableIndex.MemberRef), Handle(13, TableIndex.MemberRef), Handle(14, TableIndex.MemberRef), Handle(15, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef) }); }) .Verify(); } [Fact] public void ModifyMethod_WithAttributes2() { var source0 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A"")] static string A() { return null; } } "; var source1 = @" [System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")] static string A() { return null; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0_1 = compilation0.GetMember<MethodSymbol>("C.F"); var method0_2 = compilation0.GetMember<MethodSymbol>("D.A"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1_1 = compilation1.GetMember<MethodSymbol>("C.F"); var method1_2 = compilation1.GetMember<MethodSymbol>("D.A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1), SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2))); // 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", "A"); CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var source2 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // 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"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader2, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes2() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = source0; // Remove the attribute we just added var source3 = source1; // Add the attribute back again var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation1.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // 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"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames()); CheckAttributes(reader2, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader3, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row CheckEncMap(reader3, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [Fact] public void Lambda_Attributes() { var source0 = MarkedSource(@" class C { void F() { var x = <N:0>(int a) => a</N:0>; } }"); var source1 = MarkedSource(@" class C { void F() { var x = <N:0>[System.Obsolete](int a) => a</N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); 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>", "C", "<>c"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".cctor", ".ctor", "<F>b__0_0"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef))); 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}", "C.<>c: {<>9__0_0, <F>b__0_0}"); CheckAttributes(reader1, new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef))); CheckEncLogDefinitions(reader1, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // row 5 = new custom attribute CheckEncMapDefinitions(reader1, Handle(1, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(5, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig)); } [Fact] public void Lambda_SynthesizedDelegate() { var source0 = MarkedSource(@" class C { void F() { var x = <N:0>(ref int a, int b) => a</N:0>; } }"); var source1 = MarkedSource(@" class C { void F() { var x = <N:0>(ref int a, int b) => b</N:0>; var y = <N:1>(int a, ref int b) => a</N:1>; var z = <N:2>(int _1, int _2, int _3, int _4, int _5, int _6, ref int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, int _17, int _18, int _19, int _20, int _21, int _22, int _23, int _24, int _25, int _26, int _27, int _28, int _29, int _30, int _31, int _32, ref int _33) => { }</N:2>; } }"); var source2 = MarkedSource(@" class C { void F() { var x = <N:0>(ref int a, int b) => b</N:0>; var y = <N:1>(int a, ref int b) => b</N:1>; var z = <N:2>(int _1, int _2, int _3, int _4, int _5, int _6, ref int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, int _17, int _18, int _19, int _20, int _21, int _22, int _23, int _24, int _25, int _26, int _27, int _28, int _29, int _30, int _31, int _32, ref int _33) => { _1.ToString(); }</N:2>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); 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 method2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>F{00000001}`3", "C", "<>c"); // <>F{00000001}`3 is the synthesized delegate for the lambda 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(), "<>A{00001000,00000001}`33", "<>F{00000004}`3"); // new synthesized delegate for the new lambda CheckNames(readers, reader1.GetMethodDefNames(), "F", "<F>b__0_0", ".ctor", "Invoke", ".ctor", "Invoke", "<F>b__0_1#1", "<F>b__0_2#1"); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1#1, <>9__0_2#1, <F>b__0_0, <F>b__0_1#1, <F>b__0_2#1}"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); // No new delegate added, reusing from gen 0 and 1 CheckNames(readers, reader2.GetMethodDefNames(), "F", "<F>b__0_0", "<F>b__0_1#1", "<F>b__0_2#1"); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1#1, <>9__0_2#1, <F>b__0_0, <F>b__0_1#1, <F>b__0_2#1}"); } [WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")] [Fact] public void PartialMethod() { var source = @"partial class C { static partial void M1(); static partial void M2(); static partial void M3(); static partial void M1() { } static partial void M2() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor"); var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); var methods = diff1.TestData.GetMethodsByName(); Assert.Equal(1, methods.Count); Assert.True(methods.ContainsKey("C.M2()")); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "M2"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Method_WithAttributes_Add() { var source0 = @"class C { static void Main() { } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); // 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"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_ParameterAttributes() { var source0 = @"class C { static void Main() { } static string F(string input, int a) { return input; } }"; var source1 = @"class C { static void Main() { } static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; } static void G(string input) { } }"; var source2 = @"class C { static void Main() { } static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; } static void G([System.ComponentModel.Description(""input"")]string input) { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var methodF0 = compilation0.GetMember<MethodSymbol>("C.F"); var methodF1 = compilation1.GetMember<MethodSymbol>("C.F"); var methodG1 = compilation1.GetMember<MethodSymbol>("C.G"); var methodG2 = compilation2.GetMember<MethodSymbol>("C.G"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "input", "a"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodF0, methodF1), SemanticEdit.Create(SemanticEditKind.Insert, null, methodG1))); // 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", "G"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor"); CheckNames(readers, reader1.GetParameterDefNames(), "input", "a", "input"); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.Param), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), // New method, G Row(1, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param Row(2, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), // New param on method, G Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Support for the above Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param), Handle(5, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodG1, methodG2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "G"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor"); CheckNames(readers, reader2.GetParameterDefNames(), "input"); CheckAttributes(reader2, new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param, from the first delta Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(4, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef), Handle(5, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyDelegateInvokeMethod_AddAttributes() { var source0 = @" class A : System.Attribute { } delegate void D(int x); "; var source1 = @" class A : System.Attribute { } delegate void D([A]int x); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var invoke0 = compilation0.GetMember<MethodSymbol>("D.Invoke"); var beginInvoke0 = compilation0.GetMember<MethodSymbol>("D.BeginInvoke"); var invoke1 = compilation1.GetMember<MethodSymbol>("D.Invoke"); var beginInvoke1 = compilation1.GetMember<MethodSymbol>("D.BeginInvoke"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, invoke0, invoke1), SemanticEdit.Create(SemanticEditKind.Update, beginInvoke0, beginInvoke1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "Invoke", "BeginInvoke"); CheckNames(readers, reader1.GetParameterDefNames(), "x", "x", "callback", "object"); CheckAttributes(reader1, new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Param), Handle(1, TableIndex.MethodDef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Updating existing parameter defs Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Adding new custom attribute rows Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param), Handle(6, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(2, TableIndex.AssemblyRef)); } /// <summary> /// Add a method that requires entries in the ParameterDefs table. /// Specifically, normal parameters or return types with attributes. /// Add the method in the first edit, then modify the method in the second. /// </summary> [Fact] public void Method_WithParameterAttributes_AddThenUpdate() { var source0 = @"class A : System.Attribute { } class C { }"; var source1 = @"class A : System.Attribute { } class C { [return:A]static object F(int arg = 1) => arg; }"; var source2 = @"class A : System.Attribute { } class C { [return:A]static object F(int arg = 1) => null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetParameterDefNames(), "", "arg"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(1, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetParameterDefNames(), "", "arg"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C"); CheckNames(readers, diff2.EmitResult.UpdatedMethods, "F"); CheckEncLogDefinitions(reader2, Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), // C.F2 Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(2, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void Method_WithEmbeddedAttributes_AndThenUpdate() { var source0 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { class C { static void Main() { } } } "; var source1 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 1 }[0]; } }"; var source2 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} } }"; var source3 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} readonly ref readonly string?[]? F() => throw null; } }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main"); var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id"); var g1 = compilation1.GetMember<MethodSymbol>("N.C.G"); var g2 = compilation2.GetMember<MethodSymbol>("N.C.G"); var h2 = compilation2.GetMember<MethodSymbol>("N.C.H"); var f3 = compilation3.GetMember<MethodSymbol>("N.C.F"); // Verify full metadata contains expected rows. using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, id1), SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute}"); diff1.VerifyIL("N.C.Main", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: nop IL_0001: call ""ref readonly int N.C.G()"" IL_0006: call ""ref readonly int N.C.Id(in int)"" IL_000b: pop IL_000c: ret } "); diff1.VerifyIL("N.C.Id", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } "); diff1.VerifyIL("N.C.G", @" { // Code size 17 (0x11) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.1 IL_0009: stelem.i4 IL_000a: ldc.i4.0 IL_000b: ldelema ""int"" IL_0010: ret } "); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader0 = md0.MetadataReader; var reader1 = md1.Reader; var readers = new List<MetadataReader>() { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute"); CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g1, g2), SemanticEdit.Create(SemanticEditKind.Insert, null, h2))); // synthesized member for nullable annotations added: diff2.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); // note: NullableAttribute has 2 ctors, NullableContextAttribute has one CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute"); CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H"); // two new TypeDefs emitted for the attributes: CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(6, TableIndex.TypeDef), Handle(7, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(2, TableIndex.Field), Handle(7, TableIndex.MethodDef), Handle(8, TableIndex.MethodDef), Handle(9, TableIndex.MethodDef), Handle(10, TableIndex.MethodDef), Handle(11, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(6, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(12, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3))); // no change in synthesized members: diff3.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); // no new type defs: CheckNames(readers, reader3.GetTypeDefFullNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); } [Fact] public void Field_Add() { var source0 = @"class C { string F = ""F""; }"; var source1 = @"class C { string F = ""F""; string G = ""G""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetFieldDefNames(), "F"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var method1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "G"); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Property_Accessor_Update() { var source0 = @"class C { object P { get { return 1; } } }"; var source1 = @"class C { object P { get { return 2; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P"); var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetPropertyDefNames(), "P"); CheckNames(readers, reader1.GetMethodDefNames(), "get_P"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Property_Add() { var source0 = @" class C { } "; var source1 = @" class C { object R { get { return null; } } } "; var source2 = @" class C { object R { get { return null; } } object Q { get; set; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var r1 = compilation1.GetMember<PropertySymbol>("C.R"); var q2 = compilation2.GetMember<PropertySymbol>("C.Q"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, r1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetPropertyDefNames(), "R"); CheckNames(readers, reader1.GetMethodDefNames(), "get_R"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.MethodDef), Handle(1, TableIndex.StandAloneSig), Handle(1, TableIndex.PropertyMap), Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodSemantics)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, q2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField"); CheckNames(readers, reader2.GetPropertyDefNames(), "Q"); CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(1, TableIndex.Field), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(3, TableIndex.MethodSemantics)); } [Fact] public void Event_Add() { var source0 = @" class C { }"; var source1 = @" class C { event System.Action E; }"; var source2 = @" class C { event System.Action E; event System.Action G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var e1 = compilation1.GetMember<EventSymbol>("C.E"); var g2 = compilation2.GetMember<EventSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, e1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "E"); CheckNames(readers, reader1.GetMethodDefNames(), "add_E", "remove_E"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(1, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(1, TableIndex.EventMap), Handle(1, TableIndex.Event), Handle(1, TableIndex.MethodSemantics), Handle(2, TableIndex.MethodSemantics)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "G"); CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader2, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.Field), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics)); } [WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")] [Fact] public void EventFields() { var source0 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 1; } } "); var source1 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 10; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 3 .locals init (int V_0) IL_0000: nop IL_0001: ldsfld ""System.EventHandler C.handler"" IL_0006: ldnull IL_0007: ldnull IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)"" IL_000d: nop IL_000e: ldc.i4.s 10 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); } [Fact] public void UpdateType_AddAttributes() { var source0 = @" class C { }"; var source1 = @" [System.ComponentModel.Description(""C"")] class C { }"; var source2 = @" [System.ComponentModel.Description(""C"")] [System.ObsoleteAttribute] class C { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); Assert.Equal(2, reader2.CustomAttributes.Count); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute)); } [Fact] public void ReplaceType() { var source0 = @" class C { void F(int x) {} } "; var source1 = @" class C { void F(int x, int y) { } }"; var source2 = @" class C { void F(int x, int y) { System.Console.WriteLine(1); } }"; var source3 = @" [System.Obsolete] class C { void F(int x, int y) { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var c3 = compilation3.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); var f3 = c3.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C#1"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param)); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C#2"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2"); CheckEncLogDefinitions(reader2, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param)); // This update is an EnC update - even reloadable types are update in-place var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, c2, c3), SemanticEdit.Create(SemanticEditKind.Update, f2, f3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames(), "C#2"); CheckNames(readers, diff3.EmitResult.ChangedTypes, "C#2"); CheckEncLogDefinitions(reader3, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader3, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void EventFields_Attributes() { var source0 = MarkedSource(@" using System; class C { static event EventHandler E; } "); var source1 = MarkedSource(@" using System; class C { [System.Obsolete] static event EventHandler E; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var event0 = compilation0.GetMember<EventSymbol>("C.E"); var event1 = compilation1.GetMember<EventSymbol>("C.E"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "add_E", "remove_E", ".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, event0, event1))); // 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()); CheckNames(readers, reader1.GetEventDefNames(), "E"); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(10, TableIndex.MemberRef))); CheckEncLogDefinitions(reader1, Row(1, TableIndex.Event, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(8, TableIndex.CustomAttribute), Handle(1, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics)); } [Fact] public void ReplaceType_AsyncLambda() { var source0 = @" using System.Threading.Tasks; class C { void F(int x) { Task.Run(async() => {}); } } "; var source1 = @" using System.Threading.Tasks; class C { void F(bool y) { Task.Run(async() => {}); } } "; var source2 = @" using System.Threading.Tasks; class C { void F(uint z) { Task.Run(async() => {}); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c", "<<F>b__0_0>d"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; // A new nested type <>c is generated in C#1 CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "<>c", "<<F>b__0#1_0#1>d"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "<>c", "<<F>b__0#1_0#1>d"); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; // A new nested type <>c is generated in C#2 CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "<>c", "<<F>b__0#2_0#2>d"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "<>c", "<<F>b__0#2_0#2>d"); } [Fact] public void ReplaceType_AsyncLambda_InNestedType() { var source0 = @" using System.Threading.Tasks; class C { class D { void F(int x) { Task.Run(async() => {}); } } } "; var source1 = @" using System.Threading.Tasks; class C { class D { void F(bool y) { Task.Run(async() => {}); } } } "; var source2 = @" using System.Threading.Tasks; class C { class D { void F(uint z) { Task.Run(async() => {}); } } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D", "<>c", "<<F>b__0_0>d"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; // A new nested type <>c is generated in C#1 CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "D", "<>c", "<<F>b__0#1_0#1>d"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "D", "<>c", "<<F>b__0#1_0#1>d"); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; // A new nested type <>c is generated in C#2 CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "D", "<>c", "<<F>b__0#2_0#2>d"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "D", "<>c", "<<F>b__0#2_0#2>d"); } [Fact] public void AddNestedTypeAndMembers() { var source0 = @"class A { class B { } static object F() { return new B(); } }"; var source1 = @"class A { class B { } class C { class D { } static object F; internal static object G() { return F; } } static object F() { return C.G(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C"); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C", "D"); CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor"); CheckNames(readers, diff1.EmitResult.UpdatedMethods, "F"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "C", "D"); Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(3, TableIndex.NestedClass)); } /// <summary> /// Nested types should be emitted in the /// same order as full emit. /// </summary> [Fact] public void AddNestedTypesOrder() { var source0 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } }"; var source1 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } class B3 { class C3 { } } class B4 { class C4 { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2"); Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4"); Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass)); } [Fact] public void AddNestedGenericType() { var source0 = @"class A { class B<T> { } static object F() { return null; } }"; var source1 = @"class A { class B<T> { internal class C<U> { internal object F<V>() where V : T, new() { return new C<V>(); } } } static object F() { return new B<A>.C<B<object>>().F<A>(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "B`1", "C`1"); CheckNames(readers, reader1.GetTypeDefNames(), "C`1"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.TypeSpec), Handle(2, TableIndex.TypeSpec), Handle(3, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(2, TableIndex.GenericParam), Handle(3, TableIndex.GenericParam), Handle(4, TableIndex.GenericParam), Handle(1, TableIndex.MethodSpec), Handle(1, TableIndex.GenericParamConstraint)); } [Fact] [WorkItem(54939, "https://github.com/dotnet/roslyn/issues/54939")] public void AddNamespace() { var source0 = @" class C { static void Main() { } }"; var source1 = @" namespace N1.N2 { class D { public static void F() { } } } class C { static void Main() => N1.N2.D.F(); }"; var source2 = @" namespace N1.N2 { class D { public static void F() { } } namespace M1.M2 { class E { public static void G() { } } } } class C { static void Main() => N1.N2.M1.M2.E.G(); }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var main0 = compilation0.GetMember<MethodSymbol>("C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("C.Main"); var main2 = compilation2.GetMember<MethodSymbol>("C.Main"); var d1 = compilation1.GetMember<NamedTypeSymbol>("N1.N2.D"); var e2 = compilation2.GetMember<NamedTypeSymbol>("N1.N2.M1.M2.E"); using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, d1))); diff1.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N1.N2.D.F()"" IL_0005: nop IL_0006: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main1, main2), SemanticEdit.Create(SemanticEditKind.Insert, null, e2))); diff2.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N1.N2.M1.M2.E.G()"" IL_0005: nop IL_0006: ret }"); } [Fact] public void ModifyExplicitImplementation() { var source = @"interface I { void M(); } class C : I { void I.M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddThenModifyExplicitImplementation() { var source0 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } }"; var source1 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } void I.M() { } }"; var source2 = source1; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(2, TableIndex.MethodImpl), Handle(2, TableIndex.AssemblyRef)); var generation1 = diff1.NextGeneration; var diff2 = compilation2.EmitDifference( generation1, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetMethodDefNames(), "I.M"); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(7, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(3, TableIndex.AssemblyRef)); } [WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")] [Fact] public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation() { var source = @" interface I { void M(); } class C : I { public C() { } void I.M() { } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddAndModifyInterfaceMembers() { var source0 = @" using System; interface I { }"; var source1 = @" using System; interface I { static int X = 10; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } interface J { } }"; var source2 = @" using System; interface I { static int X = 2; static event Action Y; static I() { X--; } static void M() { X++; } void N() { X++; } static int P { get => 3; set { X++; } } int Q { get => 3; set { X++; } } static event Action E { add { X++; } remove { X++; } } event Action F { add { X++; } remove { X++; } } interface J { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J"); var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P"); var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P"); var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q"); var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q"); var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E"); var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E"); var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F"); var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F"); var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var x2 = compilation2.GetMember<FieldSymbol>("I.X"); var m2 = compilation2.GetMember<MethodSymbol>("I.M"); var n2 = compilation2.GetMember<MethodSymbol>("I.N"); var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P"); var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P"); var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q"); var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q"); var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E"); var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E"); var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F"); var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F"); var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, x1), SemanticEdit.Create(SemanticEditKind.Insert, null, y1), SemanticEdit.Create(SemanticEditKind.Insert, null, m1), SemanticEdit.Create(SemanticEditKind.Insert, null, n1), SemanticEdit.Create(SemanticEditKind.Insert, null, p1), SemanticEdit.Create(SemanticEditKind.Insert, null, q1), SemanticEdit.Create(SemanticEditKind.Insert, null, e1), SemanticEdit.Create(SemanticEditKind.Insert, null, f1), SemanticEdit.Create(SemanticEditKind.Insert, null, j1), SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J"); CheckNames(readers, reader1.GetTypeDefNames(), "J"); CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y"); CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, x1, x2), SemanticEdit.Create(SemanticEditKind.Update, m1, m2), SemanticEdit.Create(SemanticEditKind.Update, n1, n2), SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2), SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2), SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2), SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2), SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2), SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2), SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2), SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2), SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "X"); CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(3, TableIndex.Event, EditAndContinueOperation.Default), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); diff2.VerifyIL(@" { // Code size 14 (0xe) .maxstack 8 IL_0000: nop IL_0001: ldsfld 0x04000001 IL_0006: ldc.i4.1 IL_0007: add IL_0008: stsfld 0x04000001 IL_000d: ret } { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.3 IL_0001: ret } { // Code size 20 (0x14) .maxstack 8 IL_0000: ldc.i4.2 IL_0001: stsfld 0x04000001 IL_0006: nop IL_0007: ldsfld 0x04000001 IL_000c: ldc.i4.1 IL_000d: sub IL_000e: stsfld 0x04000001 IL_0013: ret } "); } [Fact] public void AddAttributeReferences() { var source0 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static object F1; [A] static object P1 { get { return null; } } [B] static event D E1; } delegate void D(); "; var source1 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static void M2<[A]T>() { } [B] static object F1; [A] static object F2; [A] static object P1 { get { return null; } } [B] static object P2 { get { return null; } } [B] static event D E1; [A] static event D E2; } delegate void D(); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(9, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(12, TableIndex.MethodDef), Handle(13, TableIndex.MethodDef), Handle(14, TableIndex.MethodDef), Handle(15, TableIndex.MethodDef), Handle(8, TableIndex.Param), Handle(9, TableIndex.Param), Handle(7, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(18, TableIndex.CustomAttribute), Handle(19, TableIndex.CustomAttribute), Handle(20, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(2, TableIndex.Property), Handle(4, TableIndex.MethodSemantics), Handle(5, TableIndex.MethodSemantics), Handle(6, TableIndex.MethodSemantics), Handle(2, TableIndex.GenericParam)); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)), new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef))); } /// <summary> /// [assembly: ...] and [module: ...] attributes should /// not be included in delta metadata. /// </summary> [Fact] public void AssemblyAndModuleAttributeReferences() { var source0 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { }"; var source1 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { static void M() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var readers = new[] { reader0, md1.Reader }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, md1.Reader.GetTypeDefNames()); CheckNames(readers, md1.Reader.GetMethodDefNames(), "M"); CheckEncLog(md1.Reader, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M CheckEncMap(md1.Reader, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void OtherReferences() { var source0 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { } }"; var source1 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { object o; o = typeof(D); o = F; o = P; E += null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C"); CheckNames(reader0, reader0.GetEventDefNames(), "E"); CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor"); CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); // Emit delta metadata. var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetEventDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M"); CheckNames(readers, reader1.GetPropertyDefNames()); } [Fact] public void ArrayInitializer() { var source0 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3 }; } }"); var source1 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3, 4 }; } }"); var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll); var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs")); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M")))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL( @"{ // Code size 25 (0x19) .maxstack 4 IL_0000: nop IL_0001: ldc.i4.4 IL_0002: newarr 0x0100000D IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.4 IL_0016: stelem.i4 IL_0017: stloc.0 IL_0018: ret }"); diff1.VerifyPdb(new[] { 0x06000001 }, @"<symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" /> </files> <methods> <method token=""0x6000001""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""40"" document=""1"" /> <entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x19""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void PInvokeModuleRefAndImplMap() { var source0 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); }"; var source1 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); [DllImport(""msvcrt.dll"")] public static extern int puts(string s); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.ImplMap)); } /// <summary> /// ClassLayout and FieldLayout tables. /// </summary> [Fact] public void ClassAndFieldLayout() { var source0 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; }"; var source1 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; } [StructLayout(LayoutKind.Explicit, Pack=4)] class B { [FieldOffset(0)]internal short F; [FieldOffset(4)]internal short G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default), Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default), Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.ClassLayout), Handle(3, TableIndex.FieldLayout), Handle(4, TableIndex.FieldLayout), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void NamespacesAndOverloads() { var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source: @"class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); } } }"); var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2"); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var compilation1 = compilation0.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); } } }"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2]))); diff1.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret }"); var compilation2 = compilation1.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); M1(c); } } }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"), compilation2.GetMember<MethodSymbol>("M.C.M2")))); diff2.VerifyIL( @"{ // Code size 26 (0x1a) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000002 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000003 IL_0010: nop IL_0011: ldarg.0 IL_0012: ldarg.3 IL_0013: call 0x06000007 IL_0018: nop IL_0019: ret }"); } [Fact] public void TypesAndOverloads() { const string source = @"using System; struct A<T> { internal class B<U> { } } class B { } class C { static void M(A<B>.B<object> a) { M(a); M((A<B>.B<B>)null); } static void M(A<B>.B<B> a) { M(a); M((A<B>.B<object>)null); } static void M(A<B> a) { M(a); M((A<B>?)a); } static void M(Nullable<A<B>> a) { M(a); M(a.Value); } unsafe static void M(int* p) { M(p); M((byte*)p); } unsafe static void M(byte* p) { M(p); M((int*)p); } static void M(B[][] b) { M(b); M((object[][])b); } static void M(object[][] b) { M(b); M((B[][])b); } static void M(A<B[]>.B<object> b) { M(b); M((A<B[, ,]>.B<object>)null); } static void M(A<B[, ,]>.B<object> b) { M(b); M((A<B[]>.B<object>)null); } static void M(dynamic d) { M(d); M((dynamic[])d); } static void M(dynamic[] d) { M(d); M((dynamic)d); } static void M<T>(A<int>.B<T> t) where T : B { M(t); M((A<double>.B<int>)null); } static void M<T>(A<double>.B<T> t) where T : struct { M(t); M((A<int>.B<B>)null); } }"; var options = TestOptions.UnsafeDebugDll; var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef }); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var n = compilation0.GetMembers("C.M").Length; Assert.Equal(14, n); //static void M(A<B>.B<object> a) //{ // M(a); // M((A<B>.B<B>)null); //} var compilation1 = compilation0.WithSource(source); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0]))); diff1.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(A<B>.B<B> a) //{ // M(a); // M((A<B>.B<object>)null); //} var compilation2 = compilation1.WithSource(source); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1]))); diff2.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000003 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000002 IL_000e: nop IL_000f: ret }"); //static void M(A<B> a) //{ // M(a); // M((A<B>?)a); //} var compilation3 = compilation2.WithSource(source); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2]))); diff3.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000004 IL_0007: nop IL_0008: ldarg.0 IL_0009: newobj 0x0A000016 IL_000e: call 0x06000005 IL_0013: nop IL_0014: ret }"); //static void M(Nullable<A<B>> a) //{ // M(a); // M(a.Value); //} var compilation4 = compilation3.WithSource(source); var diff4 = compilation4.EmitDifference( diff3.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3]))); diff4.VerifyIL( @"{ // Code size 22 (0x16) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000005 IL_0007: nop IL_0008: ldarga.s V_0 IL_000a: call 0x0A000017 IL_000f: call 0x06000004 IL_0014: nop IL_0015: ret }"); //unsafe static void M(int* p) //{ // M(p); // M((byte*)p); //} var compilation5 = compilation4.WithSource(source); var diff5 = compilation5.EmitDifference( diff4.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4]))); diff5.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000006 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000007 IL_000e: nop IL_000f: ret }"); //unsafe static void M(byte* p) //{ // M(p); // M((int*)p); //} var compilation6 = compilation5.WithSource(source); var diff6 = compilation6.EmitDifference( diff5.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5]))); diff6.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000007 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000006 IL_000e: nop IL_000f: ret }"); //static void M(B[][] b) //{ // M(b); // M((object[][])b); //} var compilation7 = compilation6.WithSource(source); var diff7 = compilation7.EmitDifference( diff6.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6]))); diff7.VerifyIL( @"{ // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000008 IL_0007: nop IL_0008: ldarg.0 IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: call 0x06000009 IL_0010: nop IL_0011: ret }"); //static void M(object[][] b) //{ // M(b); // M((B[][])b); //} var compilation8 = compilation7.WithSource(source); var diff8 = compilation8.EmitDifference( diff7.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7]))); diff8.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000009 IL_0007: nop IL_0008: ldarg.0 IL_0009: castclass 0x1B00000A IL_000e: call 0x06000008 IL_0013: nop IL_0014: ret }"); //static void M(A<B[]>.B<object> b) //{ // M(b); // M((A<B[,,]>.B<object>)null); //} var compilation9 = compilation8.WithSource(source); var diff9 = compilation9.EmitDifference( diff8.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8]))); diff9.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000A IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000B IL_000e: nop IL_000f: ret }"); //static void M(A<B[,,]>.B<object> b) //{ // M(b); // M((A<B[]>.B<object>)null); //} var compilation10 = compilation9.WithSource(source); var diff10 = compilation10.EmitDifference( diff9.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9]))); diff10.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000B IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000A IL_000e: nop IL_000f: ret }"); // TODO: dynamic #if false //static void M(dynamic d) //{ // M(d); // M((dynamic[])d); //} previousMethod = compilation.GetMembers("C.M")[10]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(dynamic[] d) //{ // M(d); // M((dynamic)d); //} previousMethod = compilation.GetMembers("C.M")[11]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); #endif //static void M<T>(A<int>.B<T> t) where T : B //{ // M(t); // M((A<double>.B<int>)null); //} var compilation11 = compilation10.WithSource(source); var diff11 = compilation11.EmitDifference( diff10.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12]))); diff11.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000005 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000006 IL_000e: nop IL_000f: ret }"); //static void M<T>(A<double>.B<T> t) where T : struct //{ // M(t); // M((A<int>.B<B>)null); //} var compilation12 = compilation11.WithSource(source); var diff12 = compilation12.EmitDifference( diff11.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13]))); diff12.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000007 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000008 IL_000e: nop IL_000f: ret }"); } [Fact] public void Struct_ImplementSynthesizedConstructor() { var source0 = @" struct S { int a = 1; int b; } "; var source1 = @" struct S { int a = 1; int b; public S() { b = 2; } } "; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var ctor0 = compilation0.GetMember<MethodSymbol>("S..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("S..ctor"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); // Verify full metadata contains expected rows. var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "S"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1))); // 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(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } /// <summary> /// Types should be retained in deleted locals /// for correct alignment of remaining locals. /// </summary> [Fact] public void DeletedValueTypeLocal() { var source0 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var x = new S1(1, 2); var y = new S2(3); System.Console.WriteLine(y.C); } }"; var source1 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var y = new S2(3); System.Console.WriteLine(y.C); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.Main"); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); testData0.GetMethodData("C.Main").VerifyIL( @" { // Code size 31 (0x1f) .maxstack 3 .locals init (S1 V_0, //x S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""S1..ctor(int, int)"" IL_000a: ldloca.s V_1 IL_000c: ldc.i4.3 IL_000d: call ""S2..ctor(int)"" IL_0012: ldloc.1 IL_0013: ldfld ""int S2.C"" IL_0018: call ""void System.Console.WriteLine(int)"" IL_001d: nop IL_001e: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @"{ // Code size 22 (0x16) .maxstack 2 .locals init ([unchanged] V_0, S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_1 IL_0003: ldc.i4.3 IL_0004: call ""S2..ctor(int)"" IL_0009: ldloc.1 IL_000a: ldfld ""int S2.C"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret }"); } /// <summary> /// Instance and static constructors synthesized for /// PrivateImplementationDetails should not be /// generated for delta. /// </summary> [Fact] public void PrivateImplementationDetails() { var source = @"class C { static int[] F = new int[] { 1, 2, 3 }; int[] G = new int[] { 4, 5, 6 }; int M(int index) { return F[index] + G[index]; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var reader0 = md0.MetadataReader; var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames()); Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal))); } var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 3 .locals init ([int] V_0, int V_1) IL_0000: nop IL_0001: ldsfld ""int[] C.F"" IL_0006: ldarg.1 IL_0007: ldelem.i4 IL_0008: ldarg.0 IL_0009: ldfld ""int[] C.G"" IL_000e: ldarg.1 IL_000f: ldelem.i4 IL_0010: add IL_0011: stloc.1 IL_0012: br.s IL_0014 IL_0014: ldloc.1 IL_0015: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromMetadata() { var source0 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[0]); } }"; var source1 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[1]); } }"; var source2 = @"class C { static void M() { int[] a = { 4, 5, 6, 7, 8, 9, 10 }; System.Console.WriteLine(a[1]); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE")); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); methodData0.VerifyIL( @" { // Code size 29 (0x1d) .maxstack 3 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: ldelem.i4 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop IL_001c: ret } "); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 30 (0x1e) .maxstack 4 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: nop IL_001d: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 48 (0x30) .maxstack 4 .locals init ([unchanged] V_0, int[] V_1) //a IL_0000: nop IL_0001: ldc.i4.7 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.4 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.5 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.6 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.7 IL_0016: stelem.i4 IL_0017: dup IL_0018: ldc.i4.4 IL_0019: ldc.i4.8 IL_001a: stelem.i4 IL_001b: dup IL_001c: ldc.i4.5 IL_001d: ldc.i4.s 9 IL_001f: stelem.i4 IL_0020: dup IL_0021: ldc.i4.6 IL_0022: ldc.i4.s 10 IL_0024: stelem.i4 IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldc.i4.1 IL_0028: ldelem.i4 IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromSource() { // PrivateImplementationDetails not needed initially. var source0 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } }"; var source1 = @"class C { static object F1() { return new[] { 1, 2, 3 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return null; } static object F4() { return new[] { 7, 8, 9 }; } }"; var source2 = @"class C { static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return new[] { 13, 14, 15 }; } static object F4() { return new[] { 7, 8, 9 }; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4")))); diff1.VerifyIL("C.F1", @"{ // Code size 24 (0x18) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret }"); diff1.VerifyIL("C.F4", @"{ // Code size 25 (0x19) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.7 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.8 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.s 9 IL_0013: stelem.i4 IL_0014: stloc.0 IL_0015: br.s IL_0017 IL_0017: ldloc.0 IL_0018: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3")))); diff2.VerifyIL("C.F1", @"{ // Code size 49 (0x31) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: brtrue.s IL_002c IL_0016: pop IL_0017: ldc.i4.3 IL_0018: newarr ""int"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.s 10 IL_0021: stelem.i4 IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.s 11 IL_0026: stelem.i4 IL_0027: dup IL_0028: ldc.i4.2 IL_0029: ldc.i4.s 12 IL_002b: stelem.i4 IL_002c: stloc.0 IL_002d: br.s IL_002f IL_002f: ldloc.0 IL_0030: ret }"); diff2.VerifyIL("C.F3", @"{ // Code size 27 (0x1b) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.s 13 IL_000b: stelem.i4 IL_000c: dup IL_000d: ldc.i4.1 IL_000e: ldc.i4.s 14 IL_0010: stelem.i4 IL_0011: dup IL_0012: ldc.i4.2 IL_0013: ldc.i4.s 15 IL_0015: stelem.i4 IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret }"); } /// <summary> /// Should not generate method for string switch since /// the CLR only allows adding private members. /// </summary> [WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")] [Fact] public void PrivateImplementationDetails_ComputeStringHash() { var source = @"class C { static int F(string s) { switch (s) { case ""1"": return 1; case ""2"": return 2; case ""3"": return 3; case ""4"": return 4; case ""5"": return 5; case ""6"": return 6; case ""7"": return 7; default: return 0; } } }"; const string ComputeStringHashName = "ComputeStringHash"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); // Should have generated call to ComputeStringHash and // added the method to <PrivateImplementationDetails>. var actualIL0 = methodData0.GetMethodIL(); Assert.True(actualIL0.Contains(ComputeStringHashName)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Should not have generated call to ComputeStringHash nor // added the method to <PrivateImplementationDetails>. var actualIL1 = diff1.GetMethodIL("C.F"); Assert.False(actualIL1.Contains(ComputeStringHashName)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "F"); } /// <summary> /// Unique ids should not conflict with ids /// from previous generation. /// </summary> [WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")] public void UniqueIds() { var source0 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; System.Func<int> g = () => 2; return (b ? f : g)(); } }"; var source1 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; return f(); } }"; var source2 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> g = () => 2; return g(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1]))); diff1.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //f int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__5()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1]))); diff2.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //g int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__7()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); } /// <summary> /// Avoid adding references from method bodies /// other than the changed methods. /// </summary> [Fact] public void ReferencesInIL() { var source0 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.WriteLine(2); } }"; var source1 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.Write(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create( SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // "Write" should be included in string table, but "WriteLine" should not. Assert.True(diff1.MetadataDelta.IsIncluded("Write")); Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine")); } /// <summary> /// Local slots must be preserved based on signature. /// </summary> [Fact] public void PreserveLocalSlots() { var source0 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); A<B> y = F(); object z = F(); M(x); M(y); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" }; var source1 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { B z = F(); A<B> y = F(); object w = F(); M(w); M(y); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source2 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source3 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object c = F(); object b = F(); M(c); M(b); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("B.M"); var methodN = compilation0.GetMember<MethodSymbol>("B.N"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo()); #region Gen1 var method1 = compilation1.GetMember<MethodSymbol>("B.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL( @"{ // Code size 36 (0x24) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.3 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: call 0x06000002 IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: call 0x06000003 IL_001b: nop IL_001c: ldloc.1 IL_001d: call 0x06000003 IL_0022: nop IL_0023: ret }"); diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" /> <entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" /> <entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x24""> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen2 var method2 = compilation2.GetMember<MethodSymbol>("B.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL( @"{ // Code size 30 (0x1e) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.s V_5 IL_0008: call 0x06000002 IL_000d: stloc.3 IL_000e: ldloc.s V_5 IL_0010: call 0x06000003 IL_0015: nop IL_0016: ldloc.3 IL_0017: call 0x06000003 IL_001c: nop IL_001d: ret }"); diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" /> <entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1e""> <local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen3 // Modify different method. (Previous generations // have not referenced method.) method2 = compilation2.GetMember<MethodSymbol>("B.N"); var method3 = compilation3.GetMember<MethodSymbol>("B.N"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL( @"{ // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.2 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: ldloc.2 IL_000e: call 0x06000003 IL_0013: nop IL_0014: ldloc.1 IL_0015: call 0x06000003 IL_001a: nop IL_001b: ret }"); diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000004""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""24"" document=""1"" /> <entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" /> <entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" /> <entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" /> <entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion } /// <summary> /// Preserve locals for method added after initial compilation. /// </summary> [Fact] public void PreserveLocalSlots_NewMethod() { var source0 = @"class C { }"; var source1 = @"class C { static void M() { var a = new object(); var b = string.Empty; } }"; var source2 = @"class C { static void M() { var a = 1; var b = string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 10 (0xa) .maxstack 1 .locals init ([object] V_0, string V_1, //b int V_2) //a IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldsfld ""string string.Empty"" IL_0008: stloc.1 IL_0009: ret }"); diff2.VerifyPdb(new[] { 0x06000002 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" /> <entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } /// <summary> /// Local types should be retained, even if the local is no longer /// used by the method body, since there may be existing /// references to that slot, in a Watch window for instance. /// </summary> [WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")] [Fact] public void PreserveLocalTypes() { var source0 = @"class C { static void Main() { var x = true; var y = x; System.Console.WriteLine(y); } }"; var source1 = @"class C { static void Main() { var x = ""A""; var y = x; System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @" { // Code size 17 (0x11) .maxstack 1 .locals init ([bool] V_0, [bool] V_1, string V_2, //x string V_3) //y IL_0000: nop IL_0001: ldstr ""A"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: stloc.3 IL_0009: ldloc.3 IL_000a: call ""void System.Console.WriteLine(string)"" IL_000f: nop IL_0010: ret }"); } /// <summary> /// Preserve locals if SemanticEdit.PreserveLocalVariables is set. /// </summary> [Fact] public void PreserveLocalVariablesFlag() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (F()) { } using (var x = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1a = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false))); diff1a.VerifyIL("C.M", @" { // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret } "); var diff1b = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true))); diff1b.VerifyIL("C.M", @"{ // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret }"); } [WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")] [Fact] public void ChangeLocalType() { var source0 = @"enum E { } class C { static void M1() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in one method to type added. var source1 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in another method. var source2 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in same method. var source3 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(A); System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M1"); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M2"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M2", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method3 = compilation3.GetMember<MethodSymbol>("C.M2"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL("C.M2", @"{ // Code size 18 (0x12) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [unchanged] V_2, A V_3, //x A V_4, //y A V_5) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldnull IL_0007: stloc.s V_5 IL_0009: ldloc.s V_4 IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret }"); } [Fact] public void AnonymousTypes_Update() { var source0 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 1 }</N:0>; } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md1 = diff1.GetMetadata(); AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader })); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } [Fact] public void AnonymousTypes_UpdateAfterAdd() { var source0 = MarkedSource(@" class C { static void F() { } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } /// <summary> /// Reuse existing anonymous types. /// </summary> [WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")] [Fact] public void AnonymousTypes() { var source0 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = x.A; var z = new { }; } } }"; var source1 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = new { A = x.A }; var z = new { }; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var m0 = compilation0.GetMember<MethodSymbol>("M.B.M"); var m1 = compilation1.GetMember<MethodSymbol>("M.B.M"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider()); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type diff1.VerifyIL("M.B.M", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (<>f__AnonymousType1<int, int> V_0, //x [int] V_1, <>f__AnonymousType2 V_2, //z <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.3 IL_0002: ldc.i4.4 IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get"" IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_0014: stloc.3 IL_0015: newobj ""<>f__AnonymousType2..ctor()"" IL_001a: stloc.2 IL_001b: ret }"); } /// <summary> /// Anonymous type names with module ids /// and gaps in indices. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")] [WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")] public void AnonymousTypes_OtherTypeNames() { var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } // Valid signature, although not sequential index .class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object { .field public !'<A>j__TPar' A .field public !'<B>j__TPar' B } // Invalid signature, unexpected type parameter names .class '<>f__AnonymousType1'<A, B> extends object { .field public !A A .field public !B B } // Module id, duplicate index .class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object { .field public !'<A>j__TPar' A } // Module id .class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object { .field public !'<B>j__TPar' B } .class public C extends object { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F() { ldnull ret } }"; var source0 = @"class C { static object F() { return 0; } }"; var source1 = @"class C { static object F() { var x = new { A = new object(), B = 1 }; var y = new { A = x.A }; return y; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); diff1.VerifyIL("C.F", @"{ // Code size 31 (0x1f) .maxstack 2 .locals init (<>f__AnonymousType2<object, int> V_0, //x <>f__AnonymousType3<object> V_1, //y object V_2) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: ldc.i4.1 IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get"" IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)"" IL_0018: stloc.1 IL_0019: ldloc.1 IL_001a: stloc.2 IL_001b: br.s IL_001d IL_001d: ldloc.2 IL_001e: ret }"); } /// <summary> /// Update method with anonymous type that was /// not directly referenced in previous generation. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration() { var source0 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x; } }"); var source1 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x + 1; } }"); var source2 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 2 }</N:2>; return x.A; } }"); var source3 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 3 }</N:2>; return y.B; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var compilation3 = compilation2.WithSource(source3.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var method0 = compilation0.GetMember<MethodSymbol>("B.G"); var method1 = compilation1.GetMember<MethodSymbol>("B.G"); var method2 = compilation2.GetMember<MethodSymbol>("B.G"); var method3 = compilation3.GetMember<MethodSymbol>("B.G"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types diff1.VerifyIL("B.G", @" { // Code size 16 (0x10) .maxstack 2 .locals init (int V_0, //x [object] V_1, object V_2) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: add IL_0006: box ""int"" IL_000b: stloc.2 IL_000c: br.s IL_000e IL_000e: ldloc.2 IL_000f: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type diff2.VerifyIL("B.G", @" { // Code size 33 (0x21) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y object V_5) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.2 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.3 IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get"" IL_001a: stloc.s V_5 IL_001c: br.s IL_001e IL_001e: ldloc.s V_5 IL_0020: ret }"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true))); var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types diff3.VerifyIL("B.G", @" { // Code size 39 (0x27) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y [object] V_5, object V_6) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.3 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get"" IL_001b: box ""int"" IL_0020: stloc.s V_6 IL_0022: br.s IL_0024 IL_0024: ldloc.s V_6 IL_0026: ret }"); } /// <summary> /// Update another method (without directly referencing /// anonymous type) after updating method with anonymous type. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration_2() { var source0 = @"class C { static object F() { var x = new { A = 1 }; return x.A; } static object G() { var x = 1; return x; } }"; var source1 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x; } }"; var source2 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x + 1; } }"; var source3 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = new { A = (object)null }; var y = new { A = 'a', B = 'b' }; return x; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( md0, m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch { "F" => testData0.GetMethodData("C.F").GetEncDebugInfo(), "G" => testData0.GetMethodData("C.G").GetEncDebugInfo(), _ => default, }); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); // no additional types var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true))); using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); CheckNames(readers, reader3.GetTypeDefNames()); // no additional types } /// <summary> /// Local from previous generation is of an anonymous /// type not available in next generation. /// </summary> [Fact] public void AnonymousTypes_AddThenDelete() { var source0 = @"class C { object A; static object F() { var x = new C(); var y = x.A; return y; } }"; var source1 = @"class C { static object F() { var x = new { A = new object() }; var y = x.A; return y; } }"; var source2 = @"class C { static object F() { var x = new { A = new object(), B = 2 }; var y = x.A; y = new { B = new object() }.B; return y; } }"; var source3 = @"class C { static object F() { var x = new { A = new object(), B = 3 }; var y = x.A; return y; } }"; var source4 = @"class C { static object F() { var x = new { B = 4, A = new object() }; var y = x.A; return y; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var compilation4 = compilation3.WithSource(source4); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type diff1.VerifyIL("C.F", @" { // Code size 27 (0x1b) .maxstack 1 .locals init ([unchanged] V_0, object V_1, //y [object] V_2, <>f__AnonymousType0<object> V_3, //x object V_4) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)"" IL_000b: stloc.3 IL_000c: ldloc.3 IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get"" IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: stloc.s V_4 IL_0016: br.s IL_0018 IL_0018: ldloc.s V_4 IL_001a: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); } [Fact] public void AnonymousTypes_DifferentCase() { var source0 = MarkedSource(@" class C { static void M() { var <N:0>x = new { A = 1, B = 2 }</N:0>; var <N:1>y = new { a = 3, b = 4 }</N:1>; } }"); var source1 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { AB = 3 }</N:1>; } }"); var source2 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { Ab = 5 }</N:1>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var reader1 = diff1.GetMetadata().Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1"); // the first two slots can't be reused since the type changed diff1.VerifyIL("C.M", @"{ // Code size 17 (0x11) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.3 IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_000f: stloc.3 IL_0010: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var reader2 = diff2.GetMetadata().Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1"); // we can reuse slot for "x", it's type haven't changed diff2.VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x [unchanged] V_3, <>f__AnonymousType4<int> V_4) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)"" IL_000f: stloc.s V_4 IL_0011: ret }"); } [Fact] public void AnonymousTypes_Nested1() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Nested2() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Query1() { var source0 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> <N:3>select new { Value = a, Length = a.Length }</N:3></N:4>; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value</N:8>; args = args.Concat(newArgs).ToArray(); System.Diagnostics.Debugger.Break(); result.ToString(); } } "); var source1 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }; for (int i = 0; i < 10; i++) { var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby a.Length ascending, a descending <N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>; var linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, (total, curr) => new { Head = curr.Value, Tail = (dynamic)total }); var str = linked?.Tail?.Head; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value + value</N:8>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1) //newArgs "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>o__0#1: {<>p__0}", "C: {<>o__0#1, <>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}", "<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1, //newArgs <>f__AnonymousType5<dynamic, dynamic> V_2, //list int V_3, //i <>f__AnonymousType5<string, dynamic> V_4, //linked object V_5, //str <>f__AnonymousType5<string, dynamic> V_6, object V_7, bool V_8) "); } [Fact] public void AnonymousTypes_Dynamic1() { var template = @" using System; class C { public void F() { var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>; Console.WriteLine(x.B + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL0 = @" { // Code size 22 (0x16) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret } "; v0.VerifyIL("C.F", baselineIL0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); var baselineIL = @" { // Code size 24 (0x18) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: ldc.i4.<<VALUE>> IL_0010: add IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: nop IL_0017: ret } "; diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2")); } /// <summary> /// Should not re-use locals if the method metadata /// signature is unsupported. /// </summary> [WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")] public void LocalType_UnsupportedSignatureContent() { // Equivalent to C#, but with extra local and required modifier on // expected local. Used to generate initial (unsupported) metadata. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class C { .method public specialname rtspecialname instance void .ctor() { ret } .method private static object F() { ldnull ret } .method private static void M1() { .locals init ([0] object other, [1] object modreq(int32) o) call object C::F() stloc.1 ldloc.1 call void C::M2(object) ret } .method private static void M2(object o) { ret } }"; var source = @"class C { static object F() { return null; } static void M1() { object o = F(); M2(o); } static void M2(object o) { } }"; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 15 (0xf) .maxstack 1 .locals init (object V_0) //o IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void C.M2(object)"" IL_000d: nop IL_000e: ret }"); } /// <summary> /// Should not re-use locals with custom modifiers. /// </summary> [WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")] public void LocalType_CustomModifiers() { // Equivalent method signature to C#, but // with optional modifier on locals. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public C { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F(class [mscorlib]System.IDisposable d) { .locals init ([0] class C modopt(int32) c, [1] class [mscorlib]System.IDisposable modopt(object), [2] bool V_2, [3] object V_3) ldnull ret } }"; var source = @"class C { static object F(System.IDisposable d) { C c; using (d) { c = (C)d; } return c; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( moduleMetadata0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [bool] V_2, [object] V_3, C V_4, //c System.IDisposable V_5, object V_6) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: stloc.s V_5 .try { -IL_0004: nop -IL_0005: ldarg.0 IL_0006: castclass ""C"" IL_000b: stloc.s V_4 -IL_000d: nop IL_000e: leave.s IL_001d } finally { ~IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_001c IL_0014: ldloc.s V_5 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop IL_001c: endfinally } -IL_001d: ldloc.s V_4 IL_001f: stloc.s V_6 IL_0021: br.s IL_0023 -IL_0023: ldloc.s V_6 IL_0025: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } /// <summary> /// Temporaries for locals used within a single /// statement should not be preserved. /// </summary> [Fact] public void TemporaryLocals_Other() { // Use increment as an example of a compiler generated // temporary that does not span multiple statements. var source = @"class C { int P { get; set; } static int M() { var c = new C(); return c.P++; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 32 (0x20) .maxstack 3 .locals init (C V_0, //c [int] V_1, [int] V_2, int V_3, int V_4) IL_0000: nop IL_0001: newobj ""C..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: dup IL_0009: callvirt ""int C.P.get"" IL_000e: stloc.3 IL_000f: ldloc.3 IL_0010: ldc.i4.1 IL_0011: add IL_0012: callvirt ""void C.P.set"" IL_0017: nop IL_0018: ldloc.3 IL_0019: stloc.s V_4 IL_001b: br.s IL_001d IL_001d: ldloc.s V_4 IL_001f: ret }"); } /// <summary> /// Local names array (from PDB) may have fewer slots than method /// signature (from metadata) when the trailing slots are unnamed. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); testData0.GetMethodData("C.M").VerifyIL(@" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); } /// <summary> /// Similar to above test but with no named locals in original. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270_NoNamedLocals() { // Equivalent to C#, but with unnamed locals. // Used to generate initial metadata. var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } .assembly '<<GeneratedFileName>>' { } .class C extends object { .method private static class [netstandard]System.IDisposable F() { ldnull ret } .method private static void M() { .locals init ([0] object, [1] object) ret } }"; var source0 = @"class C { static System.IDisposable F() { return null; } static void M() { } }"; var source1 = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init ([object] V_0, [object] V_1, System.IDisposable V_2) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.2 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.2 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.2 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret } "); } [Fact] public void TemporaryLocals_ReferencedType() { var source = @"class C { static object F() { return null; } static void M() { var x = new System.Collections.Generic.HashSet<int>(); x.Add(1); } }"; var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var modMeta = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( modMeta, methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.HashSet<int> V_0) //x IL_0000: nop IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)"" IL_000e: pop IL_000f: ret } "); } [WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")] [WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")] [Fact] public void DynamicOperations() { var source = @"class A { static object F = null; object x = ((dynamic)F) + 1; static A() { ((dynamic)F).F(); } A() { } static void M(object o) { ((dynamic)o).x = 1; } static void N(A o) { o.x = 1; } } class B { static object F = null; static object G = ((dynamic)F).F(); object x = ((dynamic)F) + 1; }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); // Source method with dynamic operations. var methodData0 = testData0.GetMethodData("A.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("A.M"); var method1 = compilation1.GetMember<MethodSymbol>("A.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Source method with no dynamic operations. methodData0 = testData0.GetMethodData("A.N"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A.N"); method1 = compilation1.GetMember<MethodSymbol>("A.N"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("A..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..ctor"); method1 = compilation1.GetMember<MethodSymbol>("A..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("A..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..cctor"); method1 = compilation1.GetMember<MethodSymbol>("A..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("B..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..ctor"); method1 = compilation1.GetMember<MethodSymbol>("B..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("B..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..cctor"); method1 = compilation1.GetMember<MethodSymbol>("B..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void DynamicLocals() { var template = @" using System; class C { public void F() { dynamic <N:0>x = 1</N:0>; Console.WriteLine((int)x + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 82 (0x52) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: call ""void System.Console.WriteLine(int)"" IL_0050: nop IL_0051: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>o__0#1}", "C.<>o__0#1: {<>p__0}"); diff1.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.1 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>o__0#2, <>o__0#1}", "C.<>o__0#1: {<>p__0}", "C.<>o__0#2: {<>p__0}"); diff2.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.2 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); } [Fact] public void ExceptionFilters() { var source0 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } } } "); var source1 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } Console.WriteLine(1); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 90 (0x5a) .maxstack 2 .locals init (System.IO.IOException V_0, //e bool V_1, System.Exception V_2, //e bool V_3) IL_0000: nop .try { IL_0001: nop IL_0002: newobj ""System.InvalidOperationException..ctor()"" IL_0007: throw } filter { IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_0020 IL_0014: stloc.0 IL_0015: ldloc.0 IL_0016: call ""bool C.G(System.Exception)"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: ldc.i4.0 IL_001e: cgt.un IL_0020: endfilter } // end filter { // handler IL_0022: pop IL_0023: nop IL_0024: call ""void System.Console.WriteLine()"" IL_0029: nop IL_002a: nop IL_002b: leave.s IL_0052 } filter { IL_002d: isinst ""System.Exception"" IL_0032: dup IL_0033: brtrue.s IL_0039 IL_0035: pop IL_0036: ldc.i4.0 IL_0037: br.s IL_0045 IL_0039: stloc.2 IL_003a: ldloc.2 IL_003b: call ""bool C.G(System.Exception)"" IL_0040: stloc.3 IL_0041: ldloc.3 IL_0042: ldc.i4.0 IL_0043: cgt.un IL_0045: endfilter } // end filter { // handler IL_0047: pop IL_0048: nop IL_0049: call ""void System.Console.WriteLine()"" IL_004e: nop IL_004f: nop IL_0050: leave.s IL_0052 } IL_0052: ldc.i4.1 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void MethodSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(2); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } [WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void LocalSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(null); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(x); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,16): warning CS0219: The variable 'y' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"), // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } /// <summary> /// Disallow edits that require NoPIA references. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIAReferences() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")] public interface IA { void M(); int P { get; } event Action E; } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")] public interface IB { } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")] public interface IC { } public struct S { public object F; }"; var source0 = @"class C<T> { static object F = typeof(IC); static void M1() { var o = default(IA); o.M(); M2(o.P); o.E += M1; M2(C<IA>.F); M2(new S()); } static void M2(object o) { } }"; var source1A = source0; var source1B = @"class C<T> { static object F = typeof(IC); static void M1() { M2(null); } static void M2(object o) { } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1A = compilation0.WithSource(source1A); var compilation1B = compilation0.WithSource(source1B); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var method1B = compilation1B.GetMember<MethodSymbol>("C.M1"); var method1A = compilation1A.GetMember<MethodSymbol>("C.M1"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C<T>.M1"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); // Disallow edits that require NoPIA references. var diff1A = compilation1A.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true))); diff1A.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA")); // Allow edits that do not require NoPIA references, // even if the previous code included references. var diff1B = compilation1B.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true))); diff1B.VerifyIL("C<T>.M1", @"{ // Code size 9 (0x9) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1) IL_0000: nop IL_0001: ldnull IL_0002: call ""void C<T>.M2(object)"" IL_0007: nop IL_0008: ret }"); using var md1 = diff1B.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); } [WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIATypeInNamespace() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")] namespace N { [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")] public interface IA { } } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")] public interface IB { }"; var source = @"class C<T> { static void M(object o) { M(C<N.IA>.E.X); M(C<IB>.E.X); } enum E { X } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB")); diff1.VerifyIL("C<T>.M", @"{ // Code size 26 (0x1a) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""C<N.IA>.E"" IL_0007: call ""void C<T>.M(object)"" IL_000c: nop IL_000d: ldc.i4.0 IL_000e: box ""C<IB>.E"" IL_0013: call ""void C<T>.M(object)"" IL_0018: nop IL_0019: ret }"); } /// <summary> /// Should use TypeDef rather than TypeRef for unrecognized /// local of a type defined in the original assembly. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfTypeFromAssembly() { var source = @"class E : System.Exception { } class C { static void M() { try { } catch (E e) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeRefNames(), "Object"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL("C.M", @" { // Code size 11 (0xb) .maxstack 1 .locals init (E V_0) //e IL_0000: nop .try { IL_0001: nop IL_0002: nop IL_0003: leave.s IL_000a } catch E { IL_0005: stloc.0 IL_0006: nop IL_0007: nop IL_0008: leave.s IL_000a } IL_000a: ret }"); } /// <summary> /// Similar to above test but with anonymous type /// added in subsequent generation. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfAnonymousTypeFromAssembly() { var source0 = @"class C { static string F() { return null; } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source2 = @"class C { static string F() { return null; } static string G() { return null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var method1G = compilation1.GetMember<MethodSymbol>("C.G"); var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var method2G = compilation2.GetMember<MethodSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); // Use empty LocalVariableNameProvider for original locals and // use preserveLocalVariables: true for the edit so that existing // locals are retained even though all are unrecognized. var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1"); CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider"); // Change method updated in generation 1. var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetTypeRefNames(), "Object"); // Change method unchanged since generation 0. var diff2G = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true))); } [Fact] public void BrokenOutputStreams() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, badStream, ilStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, badStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [Fact] public void BrokenPortablePdbStream() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors() { var source0 = @"class C { }"; var source1 = @"class C { static void Main() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))), testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() }); diff1.EmitResult.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message")); Assert.False(diff1.EmitResult.Success); } [WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")] [Fact] public void BlobContainsInvalidValues() { var source0 = @"class C { static void F() { string goo = ""abc""; } }"; var source1 = @"class C { static void F() { float goo = 10; } }"; var source2 = @"class C { static void F() { bool goo = true; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); var handle = MetadataTokens.BlobHandle(1); byte[] value0 = reader0.GetBlobBytes(handle); Assert.Equal("20-01-01-08", BitConverter.ToString(value0)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); byte[] value1 = reader1.GetBlobBytes(handle); Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1)); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; byte[] value2 = reader2.GetBlobBytes(handle); Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly1() { var sourceA0 = @" public class A { } "; var sourceA1 = @" public class A { public void M() { System.Console.WriteLine(1);} } public class X {} "; var sourceB0 = @" public class B { public static void F() { } }"; var sourceB1 = @" public class B { public static void F() { new A().M(); } } public class Y : X { } "; var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA"); var compilationA1 = compilationA0.WithSource(sourceA1); var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var bytesA0 = compilationA0.EmitToArray(); var bytesB0 = compilationB0.EmitToArray(); var mdA0 = ModuleMetadata.CreateFromImage(bytesA0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider); var mA1 = compilationA1.GetMember<MethodSymbol>("A.M"); var mX1 = compilationA1.GetMember<TypeSymbol>("X"); var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() }; var diffA1 = compilationA1.EmitDifference( generationA0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, mA1), SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)), allAddedSymbols); diffA1.EmitResult.Diagnostics.Verify(); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))), allAddedSymbols); diffB1.EmitResult.Diagnostics.Verify( // (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public class X {} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14), // (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public void M() { System.Console.WriteLine(1);} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly2() { var sourceA = @" public class A { public void M() { } }"; var sourceB0 = @" public class B { public static void F() { var a = new A(); } }"; var sourceB1 = @" public class B { public static void F() { var a = new A(); a.M(); } }"; var sourceB2 = @" public class B { public static void F() { var a = new A(); } }"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA"); var aRef = compilationA.ToMetadataReference(); var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB"); var compilationB1 = compilationB0.WithSource(sourceB1); var compilationB2 = compilationB1.WithSource(sourceB2); var testDataB0 = new CompilationTestData(); var bytesB0 = compilationB0.EmitToArray(testData: testDataB0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider()); var f0 = compilationB0.GetMember<MethodSymbol>("B.F"); var f1 = compilationB1.GetMember<MethodSymbol>("B.F"); var f2 = compilationB2.GetMember<MethodSymbol>("B.F"); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); diffB1.VerifyIL("B.F", @" { // Code size 15 (0xf) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: callvirt ""void A.M()"" IL_000d: nop IL_000e: ret } "); var diffB2 = compilationB2.EmitDifference( diffB1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true))); diffB2.VerifyIL("B.F", @" { // Code size 8 (0x8) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void UniqueSynthesizedNames_DynamicSiteContainer() { var source0 = @" public class C { public static void F(dynamic d) { d.Goo(); } }"; var source1 = @" public class C { public static void F(dynamic d) { d.Bar(); } }"; var source2 = @" public class C { public static void F(dynamic d, byte b) { d.Bar(); } public static void F(dynamic d) { d.Bar(); } }"; var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2))); diff2.EmitResult.Diagnostics.Verify(); var reader0 = md0.MetadataReader; var reader1 = diff1.GetMetadata().Reader; var reader2 = diff2.GetMetadata().Reader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0"); CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1"); CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2"); } [WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")] [Fact] public void ManyGenerations() { var source = @"class C {{ static int F() {{ return {0}; }} }}"; var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll); var bytes0 = compilation0.EmitToArray(); var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); for (int i = 2; i <= 50; i++) { var compilation1 = compilation0.WithSource(String.Format(source, i)); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); compilation0 = compilation1; method0 = method1; generation0 = diff1.NextGeneration; } } [WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")] [Fact] public void PdbReadingErrors() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new InvalidDataException("Bad PDB!"); }); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''. Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14)); } [Fact] public void PdbReadingErrors_PassThruExceptions() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new ArgumentOutOfRangeException(); }); // the compiler should't swallow any exceptions but InvalidDataException Assert.Throws<ArgumentOutOfRangeException>(() => compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)))); } [Fact] public void PatternVariable_TypeChange() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 46 (0x2e) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, //i bool V_4, int V_5) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""bool"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""bool"" IL_000f: stloc.3 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.s V_4 IL_0016: ldloc.s V_4 IL_0018: brfalse.s IL_0026 IL_001a: nop IL_001b: ldloc.3 IL_001c: brtrue.s IL_0021 IL_001e: ldc.i4.0 IL_001f: br.s IL_0022 IL_0021: ldc.i4.1 IL_0022: stloc.s V_5 IL_0024: br.s IL_002b IL_0026: ldc.i4.0 IL_0027: stloc.s V_5 IL_0029: br.s IL_002b IL_002b: ldloc.s V_5 IL_002d: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [bool] V_4, [int] V_5, int V_6, //j bool V_7, int V_8) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_6 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_7 IL_0017: ldloc.s V_7 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_6 IL_001e: stloc.s V_8 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_8 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_8 IL_0029: ret }"); } [Fact] public void PatternVariable_DeleteInsert() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is int) { return 1; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 28 (0x1c) .maxstack 2 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, int V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: ldnull IL_0008: cgt.un IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: brfalse.s IL_0014 IL_000e: nop IL_000f: ldc.i4.1 IL_0010: stloc.s V_4 IL_0012: br.s IL_0019 IL_0014: ldc.i4.0 IL_0015: stloc.s V_4 IL_0017: br.s IL_0019 IL_0019: ldloc.s V_4 IL_001b: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [int] V_4, int V_5, //i bool V_6, int V_7) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_5 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_6 IL_0017: ldloc.s V_6 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_5 IL_001e: stloc.s V_7 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_7 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_7 IL_0029: ret }"); } [Fact] public void PatternVariable_InConstructorInitializer() { var baseClass = "public class Base { public Base(bool x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; } }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { } }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.1 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.1 IL_0015: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 15 (0xf) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.0 IL_0005: ceq IL_0007: call ""Base..ctor(bool)"" IL_000c: nop IL_000d: nop IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.2 IL_0015: ret } "); } [Fact] public void PatternVariable_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>; }"); var source1 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.1 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 24 (0x18) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ceq IL_000b: stfld ""bool C.field"" IL_0010: ldarg.0 IL_0011: call ""object..ctor()"" IL_0016: nop IL_0017: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.2 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); } [Fact] public void PatternVariable_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.1 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 7 (0x7) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ceq IL_0006: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.2 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); } [Fact] public void Tuple_Parenthesized() { var source0 = MarkedSource(@" class C { static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"); var source1 = MarkedSource(@" class C { static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; } }"); var source2 = MarkedSource(@" class C { static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 51 (0x33) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_0010: ldloc.0 IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0016: ldloc.0 IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0021: add IL_0022: ldloc.0 IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: add IL_002e: stloc.1 IL_002f: br.s IL_0031 IL_0031: ldloc.1 IL_0032: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 36 (0x24) .maxstack 4 .locals init ([unchanged] V_0, [int] V_1, System.ValueTuple<int, int, int> V_2, //x int V_3) IL_0000: nop IL_0001: ldloca.s V_2 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)"" IL_000b: ldloc.2 IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1"" IL_0011: ldloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2"" IL_0017: add IL_0018: ldloc.2 IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3"" IL_001e: add IL_001f: stloc.3 IL_0020: br.s IL_0022 IL_0022: ldloc.3 IL_0023: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 32 (0x20) .maxstack 3 .locals init ([unchanged] V_0, [int] V_1, [unchanged] V_2, [int] V_3, System.ValueTuple<int, int> V_4, //x int V_5) IL_0000: nop IL_0001: ldloca.s V_4 IL_0003: ldc.i4.1 IL_0004: ldc.i4.3 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.s V_4 IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: ldloc.s V_4 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: add IL_0019: stloc.s V_5 IL_001b: br.s IL_001d IL_001d: ldloc.s V_5 IL_001f: ret } "); } [Fact] public void Tuple_Decomposition() { var source0 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var source1 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; } }"); var source2 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 17 (0x11) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2, //z int V_3) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldc.i4.3 IL_0006: stloc.2 IL_0007: ldloc.0 IL_0008: ldloc.1 IL_0009: add IL_000a: ldloc.2 IL_000b: add IL_000c: stloc.3 IL_000d: br.s IL_000f IL_000f: ldloc.3 IL_0010: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, int V_4) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.3 IL_0004: stloc.2 IL_0005: ldloc.0 IL_0006: ldloc.2 IL_0007: add IL_0008: stloc.s V_4 IL_000a: br.s IL_000c IL_000c: ldloc.s V_4 IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, [int] V_4, int V_5, //y int V_6) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.s V_5 IL_0006: ldc.i4.3 IL_0007: stloc.2 IL_0008: ldloc.0 IL_0009: ldloc.s V_5 IL_000b: add IL_000c: ldloc.2 IL_000d: add IL_000e: stloc.s V_6 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_6 IL_0014: ret } "); } [Fact] public void ForeachStatement() { var source0 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x); } } }"); var source1 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x1); } } }"); var source2 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F()) { System.Console.WriteLine(x1); } } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 70 (0x46) .maxstack 2 .locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0, int V_1, int V_2, //x bool V_3, //y double V_4, //z System.ValueTuple<bool, double> V_5) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 IL_000a: br.s IL_003f IL_000c: ldloc.0 IL_000d: ldloc.1 IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0013: dup IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0019: stloc.s V_5 IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0020: stloc.2 IL_0021: ldloc.s V_5 IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_0028: stloc.3 IL_0029: ldloc.s V_5 IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0030: stloc.s V_4 IL_0032: nop IL_0033: ldloc.2 IL_0034: call ""void System.Console.WriteLine(int)"" IL_0039: nop IL_003a: nop IL_003b: ldloc.1 IL_003c: ldc.i4.1 IL_003d: add IL_003e: stloc.1 IL_003f: ldloc.1 IL_0040: ldloc.0 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_000c IL_0045: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 78 (0x4e) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 bool V_3, //y double V_4, //z [unchanged] V_5, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6, int V_7, System.ValueTuple<bool, double> V_8) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_6 IL_0009: ldc.i4.0 IL_000a: stloc.s V_7 IL_000c: br.s IL_0045 IL_000e: ldloc.s V_6 IL_0010: ldloc.s V_7 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_001d: stloc.s V_8 IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0024: stloc.2 IL_0025: ldloc.s V_8 IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_002c: stloc.3 IL_002d: ldloc.s V_8 IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0034: stloc.s V_4 IL_0036: nop IL_0037: ldloc.2 IL_0038: call ""void System.Console.WriteLine(int)"" IL_003d: nop IL_003e: nop IL_003f: ldloc.s V_7 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.s V_7 IL_0045: ldloc.s V_7 IL_0047: ldloc.s V_6 IL_0049: ldlen IL_004a: conv.i4 IL_004b: blt.s IL_000e IL_004d: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 61 (0x3d) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 [bool] V_3, [unchanged] V_4, [unchanged] V_5, [unchanged] V_6, [int] V_7, [unchanged] V_8, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9, int V_10, System.ValueTuple<bool, double> V_11) //yz IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_9 IL_0009: ldc.i4.0 IL_000a: stloc.s V_10 IL_000c: br.s IL_0034 IL_000e: ldloc.s V_9 IL_0010: ldloc.s V_10 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_001d: stloc.2 IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0023: stloc.s V_11 IL_0025: nop IL_0026: ldloc.2 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop IL_002d: nop IL_002e: ldloc.s V_10 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stloc.s V_10 IL_0034: ldloc.s V_10 IL_0036: ldloc.s V_9 IL_0038: ldlen IL_0039: conv.i4 IL_003a: blt.s IL_000e IL_003c: ret } "); } [Fact] public void OutVar() { var source0 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; } }"); var source1 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; } }"); var source2 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.2 IL_000f: br.s IL_0011 IL_0011: ldloc.2 IL_0012: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //z [int] V_2, int V_3) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.3 IL_000f: br.s IL_0011 IL_0011: ldloc.3 IL_0012: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x int V_1, //y [int] V_2, [int] V_3, int V_4) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.s V_4 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_4 IL_0014: ret } "); } [Fact] public void OutVar_InConstructorInitializer() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); } static int M(out int x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x) { } static int M(out int x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.1 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 18 (0x12) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: call ""Base..ctor(int)"" IL_000f: nop IL_0010: nop IL_0011: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.2 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); } [Fact] public void OutVar_InConstructorInitializer_WithLambda() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0"); diff1.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff1.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0"); diff2.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff2.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InMethodBody_WithLambda() { var source0 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method"); var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method"); var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.1 IL_0025: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff1.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, int V_2) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.2 IL_0025: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff2.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, [int] V_2, int V_3) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.3 IL_0025: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>); static int M(out int x) => throw null; }"); var source1 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x; static int M(out int x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 23 (0x17) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: stfld ""int C.field"" IL_000f: ldarg.0 IL_0010: call ""object..ctor()"" IL_0015: nop IL_0016: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); } [Fact] public void OutVar_InFieldInitializer_WithLambda() { var source0 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff1.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff2.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_1 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 11 (0xb) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_2 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); } [Fact] public void OutVar_InQuery_WithLambda() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InSwitchExpression() { var source0 = MarkedSource(@" public class Program { static object G(int i) { return i switch { 0 => 0, _ => 1 }; } static object N(out int x) { x = 1; return null; } }"); var source1 = MarkedSource(@" public class Program { static object G(int i) { return i + N(out var x) switch { 0 => 0, _ => 1 }; } static int N(out int x) { x = 1; return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.G"); var n1 = compilation1.GetMember<MethodSymbol>("Program.G"); var n2 = compilation2.GetMember<MethodSymbol>("Program.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.G(int)", @" { // Code size 33 (0x21) .maxstack 1 .locals init (int V_0, object V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000e IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_0012 IL_000e: ldc.i4.1 IL_000f: stloc.0 IL_0010: br.s IL_0012 IL_0012: ldc.i4.1 IL_0013: brtrue.s IL_0016 IL_0015: nop IL_0016: ldloc.0 IL_0017: box ""int"" IL_001c: stloc.1 IL_001d: br.s IL_001f IL_001f: ldloc.1 IL_0020: ret } "); v0.VerifyIL("Program.N(out int)", @" { // Code size 10 (0xa) .maxstack 2 .locals init (object V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: stind.i4 IL_0004: ldnull IL_0005: stloc.0 IL_0006: br.s IL_0008 IL_0008: ldloc.0 IL_0009: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers(); diff1.VerifyIL("Program.G(int)", @" { // Code size 52 (0x34) .maxstack 2 .locals init ([int] V_0, [object] V_1, int V_2, //x int V_3, int V_4, int V_5, object V_6) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.3 IL_0003: ldloca.s V_2 IL_0005: call ""int Program.N(out int)"" IL_000a: stloc.s V_5 IL_000c: ldc.i4.1 IL_000d: brtrue.s IL_0010 IL_000f: nop IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_0016 IL_0014: br.s IL_001b IL_0016: ldc.i4.0 IL_0017: stloc.s V_4 IL_0019: br.s IL_0020 IL_001b: ldc.i4.1 IL_001c: stloc.s V_4 IL_001e: br.s IL_0020 IL_0020: ldc.i4.1 IL_0021: brtrue.s IL_0024 IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.s V_4 IL_0027: add IL_0028: box ""int"" IL_002d: stloc.s V_6 IL_002f: br.s IL_0031 IL_0031: ldloc.s V_6 IL_0033: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers(); diff2.VerifyIL("Program.G(int)", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([int] V_0, [object] V_1, [int] V_2, [int] V_3, [int] V_4, [int] V_5, [object] V_6, int V_7, object V_8) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000f IL_000a: ldc.i4.0 IL_000b: stloc.s V_7 IL_000d: br.s IL_0014 IL_000f: ldc.i4.1 IL_0010: stloc.s V_7 IL_0012: br.s IL_0014 IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 IL_0017: nop IL_0018: ldloc.s V_7 IL_001a: box ""int"" IL_001f: stloc.s V_8 IL_0021: br.s IL_0023 IL_0023: ldloc.s V_8 IL_0025: ret } "); } [Fact] public void AddUsing_AmbiguousCode() { var source0 = MarkedSource(@" using System.Threading; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } }"); var source1 = MarkedSource(@" using System.Threading; using System.Timers; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } static void G() { System.Console.WriteLine(new TimersDescriptionAttribute("""")); } }"); var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Pretend there was an update to C.E to ensure we haven't invalidated the test var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer' // var t = new Timer(s => System.Console.WriteLine(s)); Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21)); // Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff.EmitResult.Diagnostics.Verify(); diff.VerifyIL(@"C.G", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldstr """" IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)"" IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret } "); } [Fact] public void Records_AddWellKnownMember() { var source0 = @" #nullable enable namespace N { record R(int X) { } } "; var source1 = @" #nullable enable namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); // Verify full metadata contains expected rows. var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R"); CheckNames(reader0, reader0.GetMethodDefNames(), /* EmbeddedAttribute */".ctor", /* NullableAttribute */ ".ctor", /* NullableContextAttribute */".ctor", /* IsExternalInit */".ctor", /* R: */ ".ctor", "get_EqualityContract", "get_X", "set_X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); // 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(), "PrintMembers"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default), 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)); CheckEncMap(reader1, Handle(20, TableIndex.TypeRef), Handle(21, TableIndex.TypeRef), Handle(22, TableIndex.TypeRef), Handle(10, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Records_RemoveWellKnownMember() { var source0 = @" namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var source1 = @" namespace N { record R(int X) { } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); } [Fact] public void TopLevelStatement_Update() { var source0 = @" using System; Console.WriteLine(""Hello""); "; var source1 = @" using System; Console.WriteLine(""Hello World""); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("Program.<Main>$"); var method1 = compilation1.GetMember<MethodSymbol>("Program.<Main>$"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "Program"); CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine", /*Program.*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // 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(), "<Main>$"); CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), // Synthesized Main method Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void LambdaParameterToDiscard() { var source0 = MarkedSource(@" using System; class C { void M() { var x = new Func<int, int, int>(<N:0>(a, b) => a + b + 1</N:0>); Console.WriteLine(x(1, 2)); } }"); var source1 = MarkedSource(@" using System; class C { void M() { var x = new Func<int, int, int>(<N:0>(_, _) => 10</N:0>); Console.WriteLine(x(1, 2)); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // There should be no diagnostics from rude edits diff.EmitResult.Diagnostics.Verify(); diff.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <M>b__0_0}"); diff.VerifyIL("C.M", @" { // Code size 48 (0x30) .maxstack 3 .locals init ([unchanged] V_0, System.Func<int, int, int> V_1) //x IL_0000: nop IL_0001: ldsfld ""System.Func<int, int, int> C.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""C.<>c C.<>c.<>9"" IL_000f: ldftn ""int C.<>c.<M>b__0_0(int, int)"" IL_0015: newobj ""System.Func<int, int, int>..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""System.Func<int, int, int> C.<>c.<>9__0_0"" IL_0020: stloc.1 IL_0021: ldloc.1 IL_0022: ldc.i4.1 IL_0023: ldc.i4.2 IL_0024: callvirt ""int System.Func<int, int, int>.Invoke(int, int)"" IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); diff.VerifyIL("C.<>c.<M>b__0_0(int, int)", @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 10 IL_0002: ret }"); } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/SymbolMatcherTests.cs
// 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. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class SymbolMatcherTests : EditAndContinueTestBase { private static PEAssemblySymbol CreatePEAssemblySymbol(string source) { var compilation = CreateCompilation(source, options: TestOptions.DebugDll); var reference = compilation.EmitToImageReference(); return (PEAssemblySymbol)CreateCompilation("", new[] { reference }).GetReferencedAssemblySymbol(reference); } [Fact] public void ConcurrentAccess() { var source = @"class A { B F; D P { get; set; } void M(A a, B b, S s, I i) { } delegate void D(S s); class B { } struct S { } interface I { } } class B { A M<T, U>() where T : A where U : T, I { return null; } event D E; delegate void D(S s); struct S { } interface I { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var builder = new List<Symbol>(); var type = compilation1.GetMember<NamedTypeSymbol>("A"); builder.Add(type); builder.AddRange(type.GetMembers()); type = compilation1.GetMember<NamedTypeSymbol>("B"); builder.Add(type); builder.AddRange(type.GetMembers()); var members = builder.ToImmutableArray(); Assert.True(members.Length > 10); for (int i = 0; i < 10; i++) { var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var tasks = new Task[10]; for (int j = 0; j < tasks.Length; j++) { int startAt = i + j + 1; tasks[j] = Task.Run(() => { MatchAll(matcher, members, startAt); Thread.Sleep(10); }); } Task.WaitAll(tasks); } } private static void MatchAll(CSharpSymbolMatcher matcher, ImmutableArray<Symbol> members, int startAt) { int n = members.Length; for (int i = 0; i < n; i++) { var member = members[(i + startAt) % n]; var other = matcher.MapDefinition((Cci.IDefinition)member.GetCciAdapter()); Assert.NotNull(other); } } [Fact] public void TypeArguments() { const string source = @"class A<T> { class B<U> { static A<V> M<V>(A<U>.B<T> x, A<object>.S y) { return null; } static A<V> M<V>(A<U>.B<T> x, A<V>.S y) { return null; } } struct S { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var members = compilation1.GetMember<NamedTypeSymbol>("A.B").GetMembers("M"); Assert.Equal(2, members.Length); foreach (var member in members) { var other = matcher.MapDefinition((Cci.IMethodDefinition)member.GetCciAdapter()); Assert.NotNull(other); } } [Fact] public void Constraints() { const string source = @"interface I<T> where T : I<T> { } class C { static void M<T>(I<T> o) where T : I<T> { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void CustomModifiers() { var ilSource = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F(int32 modopt(object) *p) { } }"; var metadataRef = CompileIL(ilSource); var source = @"unsafe class B : A { public override object[] F(int* p) { return null; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { metadataRef }); var compilation1 = compilation0.WithSource(source); var member1 = compilation1.GetMember<MethodSymbol>("B.F"); Assert.Equal(1, ((PointerTypeSymbol)member1.Parameters[0].Type).PointedAtTypeWithAnnotations.CustomModifiers.Length); Assert.Equal(1, ((ArrayTypeSymbol)member1.ReturnType).ElementTypeWithAnnotations.CustomModifiers.Length); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var other = (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol(); Assert.NotNull(other); Assert.Equal(1, ((PointerTypeSymbol)other.Parameters[0].Type).PointedAtTypeWithAnnotations.CustomModifiers.Length); Assert.Equal(1, ((ArrayTypeSymbol)other.ReturnType).ElementTypeWithAnnotations.CustomModifiers.Length); } [Fact] public void CustomModifiers_InAttribute_Source() { // The parameter is emitted as // int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) var source0 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(in int x) => throw null; }"; var source1 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(int x) => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); Assert.Same(f0, (MethodSymbol)matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(g0, (MethodSymbol)matcher.MapDefinition(g1.GetCciAdapter()).GetInternalSymbol()); Assert.Null(matcher.MapDefinition(h1.GetCciAdapter())); } [Fact] public void CustomModifiers_InAttribute_Metadata() { // The parameter is emitted as // int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) var source0 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(in int x) => throw null; }"; var source1 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(int x) => throw null; }"; var peAssemblySymbol = CreatePEAssemblySymbol(source0); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll).WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, peAssemblySymbol); var f0 = peAssemblySymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("F"); var g0 = peAssemblySymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("G"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); Assert.Equal(f0, (MethodSymbol)matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); Assert.Equal(g0, (MethodSymbol)matcher.MapDefinition(g1.GetCciAdapter()).GetInternalSymbol()); Assert.Null(matcher.MapDefinition(h1.GetCciAdapter())); } [ConditionalFact(typeof(DesktopOnly))] public void VaryingCompilationReferences() { string libSource = @" public class D { } "; string source = @" public class C { public void F(D a) {} } "; var lib0 = CreateCompilation(libSource, options: TestOptions.DebugDll, assemblyName: "Lib"); var lib1 = CreateCompilation(libSource, options: TestOptions.DebugDll, assemblyName: "Lib"); var compilation0 = CreateCompilation(source, new[] { lib0.ToMetadataReference() }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source).WithReferences(MscorlibRef, lib1.ToMetadataReference()); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var mf1 = matcher.MapDefinition(f1.GetCciAdapter()); Assert.Equal(f0, mf1.GetInternalSymbol()); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void PreviousType_ArrayType() { var source0 = @" class C { static void M() { int x = 0; } class D {} }"; var source1 = @" class C { static void M() { D[] x = null; } class D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreateArrayTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); Assert.NotNull(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_ArrayType() { var source0 = @" class C { static void M() { int x = 0; } }"; var source1 = @" class C { static void M() { D[] x = null; } class D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreateArrayTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_PointerType() { var source0 = @" class C { static void M() { int x = 0; } }"; var source1 = @" class C { static unsafe void M() { D* x = null; } struct D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreatePointerTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_GenericType() { var source0 = @" using System.Collections.Generic; class C { static void M() { int x = 0; } }"; var source1 = @" using System.Collections.Generic; class C { static void M() { List<D> x = null; } class D {} List<D> y; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.y"); var other = matcher.MapReference((Cci.ITypeReference)member.Type.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [Fact] public void HoistedAnonymousTypes() { var source0 = @" using System; class C { static void F() { var x1 = new { A = 1 }; var x2 = new { B = 1 }; var y = new Func<int>(() => x1.A + x2.B); } } "; var source1 = @" using System; class C { static void F() { var x1 = new { A = 1 }; var x2 = new { b = 1 }; var y = new Func<int>(() => x1.A + x2.b); } }"; var peAssemblySymbol0 = CreatePEAssemblySymbol(source0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("B", isKey: false, ignoreCase: false)))].Name); Assert.Equal(2, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass0_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); var x1 = fields[0]; var x2 = fields[1]; Assert.Equal("x1", x1.Name); Assert.Equal("x2", x2.Name); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedX1 = (Cci.IFieldDefinition)matcher.MapDefinition(x1); var mappedX2 = (Cci.IFieldDefinition)matcher.MapDefinition(x2); Assert.Equal("x1", mappedX1.Name); Assert.Null(mappedX2); } [Fact] public void HoistedAnonymousTypes_Complex() { var source0 = @" using System; class C { static void F() { var x1 = new[] { new { A = new { X = 1 } } }; var x2 = new[] { new { A = new { Y = 1 } } }; var y = new Func<int>(() => x1[0].A.X + x2[0].A.Y); } } "; var source1 = @" using System; class C { static void F() { var x1 = new[] { new { A = new { X = 1 } } }; var x2 = new[] { new { A = new { Z = 1 } } }; var y = new Func<int>(() => x1[0].A.X + x2[0].A.Z); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("X", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType2", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("Y", isKey: false, ignoreCase: false)))].Name); Assert.Equal(3, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass0_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); AssertEx.SetEqual(fields.Select(f => f.Name), new[] { "x1", "x2" }); var x1 = fields.Where(f => f.Name == "x1").Single(); var x2 = fields.Where(f => f.Name == "x2").Single(); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedX1 = (Cci.IFieldDefinition)matcher.MapDefinition(x1); var mappedX2 = (Cci.IFieldDefinition)matcher.MapDefinition(x2); Assert.Equal("x1", mappedX1.Name); Assert.Null(mappedX2); } [Fact] public void TupleField_TypeChange() { var source0 = @" class C { public (int a, int b) x; }"; var source1 = @" class C { public (int a, bool b) x; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.x"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleField_NameChange() { var source0 = @" class C { public (int a, int b) x; }"; var source1 = @" class C { public (int a, int c) x; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.x"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleMethod_TypeChange() { var source0 = @" class C { public (int a, int b) X() { return null }; }"; var source1 = @" class C { public (int a, bool b) X() { return null }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleMethod_NameChange() { var source0 = @" class C { public (int a, int b) X() { return null }; }"; var source1 = @" class C { public (int a, int c) X() { return null }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleProperty_TypeChange() { var source0 = @" class C { public (int a, int b) X { get { return null; } }; }"; var source1 = @" class C { public (int a, bool b) X { get { return null; } }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<PropertySymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleProperty_NameChange() { var source0 = @" class C { public (int a, int b) X { get { return null; } }; }"; var source1 = @" class C { public (int a, int c) X { get { return null; } }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<PropertySymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleStructField_TypeChange() { var source0 = @" public struct Vector { public (int x, int y) Coordinates; }"; var source1 = @" public struct Vector { public (int x, int y, int z) Coordinates; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("Vector.Coordinates"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleStructField_NameChange() { var source0 = @" public struct Vector { public (int x, int y) Coordinates; }"; var source1 = @" public struct Vector { public (int x, int z) Coordinates; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("Vector.Coordinates"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleDelegate_TypeChange() { var source0 = @" public class C { public delegate (int, int) F(); }"; var source1 = @" public class C { public delegate (int, bool) F(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceNamedTypeSymbol>("C.F"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Tuple delegate defines a type. We should be able to match old and new types by name. Assert.NotNull(other); } [Fact] public void TupleDelegate_NameChange() { var source0 = @" public class C { public delegate (int, int) F(); }"; var source1 = @" public class C { public delegate (int x, int y) F(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceNamedTypeSymbol>("C.F"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void RefReturn_Method() { var source0 = @" struct C { // non-matching public ref int P() => throw null; public ref readonly int Q() => throw null; public int R() => throw null; // matching public ref readonly int S() => throw null; public ref int T() => throw null; }"; var source1 = @" struct C { // non-matching public ref bool P() => throw null; public ref int Q() => throw null; public ref int R() => throw null; // matching public ref readonly int S() => throw null; public ref int T() => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var s0 = compilation0.GetMember<MethodSymbol>("C.S"); var t0 = compilation0.GetMember<MethodSymbol>("C.T"); var p1 = compilation1.GetMember<MethodSymbol>("C.P"); var q1 = compilation1.GetMember<MethodSymbol>("C.Q"); var r1 = compilation1.GetMember<MethodSymbol>("C.R"); var s1 = compilation1.GetMember<MethodSymbol>("C.S"); var t1 = compilation1.GetMember<MethodSymbol>("C.T"); Assert.Null(matcher.MapDefinition(p1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(q1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(r1.GetCciAdapter())); Assert.Same(s0, matcher.MapDefinition(s1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(t0, matcher.MapDefinition(t1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void RefReturn_Property() { var source0 = @" struct C { // non-matching public ref int P => throw null; public ref readonly int Q => throw null; public int R => throw null; // matching public ref readonly int S => throw null; public ref int T => throw null; }"; var source1 = @" struct C { // non-matching public ref bool P => throw null; public ref int Q => throw null; public ref int R => throw null; // matching public ref readonly int S => throw null; public ref int T => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var s0 = compilation0.GetMember<PropertySymbol>("C.S"); var t0 = compilation0.GetMember<PropertySymbol>("C.T"); var p1 = compilation1.GetMember<PropertySymbol>("C.P"); var q1 = compilation1.GetMember<PropertySymbol>("C.Q"); var r1 = compilation1.GetMember<PropertySymbol>("C.R"); var s1 = compilation1.GetMember<PropertySymbol>("C.S"); var t1 = compilation1.GetMember<PropertySymbol>("C.T"); Assert.Null(matcher.MapDefinition(p1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(q1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(r1.GetCciAdapter())); Assert.Same(s0, matcher.MapDefinition(s1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(t0, matcher.MapDefinition(t1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Property_CompilationVsPE() { var source = @" using System; interface I<T, S> { int this[int index] { set; } } class C : I<int, bool> { int _current; int I<int, bool>.this[int anotherIndex] { set { _current = anotherIndex + value; } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var compilation1 = CreateCompilation(source, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var property = c.GetMember<PropertySymbol>("I<System.Int32,System.Boolean>.this[]"); var parameters = property.GetParameters().ToArray(); Assert.Equal(1, parameters.Length); Assert.Equal("anotherIndex", parameters[0].Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var matcher = new CSharpSymbolMatcher(null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedProperty = (Cci.IPropertyDefinition)matcher.MapDefinition(property.GetCciAdapter()); Assert.Equal("I<System.Int32,System.Boolean>.Item", ((PropertySymbol)mappedProperty.GetInternalSymbol()).MetadataName); } [Fact] public void Method_ParameterNullableChange() { var source0 = @" using System.Collections.Generic; class C { string c; ref string M(string? s, (string a, dynamic? b) tuple, List<string?> list) => ref c; }"; var source1 = @" using System.Collections.Generic; class C { string c; ref string? M(string s, (string? a, dynamic b) tuple, List<string> list) => ref c; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Method_ParameterRename() { var source0 = @" using System.Collections.Generic; class C { string M(string s) => s.ToString(); }"; var source1 = @" using System.Collections.Generic; class C { string M(string m) => m.ToString(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Method_ParameterRenameToDiscard() { var source0 = @" using System.Collections.Generic; class C { string M(string s) => s.ToString(); }"; var source1 = @" using System.Collections.Generic; class C { string M(string _) => ""Hello""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Field_NullableChange() { var source0 = @" class C { string S; }"; var source1 = @" class C { string? S; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.S"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void AnonymousTypesWithNullables() { var source0 = @" using System; class C { static T id<T>(T t) => t; static T F<T>(Func<T> f) => f(); static void M(string? x) { var y1 = new { A = id(x) }; var y2 = F(() => new { B = id(x) }); var z = new Func<string>(() => y1.A + y2.B); } }"; var source1 = @" using System; class C { static T id<T>(T t) => t; static T F<T>(Func<T> f) => f(); static void M(string? x) { if (x is null) throw new Exception(); var y1 = new { A = id(x) }; var y2 = F(() => new { B = id(x) }); var z = new Func<string>(() => y1.A + y2.B); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("B", isKey: false, ignoreCase: false)))].Name); Assert.Equal(2, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass2_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); AssertEx.SetEqual(fields.Select(f => f.Name), new[] { "x", "y1", "y2" }); var y1 = fields.Where(f => f.Name == "y1").Single(); var y2 = fields.Where(f => f.Name == "y2").Single(); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedY1 = (Cci.IFieldDefinition)matcher.MapDefinition(y1); var mappedY2 = (Cci.IFieldDefinition)matcher.MapDefinition(y2); Assert.Equal("y1", mappedY1.Name); Assert.Equal("y2", mappedY2.Name); } [Fact] public void InterfaceMembers() { var source = @" using System; interface I { static int X = 1; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var x0 = compilation0.GetMember<FieldSymbol>("I.X"); var y0 = compilation0.GetMember<EventSymbol>("I.Y"); var m0 = compilation0.GetMember<MethodSymbol>("I.M"); var n0 = compilation0.GetMember<MethodSymbol>("I.N"); var p0 = compilation0.GetMember<PropertySymbol>("I.P"); var q0 = compilation0.GetMember<PropertySymbol>("I.Q"); var e0 = compilation0.GetMember<EventSymbol>("I.E"); var f0 = compilation0.GetMember<EventSymbol>("I.F"); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); Assert.Same(x0, matcher.MapDefinition(x1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(y0, matcher.MapDefinition(y1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(m0, matcher.MapDefinition(m1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(n0, matcher.MapDefinition(n1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(p0, matcher.MapDefinition(p1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(q0, matcher.MapDefinition(q1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(e0, matcher.MapDefinition(e1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(f0, matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void FunctionPointerMembersTranslated() { var source = @" unsafe class C { delegate*<void> f1; delegate*<C, C, C> f2; delegate*<ref C> f3; delegate*<ref readonly C> f4; delegate*<ref C, void> f5; delegate*<in C, void> f6; delegate*<out C, void> f7; } "; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); for (int i = 1; i <= 7; i++) { var f_0 = compilation0.GetMember<FieldSymbol>($"C.f{i}"); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f{i}"); Assert.Same(f_0, matcher.MapDefinition(f_1.GetCciAdapter()).GetInternalSymbol()); } } [Theory] [InlineData("C", "void")] [InlineData("C", "object")] [InlineData("C", "ref C")] [InlineData("C", "ref readonly C")] [InlineData("ref C", "ref readonly C")] public void FunctionPointerMembers_ReturnMismatch(string return1, string return2) { var source1 = $@" unsafe class C {{ delegate*<C, {return1}> f1; }}"; var source2 = $@" unsafe class C {{ delegate*<C, {return2}> f1; }}"; var compilation0 = CreateCompilation(source1, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source2); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f1"); Assert.Null(matcher.MapDefinition(f_1.GetCciAdapter())); } [Theory] [InlineData("C", "object")] [InlineData("C", "ref C")] [InlineData("C", "out C")] [InlineData("C", "in C")] [InlineData("ref C", "out C")] [InlineData("ref C", "in C")] [InlineData("out C", "in C")] [InlineData("C, C", "C")] public void FunctionPointerMembers_ParamMismatch(string param1, string param2) { var source1 = $@" unsafe class C {{ delegate*<{param1}, C, void>* f1; }}"; var source2 = $@" unsafe class C {{ delegate*<{param2}, C, void>* f1; }}"; verify(source1, source2); source1 = $@" unsafe class C {{ delegate*<C, {param1}, void> f1; }}"; source2 = $@" unsafe class C {{ delegate*<C, {param2}, void> f1; }}"; verify(source1, source2); static void verify(string source1, string source2) { var compilation0 = CreateCompilation(source1, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source2); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f1"); Assert.Null(matcher.MapDefinition(f_1.GetCciAdapter())); } } [Fact] public void Record_ImplementSynthesizedMember_ToString() { var source0 = @" public record R { }"; var source1 = @" public record R { public override string ToString() => ""R""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceOrdinaryMethodSymbol>("R.ToString"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Record_ImplementSynthesizedMember_PrintMembers() { var source0 = @" public record R { }"; var source1 = @" public record R { protected virtual bool PrintMembers(System.Text.StringBuilder builder) => true; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SynthesizedRecordPrintMembers>("R.PrintMembers"); var member1 = compilation1.GetMember<SourceOrdinaryMethodSymbol>("R.PrintMembers"); Assert.Equal(member0, (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_RemoveSynthesizedMember_PrintMembers() { var source0 = @" public record R { protected virtual bool PrintMembers(System.Text.StringBuilder builder) => true; }"; var source1 = @" public record R { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SourceOrdinaryMethodSymbol>("R.PrintMembers"); var member1 = compilation1.GetMember<SynthesizedRecordPrintMembers>("R.PrintMembers"); Assert.Equal(member0, (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_ImplementSynthesizedMember_Property() { var source0 = @" public record R(int X);"; var source1 = @" public record R(int X) { public int X { get; init; } = this.X; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SynthesizedRecordPropertySymbol>("R.X"); var member1 = compilation1.GetMember<SourcePropertySymbol>("R.X"); Assert.Equal(member0, (PropertySymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_ImplementSynthesizedMember_Constructor() { var source0 = @" public record R(int X);"; var source1 = @" public record R { public R(int X) { this.X = X; } public int X { get; init; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var members = compilation1.GetMembers("R..ctor"); // There are two, one is the copy constructor Assert.Equal(2, members.Length); var member = (SourceConstructorSymbol)members.Single(m => m.ToString() == "R.R(int)"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } } }
// 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. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class SymbolMatcherTests : EditAndContinueTestBase { private static PEAssemblySymbol CreatePEAssemblySymbol(string source) { var compilation = CreateCompilation(source, options: TestOptions.DebugDll); var reference = compilation.EmitToImageReference(); return (PEAssemblySymbol)CreateCompilation("", new[] { reference }).GetReferencedAssemblySymbol(reference); } [Fact] public void ConcurrentAccess() { var source = @"class A { B F; D P { get; set; } void M(A a, B b, S s, I i) { } delegate void D(S s); class B { } struct S { } interface I { } } class B { A M<T, U>() where T : A where U : T, I { return null; } event D E; delegate void D(S s); struct S { } interface I { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var builder = new List<Symbol>(); var type = compilation1.GetMember<NamedTypeSymbol>("A"); builder.Add(type); builder.AddRange(type.GetMembers()); type = compilation1.GetMember<NamedTypeSymbol>("B"); builder.Add(type); builder.AddRange(type.GetMembers()); var members = builder.ToImmutableArray(); Assert.True(members.Length > 10); for (int i = 0; i < 10; i++) { var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var tasks = new Task[10]; for (int j = 0; j < tasks.Length; j++) { int startAt = i + j + 1; tasks[j] = Task.Run(() => { MatchAll(matcher, members, startAt); Thread.Sleep(10); }); } Task.WaitAll(tasks); } } private static void MatchAll(CSharpSymbolMatcher matcher, ImmutableArray<Symbol> members, int startAt) { int n = members.Length; for (int i = 0; i < n; i++) { var member = members[(i + startAt) % n]; var other = matcher.MapDefinition((Cci.IDefinition)member.GetCciAdapter()); Assert.NotNull(other); } } [Fact] public void TypeArguments() { const string source = @"class A<T> { class B<U> { static A<V> M<V>(A<U>.B<T> x, A<object>.S y) { return null; } static A<V> M<V>(A<U>.B<T> x, A<V>.S y) { return null; } } struct S { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var members = compilation1.GetMember<NamedTypeSymbol>("A.B").GetMembers("M"); Assert.Equal(2, members.Length); foreach (var member in members) { var other = matcher.MapDefinition((Cci.IMethodDefinition)member.GetCciAdapter()); Assert.NotNull(other); } } [Fact] public void Constraints() { const string source = @"interface I<T> where T : I<T> { } class C { static void M<T>(I<T> o) where T : I<T> { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void CustomModifiers() { var ilSource = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F(int32 modopt(object) *p) { } }"; var metadataRef = CompileIL(ilSource); var source = @"unsafe class B : A { public override object[] F(int* p) { return null; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { metadataRef }); var compilation1 = compilation0.WithSource(source); var member1 = compilation1.GetMember<MethodSymbol>("B.F"); Assert.Equal(1, ((PointerTypeSymbol)member1.Parameters[0].Type).PointedAtTypeWithAnnotations.CustomModifiers.Length); Assert.Equal(1, ((ArrayTypeSymbol)member1.ReturnType).ElementTypeWithAnnotations.CustomModifiers.Length); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var other = (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol(); Assert.NotNull(other); Assert.Equal(1, ((PointerTypeSymbol)other.Parameters[0].Type).PointedAtTypeWithAnnotations.CustomModifiers.Length); Assert.Equal(1, ((ArrayTypeSymbol)other.ReturnType).ElementTypeWithAnnotations.CustomModifiers.Length); } [Fact] public void CustomModifiers_InAttribute_Source() { // The parameter is emitted as // int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) var source0 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(in int x) => throw null; }"; var source1 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(int x) => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); Assert.Same(f0, (MethodSymbol)matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(g0, (MethodSymbol)matcher.MapDefinition(g1.GetCciAdapter()).GetInternalSymbol()); Assert.Null(matcher.MapDefinition(h1.GetCciAdapter())); } [Fact] public void CustomModifiers_InAttribute_Metadata() { // The parameter is emitted as // int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) var source0 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(in int x) => throw null; }"; var source1 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(int x) => throw null; }"; var peAssemblySymbol = CreatePEAssemblySymbol(source0); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll).WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, peAssemblySymbol); var f0 = peAssemblySymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("F"); var g0 = peAssemblySymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("G"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); Assert.Equal(f0, (MethodSymbol)matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); Assert.Equal(g0, (MethodSymbol)matcher.MapDefinition(g1.GetCciAdapter()).GetInternalSymbol()); Assert.Null(matcher.MapDefinition(h1.GetCciAdapter())); } [ConditionalFact(typeof(DesktopOnly))] public void VaryingCompilationReferences() { string libSource = @" public class D { } "; string source = @" public class C { public void F(D a) {} } "; var lib0 = CreateCompilation(libSource, options: TestOptions.DebugDll, assemblyName: "Lib"); var lib1 = CreateCompilation(libSource, options: TestOptions.DebugDll, assemblyName: "Lib"); var compilation0 = CreateCompilation(source, new[] { lib0.ToMetadataReference() }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source).WithReferences(MscorlibRef, lib1.ToMetadataReference()); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var mf1 = matcher.MapDefinition(f1.GetCciAdapter()); Assert.Equal(f0, mf1.GetInternalSymbol()); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void PreviousType_ArrayType() { var source0 = @" class C { static void M() { int x = 0; } class D {} }"; var source1 = @" class C { static void M() { D[] x = null; } class D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreateArrayTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); Assert.NotNull(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_ArrayType() { var source0 = @" class C { static void M() { int x = 0; } }"; var source1 = @" class C { static void M() { D[] x = null; } class D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreateArrayTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_PointerType() { var source0 = @" class C { static void M() { int x = 0; } }"; var source1 = @" class C { static unsafe void M() { D* x = null; } struct D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreatePointerTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_GenericType() { var source0 = @" using System.Collections.Generic; class C { static void M() { int x = 0; } }"; var source1 = @" using System.Collections.Generic; class C { static void M() { List<D> x = null; } class D {} List<D> y; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.y"); var other = matcher.MapReference((Cci.ITypeReference)member.Type.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [Fact] public void HoistedAnonymousTypes() { var source0 = @" using System; class C { static void F() { var x1 = new { A = 1 }; var x2 = new { B = 1 }; var y = new Func<int>(() => x1.A + x2.B); } } "; var source1 = @" using System; class C { static void F() { var x1 = new { A = 1 }; var x2 = new { b = 1 }; var y = new Func<int>(() => x1.A + x2.b); } }"; var peAssemblySymbol0 = CreatePEAssemblySymbol(source0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("B", isKey: false, ignoreCase: false)))].Name); Assert.Equal(2, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass0_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); var x1 = fields[0]; var x2 = fields[1]; Assert.Equal("x1", x1.Name); Assert.Equal("x2", x2.Name); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedX1 = (Cci.IFieldDefinition)matcher.MapDefinition(x1); var mappedX2 = (Cci.IFieldDefinition)matcher.MapDefinition(x2); Assert.Equal("x1", mappedX1.Name); Assert.Null(mappedX2); } [Fact] public void HoistedAnonymousTypes_Complex() { var source0 = @" using System; class C { static void F() { var x1 = new[] { new { A = new { X = 1 } } }; var x2 = new[] { new { A = new { Y = 1 } } }; var y = new Func<int>(() => x1[0].A.X + x2[0].A.Y); } } "; var source1 = @" using System; class C { static void F() { var x1 = new[] { new { A = new { X = 1 } } }; var x2 = new[] { new { A = new { Z = 1 } } }; var y = new Func<int>(() => x1[0].A.X + x2[0].A.Z); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("X", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType2", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("Y", isKey: false, ignoreCase: false)))].Name); Assert.Equal(3, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass0_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); AssertEx.SetEqual(fields.Select(f => f.Name), new[] { "x1", "x2" }); var x1 = fields.Where(f => f.Name == "x1").Single(); var x2 = fields.Where(f => f.Name == "x2").Single(); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedX1 = (Cci.IFieldDefinition)matcher.MapDefinition(x1); var mappedX2 = (Cci.IFieldDefinition)matcher.MapDefinition(x2); Assert.Equal("x1", mappedX1.Name); Assert.Null(mappedX2); } [Fact] public void TupleField_TypeChange() { var source0 = @" class C { public (int a, int b) x; }"; var source1 = @" class C { public (int a, bool b) x; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.x"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleField_NameChange() { var source0 = @" class C { public (int a, int b) x; }"; var source1 = @" class C { public (int a, int c) x; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.x"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleMethod_TypeChange() { var source0 = @" class C { public (int a, int b) X() { return null }; }"; var source1 = @" class C { public (int a, bool b) X() { return null }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleMethod_NameChange() { var source0 = @" class C { public (int a, int b) X() { return null }; }"; var source1 = @" class C { public (int a, int c) X() { return null }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleProperty_TypeChange() { var source0 = @" class C { public (int a, int b) X { get { return null; } }; }"; var source1 = @" class C { public (int a, bool b) X { get { return null; } }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<PropertySymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleProperty_NameChange() { var source0 = @" class C { public (int a, int b) X { get { return null; } }; }"; var source1 = @" class C { public (int a, int c) X { get { return null; } }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<PropertySymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleStructField_TypeChange() { var source0 = @" public struct Vector { public (int x, int y) Coordinates; }"; var source1 = @" public struct Vector { public (int x, int y, int z) Coordinates; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("Vector.Coordinates"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleStructField_NameChange() { var source0 = @" public struct Vector { public (int x, int y) Coordinates; }"; var source1 = @" public struct Vector { public (int x, int z) Coordinates; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("Vector.Coordinates"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleDelegate_TypeChange() { var source0 = @" public class C { public delegate (int, int) F(); }"; var source1 = @" public class C { public delegate (int, bool) F(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceNamedTypeSymbol>("C.F"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Tuple delegate defines a type. We should be able to match old and new types by name. Assert.NotNull(other); } [Fact] public void TupleDelegate_NameChange() { var source0 = @" public class C { public delegate (int, int) F(); }"; var source1 = @" public class C { public delegate (int x, int y) F(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceNamedTypeSymbol>("C.F"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void RefReturn_Method() { var source0 = @" struct C { // non-matching public ref int P() => throw null; public ref readonly int Q() => throw null; public int R() => throw null; // matching public ref readonly int S() => throw null; public ref int T() => throw null; }"; var source1 = @" struct C { // non-matching public ref bool P() => throw null; public ref int Q() => throw null; public ref int R() => throw null; // matching public ref readonly int S() => throw null; public ref int T() => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var s0 = compilation0.GetMember<MethodSymbol>("C.S"); var t0 = compilation0.GetMember<MethodSymbol>("C.T"); var p1 = compilation1.GetMember<MethodSymbol>("C.P"); var q1 = compilation1.GetMember<MethodSymbol>("C.Q"); var r1 = compilation1.GetMember<MethodSymbol>("C.R"); var s1 = compilation1.GetMember<MethodSymbol>("C.S"); var t1 = compilation1.GetMember<MethodSymbol>("C.T"); Assert.Null(matcher.MapDefinition(p1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(q1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(r1.GetCciAdapter())); Assert.Same(s0, matcher.MapDefinition(s1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(t0, matcher.MapDefinition(t1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void RefReturn_Property() { var source0 = @" struct C { // non-matching public ref int P => throw null; public ref readonly int Q => throw null; public int R => throw null; // matching public ref readonly int S => throw null; public ref int T => throw null; }"; var source1 = @" struct C { // non-matching public ref bool P => throw null; public ref int Q => throw null; public ref int R => throw null; // matching public ref readonly int S => throw null; public ref int T => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var s0 = compilation0.GetMember<PropertySymbol>("C.S"); var t0 = compilation0.GetMember<PropertySymbol>("C.T"); var p1 = compilation1.GetMember<PropertySymbol>("C.P"); var q1 = compilation1.GetMember<PropertySymbol>("C.Q"); var r1 = compilation1.GetMember<PropertySymbol>("C.R"); var s1 = compilation1.GetMember<PropertySymbol>("C.S"); var t1 = compilation1.GetMember<PropertySymbol>("C.T"); Assert.Null(matcher.MapDefinition(p1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(q1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(r1.GetCciAdapter())); Assert.Same(s0, matcher.MapDefinition(s1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(t0, matcher.MapDefinition(t1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Property_CompilationVsPE() { var source = @" using System; interface I<T, S> { int this[int index] { set; } } class C : I<int, bool> { int _current; int I<int, bool>.this[int anotherIndex] { set { _current = anotherIndex + value; } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var compilation1 = CreateCompilation(source, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var property = c.GetMember<PropertySymbol>("I<System.Int32,System.Boolean>.this[]"); var parameters = property.GetParameters().ToArray(); Assert.Equal(1, parameters.Length); Assert.Equal("anotherIndex", parameters[0].Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var matcher = new CSharpSymbolMatcher(null, null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedProperty = (Cci.IPropertyDefinition)matcher.MapDefinition(property.GetCciAdapter()); Assert.Equal("I<System.Int32,System.Boolean>.Item", ((PropertySymbol)mappedProperty.GetInternalSymbol()).MetadataName); } [Fact] public void Method_ParameterNullableChange() { var source0 = @" using System.Collections.Generic; class C { string c; ref string M(string? s, (string a, dynamic? b) tuple, List<string?> list) => ref c; }"; var source1 = @" using System.Collections.Generic; class C { string c; ref string? M(string s, (string? a, dynamic b) tuple, List<string> list) => ref c; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Method_ParameterRename() { var source0 = @" using System.Collections.Generic; class C { string M(string s) => s.ToString(); }"; var source1 = @" using System.Collections.Generic; class C { string M(string m) => m.ToString(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Method_ParameterRenameToDiscard() { var source0 = @" using System.Collections.Generic; class C { string M(string s) => s.ToString(); }"; var source1 = @" using System.Collections.Generic; class C { string M(string _) => ""Hello""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Field_NullableChange() { var source0 = @" class C { string S; }"; var source1 = @" class C { string? S; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.S"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void AnonymousTypesWithNullables() { var source0 = @" using System; class C { static T id<T>(T t) => t; static T F<T>(Func<T> f) => f(); static void M(string? x) { var y1 = new { A = id(x) }; var y2 = F(() => new { B = id(x) }); var z = new Func<string>(() => y1.A + y2.B); } }"; var source1 = @" using System; class C { static T id<T>(T t) => t; static T F<T>(Func<T> f) => f(); static void M(string? x) { if (x is null) throw new Exception(); var y1 = new { A = id(x) }; var y2 = F(() => new { B = id(x) }); var z = new Func<string>(() => y1.A + y2.B); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("B", isKey: false, ignoreCase: false)))].Name); Assert.Equal(2, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass2_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); AssertEx.SetEqual(fields.Select(f => f.Name), new[] { "x", "y1", "y2" }); var y1 = fields.Where(f => f.Name == "y1").Single(); var y2 = fields.Where(f => f.Name == "y2").Single(); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedY1 = (Cci.IFieldDefinition)matcher.MapDefinition(y1); var mappedY2 = (Cci.IFieldDefinition)matcher.MapDefinition(y2); Assert.Equal("y1", mappedY1.Name); Assert.Equal("y2", mappedY2.Name); } [Fact] public void InterfaceMembers() { var source = @" using System; interface I { static int X = 1; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var x0 = compilation0.GetMember<FieldSymbol>("I.X"); var y0 = compilation0.GetMember<EventSymbol>("I.Y"); var m0 = compilation0.GetMember<MethodSymbol>("I.M"); var n0 = compilation0.GetMember<MethodSymbol>("I.N"); var p0 = compilation0.GetMember<PropertySymbol>("I.P"); var q0 = compilation0.GetMember<PropertySymbol>("I.Q"); var e0 = compilation0.GetMember<EventSymbol>("I.E"); var f0 = compilation0.GetMember<EventSymbol>("I.F"); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); Assert.Same(x0, matcher.MapDefinition(x1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(y0, matcher.MapDefinition(y1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(m0, matcher.MapDefinition(m1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(n0, matcher.MapDefinition(n1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(p0, matcher.MapDefinition(p1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(q0, matcher.MapDefinition(q1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(e0, matcher.MapDefinition(e1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(f0, matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void FunctionPointerMembersTranslated() { var source = @" unsafe class C { delegate*<void> f1; delegate*<C, C, C> f2; delegate*<ref C> f3; delegate*<ref readonly C> f4; delegate*<ref C, void> f5; delegate*<in C, void> f6; delegate*<out C, void> f7; } "; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); for (int i = 1; i <= 7; i++) { var f_0 = compilation0.GetMember<FieldSymbol>($"C.f{i}"); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f{i}"); Assert.Same(f_0, matcher.MapDefinition(f_1.GetCciAdapter()).GetInternalSymbol()); } } [Theory] [InlineData("C", "void")] [InlineData("C", "object")] [InlineData("C", "ref C")] [InlineData("C", "ref readonly C")] [InlineData("ref C", "ref readonly C")] public void FunctionPointerMembers_ReturnMismatch(string return1, string return2) { var source1 = $@" unsafe class C {{ delegate*<C, {return1}> f1; }}"; var source2 = $@" unsafe class C {{ delegate*<C, {return2}> f1; }}"; var compilation0 = CreateCompilation(source1, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source2); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f1"); Assert.Null(matcher.MapDefinition(f_1.GetCciAdapter())); } [Theory] [InlineData("C", "object")] [InlineData("C", "ref C")] [InlineData("C", "out C")] [InlineData("C", "in C")] [InlineData("ref C", "out C")] [InlineData("ref C", "in C")] [InlineData("out C", "in C")] [InlineData("C, C", "C")] public void FunctionPointerMembers_ParamMismatch(string param1, string param2) { var source1 = $@" unsafe class C {{ delegate*<{param1}, C, void>* f1; }}"; var source2 = $@" unsafe class C {{ delegate*<{param2}, C, void>* f1; }}"; verify(source1, source2); source1 = $@" unsafe class C {{ delegate*<C, {param1}, void> f1; }}"; source2 = $@" unsafe class C {{ delegate*<C, {param2}, void> f1; }}"; verify(source1, source2); static void verify(string source1, string source2) { var compilation0 = CreateCompilation(source1, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source2); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f1"); Assert.Null(matcher.MapDefinition(f_1.GetCciAdapter())); } } [Fact] public void Record_ImplementSynthesizedMember_ToString() { var source0 = @" public record R { }"; var source1 = @" public record R { public override string ToString() => ""R""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceOrdinaryMethodSymbol>("R.ToString"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Record_ImplementSynthesizedMember_PrintMembers() { var source0 = @" public record R { }"; var source1 = @" public record R { protected virtual bool PrintMembers(System.Text.StringBuilder builder) => true; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SynthesizedRecordPrintMembers>("R.PrintMembers"); var member1 = compilation1.GetMember<SourceOrdinaryMethodSymbol>("R.PrintMembers"); Assert.Equal(member0, (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_RemoveSynthesizedMember_PrintMembers() { var source0 = @" public record R { protected virtual bool PrintMembers(System.Text.StringBuilder builder) => true; }"; var source1 = @" public record R { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SourceOrdinaryMethodSymbol>("R.PrintMembers"); var member1 = compilation1.GetMember<SynthesizedRecordPrintMembers>("R.PrintMembers"); Assert.Equal(member0, (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_ImplementSynthesizedMember_Property() { var source0 = @" public record R(int X);"; var source1 = @" public record R(int X) { public int X { get; init; } = this.X; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SynthesizedRecordPropertySymbol>("R.X"); var member1 = compilation1.GetMember<SourcePropertySymbol>("R.X"); Assert.Equal(member0, (PropertySymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_ImplementSynthesizedMember_Constructor() { var source0 = @" public record R(int X);"; var source1 = @" public record R { public R(int X) { this.X = X; } public int X { get; init; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var members = compilation1.GetMembers("R..ctor"); // There are two, one is the copy constructor Assert.Equal(2, members.Length); var member = (SourceConstructorSymbol)members.Single(m => m.ToString() == "R.R(int)"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void SynthesizedDelegates() { var source0 = @" using System; class C { static void F() { var _1 = (int a, ref int b) => a; var _2 = (in int a, int b) => { }; var _3 = (int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, int _17, int _18, int _19, int _20, int _21, int _22, int _23, int _24, int _25, int _26, int _27, int _28, int _29, int _30, int _31, int _32, ref int _33) => { }; } } "; var source1 = @" using System; class C { static void F() { var _1 = (int c, ref int d) => c; var _2 = (in int c, int d) => { d.ToString(); }; var _3 = (int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, int _17, int _18, int _19, int _20, int _21, int _22, int _23, int _24, int _25, int _26, int _27, int _28, int _29, int _30, int _31, int _32, ref int _33) => { _1.ToString(); }; } }"; var peAssemblySymbol0 = CreatePEAssemblySymbol(source0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var synthesizedDelegates0 = PEDeltaAssemblyBuilder.GetSynthesizedDelegateMapFromMetadata(reader0, decoder0); Assert.Contains(new SynthesizedDelegateKey("<>F{00000004}`3"), synthesizedDelegates0); Assert.Contains(new SynthesizedDelegateKey("<>A{00000003}`2"), synthesizedDelegates0); Assert.Contains(new SynthesizedDelegateKey("<>A{00000000,00000001}`33"), synthesizedDelegates0); Assert.Equal(3, synthesizedDelegates0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); var field1 = fields[1]; var field2 = fields[2]; var field3 = fields[3]; Assert.Equal("<>9__0_0", field1.Name); Assert.Equal("<>9__0_1", field2.Name); Assert.Equal("<>9__0_2", field3.Name); var matcher = new CSharpSymbolMatcher(null, synthesizedDelegates0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedField1 = (Cci.IFieldDefinition)matcher.MapDefinition(field1); var mappedField2 = (Cci.IFieldDefinition)matcher.MapDefinition(field2); var mappedField3 = (Cci.IFieldDefinition)matcher.MapDefinition(field3); Assert.Equal("<>9__0_0", mappedField1.Name); Assert.Equal("<>9__0_1", mappedField2.Name); Assert.Equal("<>9__0_2", mappedField3.Name); } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Test/Semantic/Semantics/DelegateTypeTests.cs
// 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 System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTypeTests : CSharpTestBase { private const string s_utils = @"using System; using System.Linq; static class Utils { internal static string GetDelegateMethodName(this Delegate d) { var method = d.Method; return Concat(GetTypeName(method.DeclaringType), method.Name); } internal static string GetDelegateTypeName(this Delegate d) { return d.GetType().GetTypeName(); } internal static string GetTypeName(this Type type) { if (type.IsArray) { return GetTypeName(type.GetElementType()) + ""[]""; } string typeName = type.Name; int index = typeName.LastIndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } typeName = Concat(type.Namespace, typeName); if (!type.IsGenericType) { return typeName; } return $""{typeName}<{string.Join("", "", type.GetGenericArguments().Select(GetTypeName))}>""; } private static string Concat(string container, string name) { return string.IsNullOrEmpty(container) ? name : container + ""."" + name; } }"; private static readonly string s_expressionOfTDelegateTypeName = ExecutionConditionUtil.IsDesktop ? "System.Linq.Expressions.Expression`1" : "System.Linq.Expressions.Expression0`1"; [Fact] public void LanguageVersion() { var source = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 13), // (9,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 48)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversions_01() { var source = @"using System; class Program { static void Main() { object o = Main; ICloneable c = Main; Delegate d = Main; MulticastDelegate m = Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 20), // (7,24): error CS0428: Cannot convert method group 'Main' to non-delegate type 'ICloneable'. Did you intend to invoke the method? // ICloneable c = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // Delegate d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(8, 22), // (9,31): error CS0428: Cannot convert method group 'Main' to non-delegate type 'MulticastDelegate'. Did you intend to invoke the method? // MulticastDelegate m = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)Main; var c = (ICloneable)Main; var d = (Delegate)Main; var m = (MulticastDelegate)Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,17): error CS0030: Cannot convert type 'method' to 'object' // var o = (object)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)Main").WithArguments("method", "object").WithLocation(6, 17), // (7,17): error CS0030: Cannot convert type 'method' to 'ICloneable' // var c = (ICloneable)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(ICloneable)Main").WithArguments("method", "System.ICloneable").WithLocation(7, 17), // (8,17): error CS0030: Cannot convert type 'method' to 'Delegate' // var d = (Delegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Delegate)Main").WithArguments("method", "System.Delegate").WithLocation(8, 17), // (9,17): error CS0030: Cannot convert type 'method' to 'MulticastDelegate' // var m = (MulticastDelegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(MulticastDelegate)Main").WithArguments("method", "System.MulticastDelegate").WithLocation(9, 17)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_03() { var source = @"class Program { static void Main() { System.Linq.Expressions.Expression e = F; e = (System.Linq.Expressions.Expression)F; } static int F() => 1; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0030: Cannot convert type 'method' to 'Expression' // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.Expression)F").WithArguments("method", "System.Linq.Expressions.Expression").WithLocation(6, 13)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.Expression)F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(6, 13)); } [Fact] public void MethodGroupConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void F() { } static void F(object o) { } static void Main() { object o = F; ICloneable c = F; Delegate d = F; MulticastDelegate m = F; Expression e = F; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,20): error CS8917: The delegate type could not be inferred. // object o = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(9, 20), // (10,24): error CS8917: The delegate type could not be inferred. // ICloneable c = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(10, 24), // (11,22): error CS8917: The delegate type could not be inferred. // Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(11, 22), // (12,31): error CS8917: The delegate type could not be inferred. // MulticastDelegate m = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(12, 31), // (13,24): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(13, 24)); } [Fact] public void LambdaConversions_01() { var source = @"using System; class Program { static void Main() { object o = () => { }; ICloneable c = () => { }; Delegate d = () => { }; MulticastDelegate m = () => { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // ICloneable c = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)(() => { }); var c = (ICloneable)(() => { }); var d = (Delegate)(() => { }); var m = (MulticastDelegate)(() => { }); Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,26): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // var o = (object)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 26), // (7,30): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // var c = (ICloneable)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 30), // (8,28): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var d = (Delegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 28), // (9,37): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // var m = (MulticastDelegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_03() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression e = () => 1; Report(e); e = (Expression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(7, 24), // (9,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 26)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Delegate d = x => x; object o = (object)(x => x); Expression e = x => x; e = (Expression)(x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 22), // (8,29): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "object").WithLocation(8, 29), // (9,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 24), // (10,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(10, 26)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,22): error CS8917: The delegate type could not be inferred. // Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(7, 22), // (8,29): error CS8917: The delegate type could not be inferred. // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 29), // (9,24): error CS8917: The delegate type could not be inferred. // Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 24), // (10,26): error CS8917: The delegate type could not be inferred. // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(10, 26)); } [Fact] public void LambdaConversions_05() { var source = @"using System; class Program { static void Main() { System.Delegate d = () => Main; System.Linq.Expressions.Expression e = () => Main; Report(d); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Action] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Action]] "); } [Fact] public void AnonymousMethod_01() { var source = @"using System; class Program { static void Main() { object o = delegate () { }; ICloneable c = delegate () { }; Delegate d = delegate () { }; MulticastDelegate m = delegate () { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert anonymous method to type 'object' because it is not a delegate type // object o = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert anonymous method to type 'ICloneable' because it is not a delegate type // ICloneable c = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // Delegate d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert anonymous method to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void DynamicConversion() { var source = @"using System; class Program { static void Main() { dynamic d; d = Main; d = () => 1; } static void Report(dynamic d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'dynamic'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "dynamic").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert lambda expression to type 'dynamic' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "dynamic").WithLocation(8, 13)); } private static IEnumerable<object?[]> GetMethodGroupData(Func<string, string, DiagnosticDescription[]> getExpectedDiagnostics) { yield return getData("static int F() => 0;", "Program.F", "F", "System.Func<System.Int32>"); yield return getData("static int F() => 0;", "F", "F", "System.Func<System.Int32>"); yield return getData("int F() => 0;", "(new Program()).F", "F", "System.Func<System.Int32>"); yield return getData("static T F<T>() => default;", "Program.F<int>", "F", "System.Func<System.Int32>"); yield return getData("static void F<T>() where T : class { }", "F<object>", "F", "System.Action"); yield return getData("static void F<T>() where T : struct { }", "F<int>", "F", "System.Action"); yield return getData("T F<T>() => default;", "(new Program()).F<int>", "F", "System.Func<System.Int32>"); yield return getData("T F<T>() => default;", "(new Program()).F", "F", null); yield return getData("void F<T>(T t) { }", "(new Program()).F<string>", "F", "System.Action<System.String>"); yield return getData("void F<T>(T t) { }", "(new Program()).F", "F", null); yield return getData("static ref int F() => throw null;", "F", "F", "<>F{00000001}<System.Int32>"); yield return getData("static ref readonly int F() => throw null;", "F", "F", "<>F{00000003}<System.Int32>"); yield return getData("static void F() { }", "F", "F", "System.Action"); yield return getData("static void F(int x, int y) { }", "F", "F", "System.Action<System.Int32, System.Int32>"); yield return getData("static void F(out int x, int y) { x = 0; }", "F", "F", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("static void F(int x, ref int y) { }", "F", "F", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("static void F(int x, in int y) { }", "F", "F", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "F", "F", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "F", "F", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => null;", "F", "F", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Object>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => null;", "F", "F", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); object?[] getData(string methodDeclaration, string methodGroupExpression, string methodGroupOnly, string? expectedType) => new object?[] { methodDeclaration, methodGroupExpression, expectedType is null ? getExpectedDiagnostics(methodGroupExpression, methodGroupOnly) : null, expectedType }; } public static IEnumerable<object?[]> GetMethodGroupImplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; }); } [Theory] [MemberData(nameof(GetMethodGroupImplicitConversionData))] public void MethodGroup_ImplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetMethodGroupExplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, $"(System.Delegate){methodGroupExpression}").WithArguments("method", "System.Delegate").WithLocation(6, 20) }; }); } [Theory] [MemberData(nameof(GetMethodGroupExplicitConversionData))] public void MethodGroup_ExplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ object o = (System.Delegate){methodGroupExpression}; System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/52874: GetTypeInfo() for method group should return inferred delegate type. Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } public static IEnumerable<object?[]> GetLambdaData() { yield return getData("x => x", null); yield return getData("x => { return x; }", null); yield return getData("x => ref args[0]", null); yield return getData("(x, y) => { }", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("() => ref args[0]", "<>F{00000001}<System.String>"); yield return getData("() => { }", "System.Action"); yield return getData("(int x, int y) => { }", "System.Action<System.Int32, System.Int32>"); yield return getData("(out int x, int y) => { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("(int x, ref int y) => { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("(int x, in int y) => { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); yield return getData("async () => { await System.Threading.Tasks.Task.Delay(0); }", "System.Func<System.Threading.Tasks.Task>"); yield return getData("static async () => { await System.Threading.Tasks.Task.Delay(0); return 0; }", "System.Func<System.Threading.Tasks.Task<System.Int32>>"); yield return getData("() => Main", "System.Func<System.Action<System.String[]>>"); yield return getData("(int x) => x switch { _ => null }", null); yield return getData("_ => { }", null); yield return getData("_ => _", null); yield return getData("() => throw null", null); yield return getData("x => throw null", null); yield return getData("(int x) => throw null", null); yield return getData("() => { throw null; }", "System.Action"); yield return getData("(int x) => { throw null; }", "System.Action<System.Int32>"); yield return getData("(string s) => { if (s.Length > 0) return s; return null; }", "System.Func<System.String, System.String>"); yield return getData("(string s) => { if (s.Length > 0) return default; return s; }", "System.Func<System.String, System.String>"); yield return getData("(int i) => { if (i > 0) return i; return default; }", "System.Func<System.Int32, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return x; return y; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return y; return x; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("object () => default", "System.Func<System.Object>"); yield return getData("void () => { }", "System.Action"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } public static IEnumerable<object?[]> GetAnonymousMethodData() { yield return getData("delegate { }", null); yield return getData("delegate () { return 1; }", "System.Func<System.Int32>"); yield return getData("delegate () { return ref args[0]; }", "<>F{00000001}<System.String>"); yield return getData("delegate () { }", "System.Action"); yield return getData("delegate (int x, int y) { }", "System.Action<System.Int32, System.Int32>"); yield return getData("delegate (out int x, int y) { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("delegate (int x, ref int y) { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("delegate (int x, in int y) { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { return _1; }", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { return _1; }", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Delegate d = {anonymousFunction}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 29)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal(expectedType, typeInfo.Type.ToTestDisplayString()); } Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Delegate)({anonymousFunction}); System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,38): error CS8917: The delegate type could not be inferred. // object o = (System.Delegate)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 38)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(expectedType, typeInfo.ConvertedType?.ToTestDisplayString()); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } private static bool HaveMatchingSignatures(IMethodSymbol methodA, IMethodSymbol methodB) { return MemberSignatureComparer.MethodGroupSignatureComparer.Equals(methodA.GetSymbol<MethodSymbol>(), methodB.GetSymbol<MethodSymbol>()); } public static IEnumerable<object?[]> GetExpressionData() { yield return getData("x => x", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Linq.Expressions.Expression e = {anonymousFunction}; }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,48): error CS8917: The delegate type could not be inferred. // System.Linq.Expressions.Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 48)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.Type.ToTestDisplayString()); } Assert.Equal("System.Linq.Expressions.Expression", typeInfo.ConvertedType!.ToTestDisplayString()); } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Linq.Expressions.Expression)({anonymousFunction}); }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,57): error CS8917: The delegate type could not be inferred. // object o = (System.Linq.Expressions.Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 57)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); if (expectedType is null) { Assert.Null(typeInfo.ConvertedType); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.ConvertedType.ToTestDisplayString()); } } /// <summary> /// Should bind and report diagnostics from anonymous method body /// regardless of whether the delegate type can be inferred. /// </summary> [Fact] public void AnonymousMethodBodyErrors() { var source = @"using System; class Program { static void Main() { Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Delegate d1 = (object x1) => { _ = x1.Length; }; Delegate d2 = (ref object x2) => { _ = x2.Length; }; Delegate d3 = delegate (object x3) { _ = x3.Length; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,23): error CS8917: The delegate type could not be inferred. // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }").WithLocation(6, 23), // (6,68): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(6, 68), // (7,47): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d1 = (object x1) => { _ = x1.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(7, 47), // (8,51): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(8, 51), // (9,53): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d3 = delegate (object x3) { _ = x3.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(9, 53)); } public static IEnumerable<object?[]> GetBaseAndDerivedTypesData() { yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // instance and static // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "this.F", "F", new[] { // (5,29): error CS0176: Member 'B.F(object)' cannot be accessed with an instance reference; qualify it with a type name instead // System.Delegate d = this.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.F").WithArguments("B.F(object)").WithLocation(5, 29) }); // instance and static #endif yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "base.F", "F"); // static and instance yield return getData("internal void F(object x) { }", "internal static void F() { }", "F", "F"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "B.F", "F", null, "System.Action"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "this.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "F", "F"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "B.F", "F", null, "System.Action"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "base.F", "F"); // static and instance, different number of parameters yield return getData("internal static void F(object x) { }", "private static void F() { }", "F", "F"); // internal and private yield return getData("private static void F(object x) { }", "internal static void F() { }", "F", "F", null, "System.Action"); // internal and private yield return getData("internal abstract void F(object x);", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal virtual void F(object x) { }", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal void F(object x) { }", "internal void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object y) { }", "F", "F", null, "System.Action<System.Object>"); // different parameter name yield return getData("internal void F(object x) { }", "internal void F(string x) { }", "F", "F"); // different parameter type yield return getData("internal void F(object x) { }", "internal void F(object x, object y) { }", "F", "F"); // different number of parameters yield return getData("internal void F(object x) { }", "internal void F(ref object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal void F(ref object x) { }", "internal void F(object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal abstract object F();", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal virtual object F() => throw null;", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal object F() => throw null;", "internal object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal object F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal string F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return type yield return getData("internal object F() => throw null;", "internal new ref object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal ref object F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal void F(object x) { }", "internal new void F(dynamic x) { }", "F", "F", null, "System.Action<System.Object>"); // object/dynamic yield return getData("internal dynamic F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // object/dynamic yield return getData("internal void F((object, int) x) { }", "internal new void F((object a, int b) x) { }", "F", "F", null, "System.Action<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal (object a, int b) F() => throw null;", "internal new (object, int) F() => throw null;", "F", "F", null, "System.Func<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal void F(System.IntPtr x) { }", "internal new void F(nint x) { }", "F", "F", null, "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal nint F() => throw null;", "internal new System.IntPtr F() => throw null;", "F", "F", null, "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal void F(object x) { }", @"#nullable enable internal new void F(object? x) { } #nullable disable", "F", "F", null, "System.Action<System.Object>"); // different nullability yield return getData( @"#nullable enable internal object? F() => throw null!; #nullable disable", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // different nullability yield return getData("internal void F() { }", "internal void F<T>() { }", "F", "F"); // different arity yield return getData("internal void F() { }", "internal void F<T>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F", "F"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int, object>", "F<int, object>", null, "System.Action"); // different arity yield return getData("internal void F<T>(T t) { }", "internal new void F<U>(U u) { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter names yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "base.F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter constraints // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<object>", "F<object>", new[] { // (5,29): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // System.Delegate d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(5, 29) }); // different type parameter constraints #endif static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedType }; } } [Theory] [MemberData(nameof(GetBaseAndDerivedTypesData))] public void MethodGroup_BaseAndDerivedTypes(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"partial class B {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} static void Main() {{ new B().M(); }} }} abstract class A {{ {methodA} }} partial class B : A {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetExtensionMethodsSameScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "B.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (5,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(5, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsSameScopeData))] public void MethodGroup_ExtensionMethodsSameScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} static class B {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } public static IEnumerable<object?[]> GetExtensionMethodsDifferentScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this object x) { }", "this.F", "F", null, "A.F", "System.Action"); // hiding yield return getData("internal static void F(this object x) { }", "internal static void F(this object y) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter name yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, System.IntPtr y) { }", "internal static void F(this object x, nint y) { }", "this.F", "F", null, "A.F", "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static nint F(this object x) => throw null;", "internal static System.IntPtr F(this object x) => throw null;", "this.F", "F", null, "A.F", "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "N.B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (6,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(6, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsDifferentScopeData))] public void MethodGroup_ExtensionMethodsDifferentScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"using N; class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} namespace N {{ static class B {{ {methodB} }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } [Fact] public void InstanceMethods_01() { var source = @"using System; class Program { object F1() => null; void F2(object x, int y) { } void F() { Delegate d1 = F1; Delegate d2 = this.F2; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } static void Main() { new Program().F(); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Func<System.Object>, System.Action<System.Object, System.Int32>"); } [Fact] public void InstanceMethods_02() { var source = @"using System; class A { protected virtual void F() { Console.WriteLine(nameof(A)); } } class B : A { protected override void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_03() { var source = @"using System; class A { protected void F() { Console.WriteLine(nameof(A)); } } class B : A { protected new void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_04() { var source = @"class Program { T F<T>() => default; static void Main() { var p = new Program(); System.Delegate d = p.F; object o = (System.Delegate)p.F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,31): error CS8917: The delegate type could not be inferred. // System.Delegate d = p.F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 31), // (8,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)p.F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Delegate)p.F").WithArguments("method", "System.Delegate").WithLocation(8, 20)); } [Fact] public void MethodGroup_Inaccessible() { var source = @"using System; class A { private static void F() { } internal static void F(object o) { } } class B { static void Main() { Delegate d = A.F; Console.WriteLine(d.GetDelegateTypeName()); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Action<System.Object>"); } [Fact] public void MethodGroup_IncorrectArity() { var source = @"class Program { static void F0(object o) { } static void F0<T>(object o) { } static void F1(object o) { } static void F1<T, U>(object o) { } static void F2<T>(object o) { } static void F2<T, U>(object o) { } static void Main() { System.Delegate d; d = F0<int, object>; d = F1<int>; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,13): error CS0308: The non-generic method 'Program.F0(object)' cannot be used with type arguments // d = F0<int, object>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F0<int, object>").WithArguments("Program.F0(object)", "method").WithLocation(12, 13), // (13,13): error CS0308: The non-generic method 'Program.F1(object)' cannot be used with type arguments // d = F1<int>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F1<int>").WithArguments("Program.F1(object)", "method").WithLocation(13, 13), // (14,13): error CS8917: The delegate type could not be inferred. // d = F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 13)); } [Fact] public void ExtensionMethods_01() { var source = @"static class E { internal static void F1(this object x, int y) { } internal static void F2(this object x) { } } class Program { void F2(int x) { } static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 15)); } [Fact] public void ExtensionMethods_02() { var source = @"using System; static class E { internal static void F(this System.Type x, int y) { } internal static void F(this string x) { } } class Program { static void Main() { Delegate d1 = typeof(Program).F; Delegate d2 = """".F; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action<System.Int32>, System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => d.Initializer!.Value).ToArray(); Assert.Equal(2, exprs.Length); foreach (var expr in exprs) { var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } } [Fact] public void ExtensionMethods_03() { var source = @"using N; namespace N { static class E1 { internal static void F1(this object x, int y) { } internal static void F2(this object x, int y) { } internal static void F2(this object x) { } internal static void F3(this object x) { } } } static class E2 { internal static void F1(this object x) { } } class Program { static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; d = p.F3; d = E1.F1; d = E2.F1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (22,15): error CS8917: The delegate type could not be inferred. // d = p.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(22, 15), // (23,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(23, 15)); } [Fact] public void ExtensionMethods_04() { var source = @"static class E { internal static void F1(this object x, int y) { } } static class Program { static void F2(this object x) { } static void Main() { System.Delegate d; d = E.F1; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void ExtensionMethods_05() { var source = @"using System; static class E { internal static void F(this A a) { } } class A { } class B : A { static void Invoke(Delegate d) { } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,16): error CS0103: The name 'F' does not exist in the current context // Invoke(F); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(14, 16), // (16,21): error CS0117: 'A' does not contain a definition for 'F' // Invoke(base.F); Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("A", "F").WithLocation(16, 21)); } [Fact] public void ExtensionMethods_06() { var source = @"static class E { internal static void F1<T>(this object x, T y) { } internal static void F2<T, U>(this T t) { } } class Program { static void F<T>(T t) where T : class { System.Delegate d; d = t.F1; d = t.F2; d = t.F1<int>; d = t.F1<T>; d = t.F2<T, object>; d = t.F2<object, T>; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,15): error CS8917: The delegate type could not be inferred. // d = t.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(11, 15), // (12,15): error CS8917: The delegate type could not be inferred. // d = t.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(12, 15)); } /// <summary> /// Method group with dynamic receiver does not use method group conversion. /// </summary> [Fact] public void DynamicReceiver() { var source = @"using System; class Program { void F() { } static void Main() { dynamic d = new Program(); object obj; try { obj = d.F; } catch (Exception e) { obj = e; } Console.WriteLine(obj.GetType().FullName); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, references: new[] { CSharpRef }, expectedOutput: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"); } // System.Func<> and System.Action<> cannot be used as the delegate type // when the parameters or return type are not valid type arguments. [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void InvalidTypeArguments() { var source = @"unsafe class Program { static int* F() => throw null; static void Main() { System.Delegate d; d = F; d = (int x, int* y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,13): error CS8917: The delegate type could not be inferred. // d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = (int x, int* y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, int* y) => { }").WithLocation(8, 13)); } [Fact] public void GenericDelegateType() { var source = @"using System; class Program { static void Main() { Delegate d = F<int>(); Console.WriteLine(d.GetDelegateTypeName()); } unsafe static Delegate F<T>() { return (T t, int* p) => { }; } }"; // When we synthesize delegate types with parameter types (such as int*) that cannot // be used as type arguments, run the program to report the actual delegate type. var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (11,16): error CS8917: The delegate type could not be inferred. // return (T t, int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(T t, int* p) => { }").WithLocation(11, 16)); } [Fact] public void Member_01() { var source = @"using System; class Program { static void Main() { Console.WriteLine((() => { }).GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0023: Operator '.' cannot be applied to operand of type 'lambda expression' // Console.WriteLine((() => { }).GetType()); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(() => { }).GetType").WithArguments(".", "lambda expression").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void Member_02() { var source = @"using System; class Program { static void Main() { Console.WriteLine(Main.GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0119: 'Program.Main()' is a method, which is not valid in the given context // Console.WriteLine(Main.GetType()); Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_01() { var sourceA = @".class public A { .method public static void F1(object modopt(int32) x) { ldnull throw } .method public static object modopt(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Action<System.Object> System.Func<System.Object>"); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_02() { var sourceA = @".class public A { .method public static void F1(object modreq(int32) x) { ldnull throw } .method public static object modreq(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,16): error CS0570: 'A.F1(object)' is not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F1").WithArguments("A.F1(object)").WithLocation(10, 16), // (10,16): error CS0648: '' is a type not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BogusType, "A.F1").WithArguments("").WithLocation(10, 16), // (11,16): error CS0570: 'A.F2()' is not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F2").WithArguments("A.F2()").WithLocation(11, 16), // (11,16): error CS0648: '' is a type not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BogusType, "A.F2").WithArguments("").WithLocation(11, 16)); } [Fact] public void UnmanagedCallersOnlyAttribute_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = F; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] static void F() { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS8902: 'Program.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // Delegate d = F; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("Program.F()").WithLocation(8, 22)); } [Fact] public void UnmanagedCallersOnlyAttribute_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = new S().F; } } struct S { } static class E1 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] public static void F(this S s) { } } static class E2 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] public static void F(this S s) { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'E1.F(S)' and 'E2.F(S)' // Delegate d = new S().F; Diagnostic(ErrorCode.ERR_AmbigCall, "new S().F").WithArguments("E1.F(S)", "E2.F(S)").WithLocation(8, 22)); } [Fact] public void SystemActionAndFunc_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,13): error CS8917: The delegate type could not be inferred. // d = Main; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "Main").WithLocation(6, 13), // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (7,13): error CS0518: Predefined type 'System.Func`1' is not defined or imported // d = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Func`1").WithLocation(7, 13)); } private static MetadataReference GetCorlibWithInvalidActionAndFuncOfT() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Action`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance void Invoke(!T t) { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemActionAndFunc_UseSiteErrors() { var refA = GetCorlibWithInvalidActionAndFuncOfT(); var sourceB = @"class Program { static void F(object o) { } static void Main() { System.Delegate d; d = F; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (10,13): error CS0648: 'Func<T>' is a type not supported by the language // d = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(10, 13)); } [Fact] public void SystemLinqExpressionsExpression_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (5,48): error CS0518: Predefined type 'System.Linq.Expressions.Expression`1' is not defined or imported // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Linq.Expressions.Expression`1").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_UseSiteErrors() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Linq.Expressions.LambdaExpression { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0648: 'Expression<T>' is a type not supported by the language // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Linq.Expressions.Expression<T>").WithLocation(5, 48)); } // Expression<T> not derived from Expression. private static MetadataReference GetCorlibWithExpressionOfTNotDerivedType() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_01() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_02() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static T F<T>(T t) where T : System.Linq.Expressions.Expression => t; static void Main() { var e = F(() => 1); } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (6,17): error CS0311: The type 'System.Linq.Expressions.Expression<System.Func<int>>' cannot be used as type parameter 'T' in the generic type or method 'Program.F<T>(T)'. There is no implicit reference conversion from 'System.Linq.Expressions.Expression<System.Func<int>>' to 'System.Linq.Expressions.Expression'. // var e = F(() => 1); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "F").WithArguments("Program.F<T>(T)", "System.Linq.Expressions.Expression", "T", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(6, 17)); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_01() { var source = @"using System; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Action<string> a) { Console.WriteLine(""M(Action<string> a)""); } static void F(object o) { } static void Main() { M(F); // C#9: M(Action<string>) } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "M(Action<string> a)"); // Breaking change from C#9 which binds to M(Action<string> a). CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: "M<T>(T t)"); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_02() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(object y) { Console.WriteLine(""C.M(object y)""); } } static class E { public static void M(this object x, Action y) { Console.WriteLine(""E.M(object x, Action y)""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M(object x, Action y) E.M(object x, Action y) "); // Breaking change from C#9 which binds to E.M(object x, Action y). CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"C.M(object y) C.M(object y) "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_03() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(Delegate d) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Action a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M E.M "); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M C.M "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var c = new C(); c.M(() => 1); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M"); } [Fact] public void OverloadResolution_05() { var source = @"using System; class Program { static void Report(string name) { Console.WriteLine(name); } static void FA(Delegate d) { Report(""FA(Delegate)""); } static void FA(Action d) { Report(""FA(Action)""); } static void FB(Delegate d) { Report(""FB(Delegate)""); } static void FB(Func<int> d) { Report(""FB(Func<int>)""); } static void F1() { } static int F2() => 0; static void Main() { FA(F1); FA(F2); FB(F1); FB(F2); FA(() => { }); FA(() => 0); FB(() => { }); FB(() => 0); FA(delegate () { }); FA(delegate () { return 0; }); FB(delegate () { }); FB(delegate () { return 0; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FA(F2); Diagnostic(ErrorCode.ERR_BadArgType, "F2").WithArguments("1", "method group", "System.Delegate").WithLocation(14, 12), // (15,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FB(F1); Diagnostic(ErrorCode.ERR_BadArgType, "F1").WithArguments("1", "method group", "System.Delegate").WithLocation(15, 12), // (18,18): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // FA(() => 0); Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(18, 18), // (19,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // FB(() => { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(19, 15), // (22,26): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // FA(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(22, 26), // (23,12): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // FB(delegate () { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(23, 12)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) "); } [Fact] public void OverloadResolution_06() { var source = @"using System; using System.Linq.Expressions; class Program { static void Report(string name, Expression e) { Console.WriteLine(""{0}: {1}"", name, e); } static void F(Expression e) { Report(""F(Expression)"", e); } static void F(Expression<Func<int>> e) { Report(""F(Expression<Func<int>>)"", e); } static void Main() { F(() => 0); F(() => string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // F(() => string.Empty); Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 17), // (11,17): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // F(() => string.Empty); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "string.Empty").WithArguments("lambda expression").WithLocation(11, 17)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"F(Expression<Func<int>>): () => 0 F(Expression): () => String.Empty "); } [Fact] public void OverloadResolution_07() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) { } static void F(Expression<Func<int>> e) { } static void Main() { F(delegate () { return 0; }); F(delegate () { return string.Empty; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 0; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return string.Empty; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(10, 11)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (9,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 0; }").WithLocation(9, 11), // (10,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return string.Empty; }").WithLocation(10, 11)); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_08() { var source = @"using System; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_09() { var source = @"using System; using System.Linq.Expressions; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Expression e) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Expression<Func<int, int>> e) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_10() { var source = @"using System; using static System.Console; class C { static object M1(object o) => o; static int M1(int i) => i; static int M2(int i) => i; static void Main() { var c = new C(); c.F(M1); c.F(M2); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [Fact] public void OverloadResolution_11() { var source = @"using System; using System.Linq.Expressions; class C { static object M1(object o) => o; static int M1(int i) => i; static void Main() { F1(x => x); F1(M1); F2(x => x); } static void F1(Delegate d) { } static void F2(Expression e) { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F1(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // F2(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 12)); var expectedDiagnostics10AndLater = new[] { // (9,12): error CS8917: The delegate type could not be inferred. // F1(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS8917: The delegate type could not be inferred. // F2(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 12) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_12() { var source = @"using System; #nullable enable var app = new WebApp(); app.Map(""/sub1"", builder => { builder.UseAuth(); }); app.Map(""/sub2"", (IAppBuilder builder) => { builder.UseAuth(); }); class WebApp : IAppBuilder, IRouteBuilder { public void UseAuth() { } } interface IAppBuilder { void UseAuth(); } interface IRouteBuilder { } static class AppBuilderExtensions { public static IAppBuilder Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) => app; } static class RouteBuilderExtensions { public static IRouteBuilder Map(this IRouteBuilder routes, string path, Delegate callback) => routes; } struct PathSring { public PathSring(string? path) { Path = path; } public string? Path { get; } public static implicit operator PathSring(string? s) => new PathSring(s); public static implicit operator string?(PathSring path) => path.Path; }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (8,5): error CS0121: The call is ambiguous between the following methods or properties: 'AppBuilderExtensions.Map(IAppBuilder, PathSring, Action<IAppBuilder>)' and 'RouteBuilderExtensions.Map(IRouteBuilder, string, Delegate)' // app.Map("/sub2", (IAppBuilder builder) => Diagnostic(ErrorCode.ERR_AmbigCall, "Map").WithArguments("AppBuilderExtensions.Map(IAppBuilder, PathSring, System.Action<IAppBuilder>)", "RouteBuilderExtensions.Map(IRouteBuilder, string, System.Delegate)").WithLocation(8, 5) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_13() { var source = @"using System; class Program { static void Main() { F(1, () => { }); F(2, Main); } static void F(object obj, Action a) { } static void F(int i, Delegate d) { } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(object, Action)' and 'Program.F(int, Delegate)' // F(1, () => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(object, System.Action)", "Program.F(int, System.Delegate)").WithLocation(6, 9), // (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(object, Action)' and 'Program.F(int, Delegate)' // F(2, Main); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(object, System.Action)", "Program.F(int, System.Delegate)").WithLocation(7, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_14() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { F(() => 1, 2); } static void F(Expression<Func<object>> f, object obj) { } static void F(Expression e, int i) { } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Expression<Func<object>>, object)' and 'Program.F(Expression, int)' // F(() => 1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Linq.Expressions.Expression<System.Func<object>>, object)", "Program.F(System.Linq.Expressions.Expression, int)").WithLocation(7, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_15() { var source = @"delegate void StringAction(string arg); class Program { static void F<T>(T t) { } static void F(StringAction a) { } static void M(string arg) { } static void Main() { F((string s) => { }); // C#9: F(StringAction) F(M); // C#9: F(StringAction) } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); // Breaking change from C#9 which binds calls to F(StringAction). comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(T)' and 'Program.F(StringAction)' // F((string s) => { }); // C#9: F(StringAction) Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(T)", "Program.F(StringAction)").WithLocation(9, 9), // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(T)' and 'Program.F(StringAction)' // F(M); // C#9: F(StringAction) Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(T)", "Program.F(StringAction)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_16() { var source = @"using System; class Program { static void F(Func<Func<object>> f, int i) => Report(f); static void F(Func<Func<int>> f, object o) => Report(f); static void Main() { F(() => () => 1, 2); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"System.Func`1[System.Func`1[System.Object]]"); // Breaking change from C#9 which binds calls to F(Func<Func<object>>, int). var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Func<Func<object>>, int)' and 'Program.F(Func<Func<int>>, object)' // F(() => () => 1, 2); // C#9: F(Func<Func<object>>, int) Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Func<System.Func<object>>, int)", "Program.F(System.Func<System.Func<int>>, object)").WithLocation(8, 9)); } [Fact] public void OverloadResolution_17() { var source = @"delegate void StringAction(string arg); class Program { static void F<T>(System.Action<T> a) { } static void F(StringAction a) { } static void Main() { F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F(StringAction)").WithLocation(8, 9)); } [Fact] public void OverloadResolution_18() { var source = @"delegate void StringAction(string arg); class Program { static void F0<T>(System.Action<T> a) { } static void F1<T>(System.Action<T> a) { } static void F1(StringAction a) { } static void M(string arg) { } static void Main() { F0(M); F1(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'Program.F0<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F0(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F0").WithArguments("Program.F0<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_19() { var source = @"delegate void MyAction<T>(T arg); class Program { static void F<T>(System.Action<T> a) { } static void F<T>(MyAction<T> a) { } static void M(string arg) { } static void Main() { F((string s) => { }); F(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F<T>(MyAction<T>)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F<T>(MyAction<T>)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.F<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_20() { var source = @"using System; delegate void StringAction(string s); class Program { static void F(Action<string> a) { } static void F(StringAction a) { } static void M(string s) { } static void Main() { F(M); F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F(M); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(10, 9), // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(11, 9)); } [Fact] public void OverloadResolution_21() { var source = @"using System; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Delegate>(); c.F(() => (Action)null); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Delegate]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(1361172, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1361172")] [Fact] public void OverloadResolution_22() { var source = @"using System; using System.Linq.Expressions; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Expression>(); c.F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Linq.Expressions.Expression]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (15,11): error CS0121: The call is ambiguous between the following methods or properties: 'C<T>.F(T)' and 'C<T>.F(Func<T>)' // c.F(() => Expression.Constant(1)); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("C<T>.F(T)", "C<T>.F(System.Func<T>)").WithLocation(15, 11) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [Fact] public void OverloadResolution_23() { var source = @"using System; class Program { static void F(Delegate d) => Console.WriteLine(""F(Delegate d)""); static void F(Func<object> f) => Console.WriteLine(""F(Func<int> f)""); static void Main() { F(() => 1); } }"; string expectedOutput = "F(Func<int> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_24() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) => Console.WriteLine(""F(Expression e)""); static void F(Func<Expression> f) => Console.WriteLine(""F(Func<Expression> f)""); static void Main() { F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<Expression> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Expression)' and 'Program.F(Func<Expression>)' // F(() => Expression.Constant(1)); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Linq.Expressions.Expression)", "Program.F(System.Func<System.Linq.Expressions.Expression>)").WithLocation(9, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [Fact] public void BestCommonType_01() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { StringIntDelegate d = M; var a1 = new[] { d, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => int.Parse(s), d }; Report(a1[1]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_02() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void F(bool b) { StringIntDelegate d = M; var c1 = b ? d : ((string s) => int.Parse(s)); var c2 = b ? ((string s) => int.Parse(s)) : d; Report(c1); Report(c2); } static void Main() { F(false); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_03() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return (StringIntDelegate)M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return (StringIntDelegate)M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"StringIntDelegate StringIntDelegate"); } [Fact] public void BestCommonType_04() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_05() { var source = @"using System; class Program { static int M1(string s) => s.Length; static int M2(string s) => int.Parse(s); static void Main() { var a1 = new[] { M1, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => s.Length, M2 }; Report(a1[1]); Report(a2[1]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { M1, (string s) => int.Parse(s) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { M1, (string s) => int.Parse(s) }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (string s) => s.Length, M2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (string s) => s.Length, M2 }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_06() { var source = @"using System; class Program { static void F1<T>(T t) { } static T F2<T>() => default; static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object>, F2<string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object>, F2<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object>, F2<string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Func`1[System.Object]"); } [Fact] public void BestCommonType_07() { var source = @"class Program { static void F1<T>(T t) { } static T F2<T>() => default; static T F3<T>(T t) => t; static void Main() { var a1 = new[] { F1<int>, F1<object> }; var a2 = new[] { F2<nint>, F2<System.IntPtr> }; var a3 = new[] { F3<string>, F3<object> }; } }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<int>, F1<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<int>, F1<object> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<nint>, F2<System.IntPtr> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<nint>, F2<System.IntPtr> }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F3<string>, F3<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F3<string>, F3<object> }").WithLocation(10, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_08() { var source = @"#nullable enable using System; class Program { static void F<T>(T t) { } static void Main() { var a1 = new[] { F<string?>, F<string> }; var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<string?>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<string?>, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<(int X, object Y)>, F<(int, dynamic)> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Action`1[System.ValueTuple`2[System.Int32,System.Object]]"); } [Fact] public void BestCommonType_09() { var source = @"using System; class Program { static void Main() { var a1 = new[] { (object o) => { }, (string s) => { } }; var a2 = new[] { () => (object)null, () => (string)null }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object o) => { }, (string s) => { } }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { () => (object)null, () => (string)null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => (object)null, () => (string)null }").WithLocation(7, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,26): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(6, 26), // (6,34): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(6, 34)); } [Fact] public void BestCommonType_10() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<string>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<string>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<string>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000004}`2[System.String,System.Object] <>A{00000001}`2[System.Object,System.String]"); } [Fact] [WorkItem(55909, "https://github.com/dotnet/roslyn/issues/55909")] public void BestCommonType_11() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, object> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, object> }").WithLocation(9, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/55909: ConversionsBase.HasImplicitSignatureConversion() // relies on the variance of FunctionTypeSymbol.GetInternalDelegateType() which fails for synthesized // delegate types where the type parameters are invariant. comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_12() { var source = @"class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, F<string> }; var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; } }"; var expectedDiagnostics = new[] { // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, F<string> }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_13() { var source = @"using System; class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, null }; var a2 = new[] { default, F<string> }; var a3 = new[] { null, default, (object x, ref string y) => { } }; Report(a1[0]); Report(a2[1]); Report(a3[2]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, null }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { default, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { default, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { null, default, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { null, default, (object x, ref string y) => { } }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000001}`1[System.Object] <>A{00000001}`1[System.String] <>A{00000004}`2[System.Object,System.String] "); } /// <summary> /// Best common type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void BestCommonType_NoInferredSignature() { var source = @"class Program { static void F1() { } static int F1(int i) => i; static void F2() { } static void Main() { var a1 = new[] { F1 }; var a2 = new[] { F1, F2 }; var a3 = new[] { F2, F1 }; var a4 = new[] { x => x }; var a5 = new[] { x => x, (int y) => y }; var a6 = new[] { (int y) => y, static x => x }; var a7 = new[] { x => x, F1 }; var a8 = new[] { F1, (int y) => y }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F1, F2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, F2 }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F2, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2, F1 }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var a5 = new[] { x => x, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, (int y) => y }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var a6 = new[] { (int y) => y, static x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (int y) => y, static x => x }").WithLocation(13, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var a8 = new[] { F1, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, (int y) => y }").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18)); } [Fact] public void ArrayInitializer_01() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Func<int>[] { () => 1 }; var a2 = new Expression<Func<int>>[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = $@"System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void ArrayInitializer_02() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Delegate[] { () => 1 }; var a2 = new Expression[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,35): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var a1 = new Delegate[] { () => 1 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 35), // (8,37): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // var a2 = new Expression[] { () => 2 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(8, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]]"); } [Fact] public void ArrayInitializer_03() { var source = @"using System; class Program { static void Main() { var a1 = new[] { () => 1 }; Report(a1[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { () => 1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => 1 }").WithLocation(6, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32]"); } [Fact] public void ConditionalOperator_01() { var source = @"class Program { static void F<T>(T t) { } static void Main() { var c1 = F<object> ?? F<string>; var c2 = ((object o) => { }) ?? ((string s) => { }); var c3 = F<string> ?? ((object o) => { }); } }"; var expectedDiagnostics = new[] { // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // var c1 = F<object> ?? F<string>; Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<object> ?? F<string>").WithArguments("??", "method group", "method group").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'lambda expression' and 'lambda expression' // var c2 = ((object o) => { }) ?? ((string s) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "((object o) => { }) ?? ((string s) => { })").WithArguments("??", "lambda expression", "lambda expression").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'lambda expression' // var c3 = F<string> ?? ((object o) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<string> ?? ((object o) => { })").WithArguments("??", "method group", "lambda expression").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaReturn_01() { var source = @"using System; class Program { static void Main() { var a1 = () => () => 1; var a2 = () => Main; Report(a1()); Report(a2()); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32] System.Action"); } [Fact] public void InferredType_MethodGroup() { var source = @"class Program { static void Main() { System.Delegate d = Main; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } [Fact] public void InferredType_LambdaExpression() { var source = @"class Program { static void Main() { System.Delegate d = () => { }; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } [Fact] public void TypeInference_Constraints_01() { var source = @"using System; using System.Linq.Expressions; class Program { static T F1<T>(T t) where T : Delegate => t; static T F2<T>(T t) where T : Expression => t; static void Main() { Report(F1((int i) => { })); Report(F2(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((int i) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F2<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Action`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_02() { var source = @"using System; using System.Linq.Expressions; class A<T> { public static U F<U>(U u) where U : T => u; } class B { static void Main() { Report(A<object>.F(() => 1)); Report(A<ICloneable>.F(() => 1)); Report(A<Delegate>.F(() => 1)); Report(A<MulticastDelegate>.F(() => 1)); Report(A<Func<int>>.F(() => 1)); Report(A<Expression>.F(() => 1)); Report(A<LambdaExpression>.F(() => 1)); Report(A<Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_03() { var source = @"using System; using System.Linq.Expressions; class A<T, U> where U : T { public static V F<V>(V v) where V : U => v; } class B { static void Main() { Report(A<object, object>.F(() => 1)); Report(A<object, Delegate>.F(() => 1)); Report(A<object, Func<int>>.F(() => 1)); Report(A<Delegate, Func<int>>.F(() => 1)); Report(A<object, Expression>.F(() => 1)); Report(A<object, Expression<Func<int>>>.F(() => 1)); Report(A<Expression, LambdaExpression>.F(() => 1)); Report(A<Expression, Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_MatchingSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(string s) => s.Length; static void F2(string s) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_DistinctSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(object o) => o.GetHashCode(); static void F2(object o) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_01() { var source = @"using System; class Program { static T M<T>(T x, T y) => x; static int F1(int i) => i; static void F1() { } static T F2<T>(T t) => t; static void Main() { var f1 = M(x => x, (int y) => y); var f2 = M(F1, F2<int>); var f3 = M(F2<object>, z => z); Report(f1); Report(f2); Report(f3); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(F1, F2<int>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M(F2<object>, z => z); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(12, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] System.Func`2[System.Object,System.Object] "); } [Fact] public void TypeInference_02() { var source = @"using System; class Program { static T M<T>(T x, T y) where T : class => x ?? y; static T F<T>() => default; static void Main() { var f1 = M(F<object>, null); var f2 = M(default, F<string>); var f3 = M((object x, ref string y) => { }, default); var f4 = M(null, (ref object x, string y) => { }); Report(f1); Report(f2); Report(f3); Report(f4); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(F<object>, null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(8, 18), // (9,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(default, F<string>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(9, 18), // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M((object x, ref string y) => { }, default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f4 = M(null, (ref object x, string y) => { }); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Object] System.Func`1[System.String] <>A{00000004}`2[System.Object,System.String] <>A{00000001}`2[System.Object,System.String] "); } [Fact] public void TypeInference_LowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (string s) => { })); Report(F(() => 2, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (object o) => { })); Report(F(() => 1.0, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (11,22): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(11, 22), // (11,30): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(11, 30), // (12,24): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.0").WithArguments("double", "int").WithLocation(12, 24), // (12,24): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1.0").WithArguments("lambda expression").WithLocation(12, 24) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_02() { var source = @"using System; class Program { static T F<T>(T x, T y) => y; static void Main() { Report(F((string s) => { }, (object o) => { })); Report(F(() => string.Empty, () => new object())); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(7, 16), // (8,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(() => string.Empty, () => new object())); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(8, 16)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,37): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(7, 37), // (7,45): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(7, 45)); } [Fact] public void TypeInference_UpperAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<int>> a2 = null; Report(F1(a1, (string s) => { })); Report(F2(() => 2, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<object>> a2 = null; Report(F1(a1, (object o) => { })); Report(F2(() => string.Empty, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,23): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 23), // (12,31): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 31) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,42): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(10, 50) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F1(ref d1, (string s) => { })); Report(F2(() => 2, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<object> d2 = () => new object(); Report(F1(ref d1, (object o) => { })); Report(F2(() => string.Empty, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,27): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 27), // (12,35): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 35) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(in T x, T y) => y; static T F2<T>(T x, in T y) => y; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,16): error CS0411: The type arguments for method 'Program.F1<T>(in T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(in T, T)").WithLocation(10, 16), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,42): error CS1661: Cannot convert lambda expression to type 'Action<D1<string>>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<D1<string>>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'D1<string>' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "D1<string>").WithLocation(10, 50), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16)); } [Fact] public void TypeInference_Nested_01() { var source = @"delegate void D<T>(T t); class Program { static T F1<T>(T t) => t; static D<T> F2<T>(D<T> d) => d; static void Main() { F2(F1((string s) => { })); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(D<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(D<T>)").WithLocation(8, 9)); } [Fact] public void TypeInference_Nested_02() { var source = @"using System.Linq.Expressions; class Program { static T F1<T>(T x) => throw null; static Expression<T> F2<T>(Expression<T> e) => e; static void Main() { F2(F1((object x1) => 1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((object x1) => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<T>)").WithLocation(8, 9)); } /// <summary> /// Method type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void TypeInference_NoInferredSignature() { var source = @"class Program { static void F1() { } static void F1(int i) { } static void F2() { } static T M1<T>(T t) => t; static T M2<T>(T x, T y) => x; static void Main() { var a1 = M1(F1); var a2 = M2(F1, F2); var a3 = M2(F2, F1); var a4 = M1(x => x); var a5 = M2(x => x, (int y) => y); var a6 = M2((int y) => y, x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a2 = M2(F1, F2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a3 = M2(F2, F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(12, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18), // (14,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a5 = M2(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(14, 18), // (15,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a6 = M2((int y) => y, x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18)); } [Fact] public void Variance() { var source = @"using System; delegate void StringAction(string s); class Program { static void Main() { Action<string> a1 = s => { }; Action<string> a2 = (string s) => { }; Action<string> a3 = (object o) => { }; Action<string> a4 = (Action<object>)((object o) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,29): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(9, 29), // (9,37): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(9, 37)); } [Fact] public void ImplicitlyTypedVariables_01() { var source = @"using System; class Program { static void Main() { var d1 = Main; Report(d1); var d2 = () => { }; Report(d2); var d3 = delegate () { }; Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = Main; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 18), // (8,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 18), // (10,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(10, 18)); comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action"); verifier.VerifyIL("Program.Main", @"{ // Code size 100 (0x64) .maxstack 2 .locals init (System.Action V_0, //d1 System.Action V_1, //d2 System.Action V_2) //d3 IL_0000: nop IL_0001: ldnull IL_0002: ldftn ""void Program.Main()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void Program.Report(System.Delegate)"" IL_0014: nop IL_0015: ldsfld ""System.Action Program.<>c.<>9__0_0"" IL_001a: dup IL_001b: brtrue.s IL_0034 IL_001d: pop IL_001e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0023: ldftn ""void Program.<>c.<Main>b__0_0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: dup IL_002f: stsfld ""System.Action Program.<>c.<>9__0_0"" IL_0034: stloc.1 IL_0035: ldloc.1 IL_0036: call ""void Program.Report(System.Delegate)"" IL_003b: nop IL_003c: ldsfld ""System.Action Program.<>c.<>9__0_1"" IL_0041: dup IL_0042: brtrue.s IL_005b IL_0044: pop IL_0045: ldsfld ""Program.<>c Program.<>c.<>9"" IL_004a: ldftn ""void Program.<>c.<Main>b__0_1()"" IL_0050: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0055: dup IL_0056: stsfld ""System.Action Program.<>c.<>9__0_1"" IL_005b: stloc.2 IL_005c: ldloc.2 IL_005d: call ""void Program.Report(System.Delegate)"" IL_0062: nop IL_0063: ret }"); } [Fact] public void ImplicitlyTypedVariables_02() { var source = @"var d1 = object.ReferenceEquals; var d2 = () => { }; var d3 = delegate () { }; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics( // (1,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = object.ReferenceEquals; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object.ReferenceEquals").WithArguments("inferred delegate type", "10.0").WithLocation(1, 10), // (2,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(2, 10), // (3,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(3, 10)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_03() { var source = @"class Program { static void Main() { ref var d1 = Main; ref var d2 = () => { }; ref var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d1 = Main; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d1 = Main").WithLocation(5, 17), // (5,22): error CS1657: Cannot use 'Main' as a ref or out value because it is a 'method group' // ref var d1 = Main; Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Main").WithArguments("Main", "method group").WithLocation(5, 22), // (6,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d2 = () => { }").WithLocation(6, 17), // (6,22): error CS1510: A ref or out value must be an assignable variable // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "() => { }").WithLocation(6, 22), // (7,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d3 = delegate () { }").WithLocation(7, 17), // (7,22): error CS1510: A ref or out value must be an assignable variable // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate () { }").WithLocation(7, 22)); } [Fact] public void ImplicitlyTypedVariables_04() { var source = @"class Program { static void Main() { using var d1 = Main; using var d2 = () => { }; using var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d1 = Main; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d1 = Main;").WithArguments("System.Action").WithLocation(5, 9), // (6,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d2 = () => { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d2 = () => { };").WithArguments("System.Action").WithLocation(6, 9), // (7,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d3 = delegate () { };").WithArguments("System.Action").WithLocation(7, 9)); } [Fact] public void ImplicitlyTypedVariables_05() { var source = @"class Program { static void Main() { foreach (var d1 in Main) { } foreach (var d2 in () => { }) { } foreach (var d3 in delegate () { }) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? // foreach (var d1 in Main) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group").WithLocation(5, 28), // (6,28): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // foreach (var d2 in () => { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => { }").WithArguments("lambda expression").WithLocation(6, 28), // (7,28): error CS0446: Foreach cannot operate on a 'anonymous method'. Did you intend to invoke the 'anonymous method'? // foreach (var d3 in delegate () { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "delegate () { }").WithArguments("anonymous method").WithLocation(7, 28)); } [Fact] public void ImplicitlyTypedVariables_06() { var source = @"using System; class Program { static void Main() { Func<int> f; var d1 = Main; f = d1; var d2 = object (int x) => x; f = d2; var d3 = delegate () { return string.Empty; }; f = d3; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<int>' // f = d1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("System.Action", "System.Func<int>").WithLocation(8, 13), // (10,13): error CS0029: Cannot implicitly convert type 'System.Func<int, object>' to 'System.Func<int>' // f = d2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("System.Func<int, object>", "System.Func<int>").WithLocation(10, 13), // (12,13): error CS0029: Cannot implicitly convert type 'System.Func<string>' to 'System.Func<int>' // f = d3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("System.Func<string>", "System.Func<int>").WithLocation(12, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Initializer != null); var expectedInfo = new (string?, string?, string?)[] { ("System.Action d1", null, "System.Action"), ("System.Func<System.Int32, System.Object> d2", null, "System.Func<System.Int32, System.Object>"), ("System.Func<System.String> d3", null, "System.Func<System.String>"), }; AssertEx.Equal(expectedInfo, variables.Select(v => getVariableInfo(model, v))); static (string?, string?, string?) getVariableInfo(SemanticModel model, VariableDeclaratorSyntax variable) { var symbol = model.GetDeclaredSymbol(variable); var typeInfo = model.GetTypeInfo(variable.Initializer!.Value); return (symbol?.ToTestDisplayString(), typeInfo.Type?.ToTestDisplayString(), typeInfo.ConvertedType?.ToTestDisplayString()); } } [Fact] public void ImplicitlyTypedVariables_07() { var source = @"class Program { static void Main() { var t = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,13): error CS0815: Cannot assign (method group, lambda expression) to an implicitly-typed variable // var t = (Main, () => { }); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (Main, () => { })").WithArguments("(method group, lambda expression)").WithLocation(5, 13)); } [Fact] public void ImplicitlyTypedVariables_08() { var source = @"class Program { static void Main() { (var x1, var y1) = Main; var (x2, y2) = () => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(5, 14), // (5,22): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(5, 22), // (5,28): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "Main").WithLocation(5, 28), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 14), // (6,18): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(6, 18), // (6,24): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "() => { }").WithLocation(6, 24)); } [Fact] public void ImplicitlyTypedVariables_09() { var source = @"class Program { static void Main() { var (x, y) = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(5, 14), // (5,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] public void ImplicitlyTypedVariables_10() { var source = @"using System; class Program { static void Main() { (var x1, Action y1) = (Main, null); (Action x2, var y2) = (null, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, Action y1) = (Main, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 14), // (7,25): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // (Action x2, var y2) = (null, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)); } [Fact] public void ImplicitlyTypedVariables_11() { var source = @"class Program { static void F(object o) { } static void F(int i) { } static void Main() { var d1 = F; var d2 = x => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d2 = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 18)); } [Fact] public void ImplicitlyTypedVariables_12() { var source = @"class Program { static void F(ref int i) { } static void Main() { var d1 = F; var d2 = (ref int x) => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_13() { var source = @"using System; class Program { static int F() => 0; static void Main() { var d1 = (F); Report(d1); var d2 = (object (int x) => x); Report(d2); var d3 = (delegate () { return string.Empty; }); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; CompileAndVerify(new[] { source, s_utils }, options: TestOptions.DebugExe, expectedOutput: @"System.Func<System.Int32> System.Func<System.Int32, System.Object> System.Func<System.String>"); } [Fact] public void ImplicitlyTypedVariables_14() { var source = @"delegate void D(string s); class Program { static void Main() { (D x, var y) = (() => string.Empty, () => string.Empty); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // (D x, var y) = (() => string.Empty, () => string.Empty); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(6, 19)); } [Fact] public void ImplicitlyTypedVariables_UseSiteErrors() { var source = @"class Program { static void F(object o) { } static void Main() { var d1 = F; var d2 = () => 1; } }"; var comp = CreateEmptyCompilation(source, new[] { GetCorlibWithInvalidActionAndFuncOfT() }); comp.VerifyDiagnostics( // (6,18): error CS0648: 'Action<T>' is a type not supported by the language // var d1 = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(6, 18), // (7,18): error CS0648: 'Func<T>' is a type not supported by the language // var d2 = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(7, 18)); } [Fact] public void BinaryOperator() { var source = @"using System; class Program { static void Main() { var b1 = (() => { }) == null; var b2 = null == Main; var b3 = Main == (() => { }); Console.WriteLine((b1, b2, b3)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0019: Operator '==' cannot be applied to operands of type 'lambda expression' and '<null>' // var b1 = (() => { }) == null; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(() => { }) == null").WithArguments("==", "lambda expression", "<null>").WithLocation(6, 18), // (7,18): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'method group' // var b2 = null == Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "null == Main").WithArguments("==", "<null>", "method group").WithLocation(7, 18), // (8,18): error CS0019: Operator '==' cannot be applied to operands of type 'method group' and 'lambda expression' // var b3 = Main == (() => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main == (() => { })").WithArguments("==", "method group", "lambda expression").WithLocation(8, 18)); CompileAndVerify(source, expectedOutput: "(False, False, False)"); } /// <summary> /// Ensure the conversion group containing the implicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_01() { var source = @"#nullable enable class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } /// <summary> /// Ensure the conversion group containing the explicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_02() { var source = @"#nullable enable class Program { static void Main() { object o; o = (System.Delegate)Main; o = (System.Delegate)(() => { }); o = (System.Delegate)(delegate () { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void SynthesizedDelegateTypes_01() { var source = @"using System; class Program { static void M1<T>(T t) { var d = (ref T t) => t; Report(d); Console.WriteLine(d(ref t)); } static void M2<U>(U u) where U : struct { var d = (ref U u) => u; Report(d); Console.WriteLine(d(ref u)); } static void M3(double value) { var d = (ref double d) => d; Report(d); Console.WriteLine(d(ref value)); } static void Main() { M1(41); M2(42f); M2(43d); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] 41 <>F{00000001}`2[System.Single,System.Single] 42 <>F{00000001}`2[System.Double,System.Double] 43 "); verifier.VerifyIL("Program.M1<T>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__0<T> Program.<>c__0<T>.<>9"" IL_000e: ldftn ""T Program.<>c__0<T>.<M1>b__0_0(ref T)"" IL_0014: newobj ""<>F{00000001}<T, T>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""T <>F{00000001}<T, T>.Invoke(ref T)"" IL_002c: box ""T"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M2<U>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__1<U> Program.<>c__1<U>.<>9"" IL_000e: ldftn ""U Program.<>c__1<U>.<M2>b__1_0(ref U)"" IL_0014: newobj ""<>F{00000001}<U, U>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""U <>F{00000001}<U, U>.Invoke(ref U)"" IL_002c: box ""U"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M3", @"{ // Code size 50 (0x32) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""double Program.<>c.<M3>b__2_0(ref double)"" IL_0014: newobj ""<>F{00000001}<double, double>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""double <>F{00000001}<double, double>.Invoke(ref double)"" IL_002c: call ""void System.Console.WriteLine(double)"" IL_0031: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes(); var variables = nodes.OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(3, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<T, T> d", "T <>F{00000001}<T, T>.Invoke(ref T)"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<U, U> d", "U <>F{00000001}<U, U>.Invoke(ref U)"); VerifyLocalDelegateType(model, variables[2], "<>F{00000001}<System.Double, System.Double> d", "System.Double <>F{00000001}<System.Double, System.Double>.Invoke(ref System.Double)"); var identifiers = nodes.OfType<InvocationExpressionSyntax>().Where(i => i.Expression is IdentifierNameSyntax id && id.Identifier.Text == "Report").Select(i => i.ArgumentList.Arguments[0].Expression).ToArray(); Assert.Equal(3, identifiers.Length); VerifyExpressionType(model, identifiers[0], "<>F{00000001}<T, T> d", "<>F{00000001}<T, T>"); VerifyExpressionType(model, identifiers[1], "<>F{00000001}<U, U> d", "<>F{00000001}<U, U>"); VerifyExpressionType(model, identifiers[2], "<>F{00000001}<System.Double, System.Double> d", "<>F{00000001}<System.Double, System.Double>"); } [Fact] public void SynthesizedDelegateTypes_02() { var source = @"using System; class Program { static void M1(A a, int value) { var d = a.F1; d() = value; } static void M2(B b, float value) { var d = b.F2; d() = value; } static void Main() { var a = new A(); M1(a, 41); var b = new B(); M2(b, 42f); Console.WriteLine((a._f, b._f)); } } class A { public int _f; public ref int F1() => ref _f; } class B { public float _f; } static class E { public static ref float F2(this B b) => ref b._f; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"(41, 42)"); verifier.VerifyIL("Program.M1", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref int A.F1()"" IL_0007: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref int <>F{00000001}<int>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.i4 IL_0013: ret }"); verifier.VerifyIL("Program.M2", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref float E.F2(B)"" IL_0007: newobj ""<>F{00000001}<float>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref float <>F{00000001}<float>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.r4 IL_0013: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(2, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<System.Int32> d", "ref System.Int32 <>F{00000001}<System.Int32>.Invoke()"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<System.Single> d", "ref System.Single <>F{00000001}<System.Single>.Invoke()"); } [Fact] public void SynthesizedDelegateTypes_03() { var source = @"using System; class Program { static void Main() { Report((ref int x, int y) => { }); Report((int x, ref int y) => { }); Report((ref float x, int y) => { }); Report((float x, ref int y) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`2[System.Int32,System.Int32] <>A{00000004}`2[System.Int32,System.Int32] <>A{00000001}`2[System.Single,System.Int32] <>A{00000004}`2[System.Single,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__0_0(ref int, int)"" IL_0014: newobj ""<>A{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__0_1(int, ref int)"" IL_0038: newobj ""<>A{00000004}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__0_2(ref float, int)"" IL_005c: newobj ""<>A{00000001}<float, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__0_3(float, ref int)"" IL_0080: newobj ""<>A{00000004}<float, int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_04() { var source = @"using System; class Program { static int i = 0; static void Main() { Report(int () => i); Report((ref int () => ref i)); Report((ref readonly int () => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__1_0()"" IL_0014: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__1_1()"" IL_0038: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__1_2()"" IL_005c: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_05() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { Report(F1); Report(F2); Report(F3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 52 (0x34) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""int Program.F1()"" IL_0007: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""ref int Program.F2()"" IL_0018: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""ref readonly int Program.F3()"" IL_0029: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ret }"); } [Fact] public void SynthesizedDelegateTypes_06() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { var d1 = F1; var d2 = F2; var d3 = F3; Report(d1); Report(d2); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); } [Fact] public void SynthesizedDelegateTypes_07() { var source = @"using System; class Program { static void Main() { Report(int (ref int i) => i); Report((ref int (ref int i) => ref i)); Report((ref readonly int (ref int i) => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] <>F{00000005}`2[System.Int32,System.Int32] <>F{0000000d}`2[System.Int32,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__0_0(ref int)"" IL_0014: newobj ""<>F{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__0_1(ref int)"" IL_0038: newobj ""<>F{00000005}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__0_2(ref int)"" IL_005c: newobj ""<>F{0000000d}<int, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_08() { var source = @"#pragma warning disable 414 using System; class Program { static int i = 0; static void Main() { Report((int i) => { }); Report((out int i) => { i = 0; }); Report((ref int i) => { }); Report((in int i) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__1_0(int)"" IL_0014: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__1_1(out int)"" IL_0038: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__1_2(ref int)"" IL_005c: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__1_3(in int)"" IL_0080: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_09() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { Report(M1); Report(M2); Report(M3); Report(M4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 69 (0x45) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""void Program.M1(int)"" IL_0007: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""void Program.M2(out int)"" IL_0018: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""void Program.M3(ref int)"" IL_0029: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ldnull IL_0034: ldftn ""void Program.M4(in int)"" IL_003a: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_003f: call ""void Program.Report(System.Delegate)"" IL_0044: ret }"); } [Fact] public void SynthesizedDelegateTypes_10() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { var d1 = M1; var d2 = M2; var d3 = M3; var d4 = M4; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_11() { var source = @"class Program { unsafe static void Main() { var d1 = int* () => (int*)42; var d2 = (int* p) => { }; var d3 = delegate*<void> () => default; var d4 = (delegate*<void> d) => { }; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (5,18): error CS8917: The delegate type could not be inferred. // var d1 = int* () => (int*)42; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "int* () => (int*)42").WithLocation(5, 18), // (6,18): error CS8917: The delegate type could not be inferred. // var d2 = (int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int* p) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d3 = delegate*<void> () => default; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "delegate*<void> () => default").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d4 = (delegate*<void> d) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(delegate*<void> d) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [ConditionalFact(typeof(DesktopOnly))] public void SynthesizedDelegateTypes_12() { var source = @"using System; class Program { static void Main() { var d1 = (TypedReference x) => { }; var d2 = (int x, RuntimeArgumentHandle y) => { }; var d3 = (ArgIterator x) => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = (TypedReference x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(TypedReference x) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d2 = (int x, RuntimeArgumentHandle y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, RuntimeArgumentHandle y) => { }").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d3 = (ArgIterator x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ArgIterator x) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_13() { var source = @"ref struct S<T> { } class Program { static void F1(int x, S<int> y) { } static S<T> F2<T>() => throw null; static void Main() { var d1 = F1; var d2 = F2<object>; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8917: The delegate type could not be inferred. // var d1 = F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(8, 18), // (9,18): error CS8917: The delegate type could not be inferred. // var d2 = F2<object>; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2<object>").WithLocation(9, 18)); } [Fact] public void SynthesizedDelegateTypes_14() { var source = @"class Program { static ref void F() { } static void Main() { var d1 = F; var d2 = (ref void () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (3,16): error CS1547: Keyword 'void' cannot be used in this context // static ref void F() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(3, 16), // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(6, 18), // (7,19): error CS8917: The delegate type could not be inferred. // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 19), // (7,23): error CS1547: Keyword 'void' cannot be used in this context // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 23)); } [Fact] public void SynthesizedDelegateTypes_15() { var source = @"using System; unsafe class Program { static byte*[] F1() => null; static void F2(byte*[] a) { } static byte*[] F3(ref int i) => null; static void F4(ref byte*[] a) { } static void Main() { Report(int*[] () => null); Report((int*[] a) => { }); Report(int*[] (ref int i) => null); Report((ref int*[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32*[]] System.Action`1[System.Int32*[]] <>F{00000001}`2[System.Int32,System.Int32*[]] <>A{00000001}`1[System.Int32*[]] System.Func`1[System.Byte*[]] System.Action`1[System.Byte*[]] <>F{00000001}`2[System.Int32,System.Byte*[]] <>A{00000001}`1[System.Byte*[]] "); } [Fact] public void SynthesizedDelegateTypes_16() { var source = @"using System; unsafe class Program { static delegate*<ref int>[] F1() => null; static void F2(delegate*<ref int, void>[] a) { } static delegate*<ref int>[] F3(ref int i) => null; static void F4(ref delegate*<ref int, void>[] a) { } static void Main() { Report(delegate*<int, ref int>[] () => null); Report((delegate*<int, ref int, void>[] a) => { }); Report(delegate*<int, ref int>[] (ref int i) => null); Report((ref delegate*<int, ref int, void>[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] "); } [Fact] public void SynthesizedDelegateTypes_17() { var source = @"#nullable enable using System; class Program { static void F1(object x, dynamic y) { } static void F2(IntPtr x, nint y) { } static void F3((int x, int y) t) { } static void F4(object? x, object?[] y) { } static void F5(ref object x, dynamic y) { } static void F6(IntPtr x, ref nint y) { } static void F7(ref (int x, int y) t) { } static void F8(object? x, ref object?[] y) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); Report(F5); Report(F6); Report(F7); Report(F8); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`2[System.Object,System.Object] System.Action`2[System.IntPtr,System.IntPtr] System.Action`1[System.ValueTuple`2[System.Int32,System.Int32]] System.Action`2[System.Object,System.Object[]] <>A{00000001}`2[System.Object,System.Object] <>A{00000004}`2[System.IntPtr,System.IntPtr] <>A{00000001}`1[System.ValueTuple`2[System.Int32,System.Int32]] <>A{00000004}`2[System.Object,System.Object[]] "); } /// <summary> /// Synthesized delegate types should only be emitted if used. /// </summary> [Fact] [WorkItem(55896, "https://github.com/dotnet/roslyn/issues/55896")] public void SynthesizedDelegateTypes_18() { var source = @"using System; delegate void D2(object x, ref object y); delegate void D4(out object x, ref object y); class Program { static void F1(ref object x, object y) { } static void F2(object x, ref object y) { } static void Main() { var d1 = F1; D2 d2 = F2; var d3 = (ref object x, out object y) => { y = null; }; D4 d4 = (out object x, ref object y) => { x = null; }; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, validator: validator, expectedOutput: @"<>A{00000001}`2[System.Object,System.Object] D2 <>A{00000009}`2[System.Object,System.Object] D4"); static void validator(PEAssembly assembly) { var reader = assembly.GetMetadataReader(); var actualTypes = reader.GetTypeDefNames().Select(h => reader.GetString(h)).ToArray(); // https://github.com/dotnet/roslyn/issues/55896: Should not include <>A{00000004}`2 or <>A{00000006}`2. string[] expectedTypes = new[] { "<Module>", "<>A{00000001}`2", "<>A{00000004}`2", "<>A{00000006}`2", "<>A{00000009}`2", "D2", "D4", "Program", "<>c", }; AssertEx.Equal(expectedTypes, actualTypes); } } private static void VerifyLocalDelegateType(SemanticModel model, VariableDeclaratorSyntax variable, string expectedLocal, string expectedInvokeMethod) { var local = (ILocalSymbol)model.GetDeclaredSymbol(variable)!; Assert.Equal(expectedLocal, local.ToTestDisplayString()); var delegateType = ((INamedTypeSymbol)local.Type); Assert.Equal(Accessibility.Internal, delegateType.DeclaredAccessibility); Assert.Equal(expectedInvokeMethod, delegateType.DelegateInvokeMethod.ToTestDisplayString()); } private static void VerifyExpressionType(SemanticModel model, ExpressionSyntax variable, string expectedSymbol, string expectedType) { var symbol = model.GetSymbolInfo(variable).Symbol; Assert.Equal(expectedSymbol, symbol.ToTestDisplayString()); var type = model.GetTypeInfo(variable).Type; Assert.Equal(expectedType, type.ToTestDisplayString()); } [Fact] public void TaskRunArgument() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Run(() => { }); } }"; var verifier = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview); var method = (MethodSymbol)verifier.TestData.GetMethodsByName()["Program.<>c.<F>b__0_0()"].Method; Assert.Equal("void Program.<>c.<F>b__0_0()", method.ToTestDisplayString()); verifier.VerifyIL("Program.<>c.<F>b__0_0()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } } }
// 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 System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTypeTests : CSharpTestBase { private const string s_utils = @"using System; using System.Linq; static class Utils { internal static string GetDelegateMethodName(this Delegate d) { var method = d.Method; return Concat(GetTypeName(method.DeclaringType), method.Name); } internal static string GetDelegateTypeName(this Delegate d) { return d.GetType().GetTypeName(); } internal static string GetTypeName(this Type type) { if (type.IsArray) { return GetTypeName(type.GetElementType()) + ""[]""; } string typeName = type.Name; int index = typeName.LastIndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } typeName = Concat(type.Namespace, typeName); if (!type.IsGenericType) { return typeName; } return $""{typeName}<{string.Join("", "", type.GetGenericArguments().Select(GetTypeName))}>""; } private static string Concat(string container, string name) { return string.IsNullOrEmpty(container) ? name : container + ""."" + name; } }"; private static readonly string s_expressionOfTDelegateTypeName = ExecutionConditionUtil.IsDesktop ? "System.Linq.Expressions.Expression`1" : "System.Linq.Expressions.Expression0`1"; [Fact] public void LanguageVersion() { var source = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 13), // (9,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 48)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversions_01() { var source = @"using System; class Program { static void Main() { object o = Main; ICloneable c = Main; Delegate d = Main; MulticastDelegate m = Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 20), // (7,24): error CS0428: Cannot convert method group 'Main' to non-delegate type 'ICloneable'. Did you intend to invoke the method? // ICloneable c = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // Delegate d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(8, 22), // (9,31): error CS0428: Cannot convert method group 'Main' to non-delegate type 'MulticastDelegate'. Did you intend to invoke the method? // MulticastDelegate m = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)Main; var c = (ICloneable)Main; var d = (Delegate)Main; var m = (MulticastDelegate)Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,17): error CS0030: Cannot convert type 'method' to 'object' // var o = (object)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)Main").WithArguments("method", "object").WithLocation(6, 17), // (7,17): error CS0030: Cannot convert type 'method' to 'ICloneable' // var c = (ICloneable)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(ICloneable)Main").WithArguments("method", "System.ICloneable").WithLocation(7, 17), // (8,17): error CS0030: Cannot convert type 'method' to 'Delegate' // var d = (Delegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Delegate)Main").WithArguments("method", "System.Delegate").WithLocation(8, 17), // (9,17): error CS0030: Cannot convert type 'method' to 'MulticastDelegate' // var m = (MulticastDelegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(MulticastDelegate)Main").WithArguments("method", "System.MulticastDelegate").WithLocation(9, 17)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_03() { var source = @"class Program { static void Main() { System.Linq.Expressions.Expression e = F; e = (System.Linq.Expressions.Expression)F; } static int F() => 1; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0030: Cannot convert type 'method' to 'Expression' // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.Expression)F").WithArguments("method", "System.Linq.Expressions.Expression").WithLocation(6, 13)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.Expression)F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(6, 13)); } [Fact] public void MethodGroupConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void F() { } static void F(object o) { } static void Main() { object o = F; ICloneable c = F; Delegate d = F; MulticastDelegate m = F; Expression e = F; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,20): error CS8917: The delegate type could not be inferred. // object o = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(9, 20), // (10,24): error CS8917: The delegate type could not be inferred. // ICloneable c = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(10, 24), // (11,22): error CS8917: The delegate type could not be inferred. // Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(11, 22), // (12,31): error CS8917: The delegate type could not be inferred. // MulticastDelegate m = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(12, 31), // (13,24): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(13, 24)); } [Fact] public void LambdaConversions_01() { var source = @"using System; class Program { static void Main() { object o = () => { }; ICloneable c = () => { }; Delegate d = () => { }; MulticastDelegate m = () => { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // ICloneable c = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)(() => { }); var c = (ICloneable)(() => { }); var d = (Delegate)(() => { }); var m = (MulticastDelegate)(() => { }); Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,26): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // var o = (object)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 26), // (7,30): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // var c = (ICloneable)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 30), // (8,28): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var d = (Delegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 28), // (9,37): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // var m = (MulticastDelegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_03() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression e = () => 1; Report(e); e = (Expression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(7, 24), // (9,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 26)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Delegate d = x => x; object o = (object)(x => x); Expression e = x => x; e = (Expression)(x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 22), // (8,29): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "object").WithLocation(8, 29), // (9,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 24), // (10,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(10, 26)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,22): error CS8917: The delegate type could not be inferred. // Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(7, 22), // (8,29): error CS8917: The delegate type could not be inferred. // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 29), // (9,24): error CS8917: The delegate type could not be inferred. // Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 24), // (10,26): error CS8917: The delegate type could not be inferred. // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(10, 26)); } [Fact] public void LambdaConversions_05() { var source = @"using System; class Program { static void Main() { System.Delegate d = () => Main; System.Linq.Expressions.Expression e = () => Main; Report(d); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Action] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Action]] "); } [Fact] public void AnonymousMethod_01() { var source = @"using System; class Program { static void Main() { object o = delegate () { }; ICloneable c = delegate () { }; Delegate d = delegate () { }; MulticastDelegate m = delegate () { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert anonymous method to type 'object' because it is not a delegate type // object o = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert anonymous method to type 'ICloneable' because it is not a delegate type // ICloneable c = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // Delegate d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert anonymous method to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void DynamicConversion() { var source = @"using System; class Program { static void Main() { dynamic d; d = Main; d = () => 1; } static void Report(dynamic d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'dynamic'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "dynamic").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert lambda expression to type 'dynamic' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "dynamic").WithLocation(8, 13)); } private static IEnumerable<object?[]> GetMethodGroupData(Func<string, string, DiagnosticDescription[]> getExpectedDiagnostics) { yield return getData("static int F() => 0;", "Program.F", "F", "System.Func<System.Int32>"); yield return getData("static int F() => 0;", "F", "F", "System.Func<System.Int32>"); yield return getData("int F() => 0;", "(new Program()).F", "F", "System.Func<System.Int32>"); yield return getData("static T F<T>() => default;", "Program.F<int>", "F", "System.Func<System.Int32>"); yield return getData("static void F<T>() where T : class { }", "F<object>", "F", "System.Action"); yield return getData("static void F<T>() where T : struct { }", "F<int>", "F", "System.Action"); yield return getData("T F<T>() => default;", "(new Program()).F<int>", "F", "System.Func<System.Int32>"); yield return getData("T F<T>() => default;", "(new Program()).F", "F", null); yield return getData("void F<T>(T t) { }", "(new Program()).F<string>", "F", "System.Action<System.String>"); yield return getData("void F<T>(T t) { }", "(new Program()).F", "F", null); yield return getData("static ref int F() => throw null;", "F", "F", "<>F{00000001}<System.Int32>"); yield return getData("static ref readonly int F() => throw null;", "F", "F", "<>F{00000003}<System.Int32>"); yield return getData("static void F() { }", "F", "F", "System.Action"); yield return getData("static void F(int x, int y) { }", "F", "F", "System.Action<System.Int32, System.Int32>"); yield return getData("static void F(out int x, int y) { x = 0; }", "F", "F", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("static void F(int x, ref int y) { }", "F", "F", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("static void F(int x, in int y) { }", "F", "F", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "F", "F", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "F", "F", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => null;", "F", "F", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Object>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => null;", "F", "F", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); object?[] getData(string methodDeclaration, string methodGroupExpression, string methodGroupOnly, string? expectedType) => new object?[] { methodDeclaration, methodGroupExpression, expectedType is null ? getExpectedDiagnostics(methodGroupExpression, methodGroupOnly) : null, expectedType }; } public static IEnumerable<object?[]> GetMethodGroupImplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; }); } [Theory] [MemberData(nameof(GetMethodGroupImplicitConversionData))] public void MethodGroup_ImplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetMethodGroupExplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, $"(System.Delegate){methodGroupExpression}").WithArguments("method", "System.Delegate").WithLocation(6, 20) }; }); } [Theory] [MemberData(nameof(GetMethodGroupExplicitConversionData))] public void MethodGroup_ExplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ object o = (System.Delegate){methodGroupExpression}; System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/52874: GetTypeInfo() for method group should return inferred delegate type. Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } public static IEnumerable<object?[]> GetLambdaData() { yield return getData("x => x", null); yield return getData("x => { return x; }", null); yield return getData("x => ref args[0]", null); yield return getData("(x, y) => { }", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("() => ref args[0]", "<>F{00000001}<System.String>"); yield return getData("() => { }", "System.Action"); yield return getData("(int x, int y) => { }", "System.Action<System.Int32, System.Int32>"); yield return getData("(out int x, int y) => { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("(int x, ref int y) => { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("(int x, in int y) => { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); yield return getData("async () => { await System.Threading.Tasks.Task.Delay(0); }", "System.Func<System.Threading.Tasks.Task>"); yield return getData("static async () => { await System.Threading.Tasks.Task.Delay(0); return 0; }", "System.Func<System.Threading.Tasks.Task<System.Int32>>"); yield return getData("() => Main", "System.Func<System.Action<System.String[]>>"); yield return getData("(int x) => x switch { _ => null }", null); yield return getData("_ => { }", null); yield return getData("_ => _", null); yield return getData("() => throw null", null); yield return getData("x => throw null", null); yield return getData("(int x) => throw null", null); yield return getData("() => { throw null; }", "System.Action"); yield return getData("(int x) => { throw null; }", "System.Action<System.Int32>"); yield return getData("(string s) => { if (s.Length > 0) return s; return null; }", "System.Func<System.String, System.String>"); yield return getData("(string s) => { if (s.Length > 0) return default; return s; }", "System.Func<System.String, System.String>"); yield return getData("(int i) => { if (i > 0) return i; return default; }", "System.Func<System.Int32, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return x; return y; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return y; return x; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("object () => default", "System.Func<System.Object>"); yield return getData("void () => { }", "System.Action"); // These two lambdas have different signatures but produce the same delegate names: https://github.com/dotnet/roslyn/issues/55570 yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, ref int _17) => { }", "<>A{00000000}<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32>"); yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, in int _17) => { }", "<>A{00000000}<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } public static IEnumerable<object?[]> GetAnonymousMethodData() { yield return getData("delegate { }", null); yield return getData("delegate () { return 1; }", "System.Func<System.Int32>"); yield return getData("delegate () { return ref args[0]; }", "<>F{00000001}<System.String>"); yield return getData("delegate () { }", "System.Action"); yield return getData("delegate (int x, int y) { }", "System.Action<System.Int32, System.Int32>"); yield return getData("delegate (out int x, int y) { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("delegate (int x, ref int y) { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("delegate (int x, in int y) { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { return _1; }", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { return _1; }", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Delegate d = {anonymousFunction}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 29)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal(expectedType, typeInfo.Type.ToTestDisplayString()); } Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Delegate)({anonymousFunction}); System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,38): error CS8917: The delegate type could not be inferred. // object o = (System.Delegate)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 38)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(expectedType, typeInfo.ConvertedType?.ToTestDisplayString()); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } private static bool HaveMatchingSignatures(IMethodSymbol methodA, IMethodSymbol methodB) { return MemberSignatureComparer.MethodGroupSignatureComparer.Equals(methodA.GetSymbol<MethodSymbol>(), methodB.GetSymbol<MethodSymbol>()); } public static IEnumerable<object?[]> GetExpressionData() { yield return getData("x => x", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Linq.Expressions.Expression e = {anonymousFunction}; }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,48): error CS8917: The delegate type could not be inferred. // System.Linq.Expressions.Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 48)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.Type.ToTestDisplayString()); } Assert.Equal("System.Linq.Expressions.Expression", typeInfo.ConvertedType!.ToTestDisplayString()); } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Linq.Expressions.Expression)({anonymousFunction}); }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,57): error CS8917: The delegate type could not be inferred. // object o = (System.Linq.Expressions.Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 57)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); if (expectedType is null) { Assert.Null(typeInfo.ConvertedType); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.ConvertedType.ToTestDisplayString()); } } /// <summary> /// Should bind and report diagnostics from anonymous method body /// regardless of whether the delegate type can be inferred. /// </summary> [Fact] public void AnonymousMethodBodyErrors() { var source = @"using System; class Program { static void Main() { Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Delegate d1 = (object x1) => { _ = x1.Length; }; Delegate d2 = (ref object x2) => { _ = x2.Length; }; Delegate d3 = delegate (object x3) { _ = x3.Length; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,23): error CS8917: The delegate type could not be inferred. // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }").WithLocation(6, 23), // (6,68): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(6, 68), // (7,47): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d1 = (object x1) => { _ = x1.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(7, 47), // (8,51): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(8, 51), // (9,53): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d3 = delegate (object x3) { _ = x3.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(9, 53)); } public static IEnumerable<object?[]> GetBaseAndDerivedTypesData() { yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // instance and static // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "this.F", "F", new[] { // (5,29): error CS0176: Member 'B.F(object)' cannot be accessed with an instance reference; qualify it with a type name instead // System.Delegate d = this.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.F").WithArguments("B.F(object)").WithLocation(5, 29) }); // instance and static #endif yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "base.F", "F"); // static and instance yield return getData("internal void F(object x) { }", "internal static void F() { }", "F", "F"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "B.F", "F", null, "System.Action"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "this.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "F", "F"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "B.F", "F", null, "System.Action"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "base.F", "F"); // static and instance, different number of parameters yield return getData("internal static void F(object x) { }", "private static void F() { }", "F", "F"); // internal and private yield return getData("private static void F(object x) { }", "internal static void F() { }", "F", "F", null, "System.Action"); // internal and private yield return getData("internal abstract void F(object x);", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal virtual void F(object x) { }", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal void F(object x) { }", "internal void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object y) { }", "F", "F", null, "System.Action<System.Object>"); // different parameter name yield return getData("internal void F(object x) { }", "internal void F(string x) { }", "F", "F"); // different parameter type yield return getData("internal void F(object x) { }", "internal void F(object x, object y) { }", "F", "F"); // different number of parameters yield return getData("internal void F(object x) { }", "internal void F(ref object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal void F(ref object x) { }", "internal void F(object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal abstract object F();", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal virtual object F() => throw null;", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal object F() => throw null;", "internal object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal object F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal string F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return type yield return getData("internal object F() => throw null;", "internal new ref object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal ref object F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal void F(object x) { }", "internal new void F(dynamic x) { }", "F", "F", null, "System.Action<System.Object>"); // object/dynamic yield return getData("internal dynamic F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // object/dynamic yield return getData("internal void F((object, int) x) { }", "internal new void F((object a, int b) x) { }", "F", "F", null, "System.Action<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal (object a, int b) F() => throw null;", "internal new (object, int) F() => throw null;", "F", "F", null, "System.Func<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal void F(System.IntPtr x) { }", "internal new void F(nint x) { }", "F", "F", null, "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal nint F() => throw null;", "internal new System.IntPtr F() => throw null;", "F", "F", null, "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal void F(object x) { }", @"#nullable enable internal new void F(object? x) { } #nullable disable", "F", "F", null, "System.Action<System.Object>"); // different nullability yield return getData( @"#nullable enable internal object? F() => throw null!; #nullable disable", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // different nullability yield return getData("internal void F() { }", "internal void F<T>() { }", "F", "F"); // different arity yield return getData("internal void F() { }", "internal void F<T>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F", "F"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int, object>", "F<int, object>", null, "System.Action"); // different arity yield return getData("internal void F<T>(T t) { }", "internal new void F<U>(U u) { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter names yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "base.F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter constraints // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<object>", "F<object>", new[] { // (5,29): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // System.Delegate d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(5, 29) }); // different type parameter constraints #endif static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedType }; } } [Theory] [MemberData(nameof(GetBaseAndDerivedTypesData))] public void MethodGroup_BaseAndDerivedTypes(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"partial class B {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} static void Main() {{ new B().M(); }} }} abstract class A {{ {methodA} }} partial class B : A {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetExtensionMethodsSameScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "B.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (5,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(5, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsSameScopeData))] public void MethodGroup_ExtensionMethodsSameScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} static class B {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } public static IEnumerable<object?[]> GetExtensionMethodsDifferentScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this object x) { }", "this.F", "F", null, "A.F", "System.Action"); // hiding yield return getData("internal static void F(this object x) { }", "internal static void F(this object y) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter name yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, System.IntPtr y) { }", "internal static void F(this object x, nint y) { }", "this.F", "F", null, "A.F", "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static nint F(this object x) => throw null;", "internal static System.IntPtr F(this object x) => throw null;", "this.F", "F", null, "A.F", "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "N.B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (6,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(6, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsDifferentScopeData))] public void MethodGroup_ExtensionMethodsDifferentScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"using N; class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} namespace N {{ static class B {{ {methodB} }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } [Fact] public void InstanceMethods_01() { var source = @"using System; class Program { object F1() => null; void F2(object x, int y) { } void F() { Delegate d1 = F1; Delegate d2 = this.F2; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } static void Main() { new Program().F(); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Func<System.Object>, System.Action<System.Object, System.Int32>"); } [Fact] public void InstanceMethods_02() { var source = @"using System; class A { protected virtual void F() { Console.WriteLine(nameof(A)); } } class B : A { protected override void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_03() { var source = @"using System; class A { protected void F() { Console.WriteLine(nameof(A)); } } class B : A { protected new void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_04() { var source = @"class Program { T F<T>() => default; static void Main() { var p = new Program(); System.Delegate d = p.F; object o = (System.Delegate)p.F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,31): error CS8917: The delegate type could not be inferred. // System.Delegate d = p.F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 31), // (8,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)p.F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Delegate)p.F").WithArguments("method", "System.Delegate").WithLocation(8, 20)); } [Fact] public void MethodGroup_Inaccessible() { var source = @"using System; class A { private static void F() { } internal static void F(object o) { } } class B { static void Main() { Delegate d = A.F; Console.WriteLine(d.GetDelegateTypeName()); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Action<System.Object>"); } [Fact] public void MethodGroup_IncorrectArity() { var source = @"class Program { static void F0(object o) { } static void F0<T>(object o) { } static void F1(object o) { } static void F1<T, U>(object o) { } static void F2<T>(object o) { } static void F2<T, U>(object o) { } static void Main() { System.Delegate d; d = F0<int, object>; d = F1<int>; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,13): error CS0308: The non-generic method 'Program.F0(object)' cannot be used with type arguments // d = F0<int, object>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F0<int, object>").WithArguments("Program.F0(object)", "method").WithLocation(12, 13), // (13,13): error CS0308: The non-generic method 'Program.F1(object)' cannot be used with type arguments // d = F1<int>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F1<int>").WithArguments("Program.F1(object)", "method").WithLocation(13, 13), // (14,13): error CS8917: The delegate type could not be inferred. // d = F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 13)); } [Fact] public void ExtensionMethods_01() { var source = @"static class E { internal static void F1(this object x, int y) { } internal static void F2(this object x) { } } class Program { void F2(int x) { } static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 15)); } [Fact] public void ExtensionMethods_02() { var source = @"using System; static class E { internal static void F(this System.Type x, int y) { } internal static void F(this string x) { } } class Program { static void Main() { Delegate d1 = typeof(Program).F; Delegate d2 = """".F; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action<System.Int32>, System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => d.Initializer!.Value).ToArray(); Assert.Equal(2, exprs.Length); foreach (var expr in exprs) { var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } } [Fact] public void ExtensionMethods_03() { var source = @"using N; namespace N { static class E1 { internal static void F1(this object x, int y) { } internal static void F2(this object x, int y) { } internal static void F2(this object x) { } internal static void F3(this object x) { } } } static class E2 { internal static void F1(this object x) { } } class Program { static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; d = p.F3; d = E1.F1; d = E2.F1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (22,15): error CS8917: The delegate type could not be inferred. // d = p.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(22, 15), // (23,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(23, 15)); } [Fact] public void ExtensionMethods_04() { var source = @"static class E { internal static void F1(this object x, int y) { } } static class Program { static void F2(this object x) { } static void Main() { System.Delegate d; d = E.F1; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void ExtensionMethods_05() { var source = @"using System; static class E { internal static void F(this A a) { } } class A { } class B : A { static void Invoke(Delegate d) { } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,16): error CS0103: The name 'F' does not exist in the current context // Invoke(F); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(14, 16), // (16,21): error CS0117: 'A' does not contain a definition for 'F' // Invoke(base.F); Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("A", "F").WithLocation(16, 21)); } [Fact] public void ExtensionMethods_06() { var source = @"static class E { internal static void F1<T>(this object x, T y) { } internal static void F2<T, U>(this T t) { } } class Program { static void F<T>(T t) where T : class { System.Delegate d; d = t.F1; d = t.F2; d = t.F1<int>; d = t.F1<T>; d = t.F2<T, object>; d = t.F2<object, T>; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,15): error CS8917: The delegate type could not be inferred. // d = t.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(11, 15), // (12,15): error CS8917: The delegate type could not be inferred. // d = t.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(12, 15)); } /// <summary> /// Method group with dynamic receiver does not use method group conversion. /// </summary> [Fact] public void DynamicReceiver() { var source = @"using System; class Program { void F() { } static void Main() { dynamic d = new Program(); object obj; try { obj = d.F; } catch (Exception e) { obj = e; } Console.WriteLine(obj.GetType().FullName); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, references: new[] { CSharpRef }, expectedOutput: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"); } // System.Func<> and System.Action<> cannot be used as the delegate type // when the parameters or return type are not valid type arguments. [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void InvalidTypeArguments() { var source = @"unsafe class Program { static int* F() => throw null; static void Main() { System.Delegate d; d = F; d = (int x, int* y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,13): error CS8917: The delegate type could not be inferred. // d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = (int x, int* y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, int* y) => { }").WithLocation(8, 13)); } [Fact] public void GenericDelegateType() { var source = @"using System; class Program { static void Main() { Delegate d = F<int>(); Console.WriteLine(d.GetDelegateTypeName()); } unsafe static Delegate F<T>() { return (T t, int* p) => { }; } }"; // When we synthesize delegate types with parameter types (such as int*) that cannot // be used as type arguments, run the program to report the actual delegate type. var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (11,16): error CS8917: The delegate type could not be inferred. // return (T t, int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(T t, int* p) => { }").WithLocation(11, 16)); } [Fact] public void Member_01() { var source = @"using System; class Program { static void Main() { Console.WriteLine((() => { }).GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0023: Operator '.' cannot be applied to operand of type 'lambda expression' // Console.WriteLine((() => { }).GetType()); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(() => { }).GetType").WithArguments(".", "lambda expression").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void Member_02() { var source = @"using System; class Program { static void Main() { Console.WriteLine(Main.GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0119: 'Program.Main()' is a method, which is not valid in the given context // Console.WriteLine(Main.GetType()); Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_01() { var sourceA = @".class public A { .method public static void F1(object modopt(int32) x) { ldnull throw } .method public static object modopt(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Action<System.Object> System.Func<System.Object>"); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_02() { var sourceA = @".class public A { .method public static void F1(object modreq(int32) x) { ldnull throw } .method public static object modreq(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,16): error CS0570: 'A.F1(object)' is not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F1").WithArguments("A.F1(object)").WithLocation(10, 16), // (10,16): error CS0648: '' is a type not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BogusType, "A.F1").WithArguments("").WithLocation(10, 16), // (11,16): error CS0570: 'A.F2()' is not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F2").WithArguments("A.F2()").WithLocation(11, 16), // (11,16): error CS0648: '' is a type not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BogusType, "A.F2").WithArguments("").WithLocation(11, 16)); } [Fact] public void UnmanagedCallersOnlyAttribute_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = F; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] static void F() { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS8902: 'Program.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // Delegate d = F; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("Program.F()").WithLocation(8, 22)); } [Fact] public void UnmanagedCallersOnlyAttribute_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = new S().F; } } struct S { } static class E1 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] public static void F(this S s) { } } static class E2 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] public static void F(this S s) { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'E1.F(S)' and 'E2.F(S)' // Delegate d = new S().F; Diagnostic(ErrorCode.ERR_AmbigCall, "new S().F").WithArguments("E1.F(S)", "E2.F(S)").WithLocation(8, 22)); } [Fact] public void SystemActionAndFunc_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,13): error CS8917: The delegate type could not be inferred. // d = Main; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "Main").WithLocation(6, 13), // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (7,13): error CS0518: Predefined type 'System.Func`1' is not defined or imported // d = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Func`1").WithLocation(7, 13)); } private static MetadataReference GetCorlibWithInvalidActionAndFuncOfT() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Action`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance void Invoke(!T t) { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemActionAndFunc_UseSiteErrors() { var refA = GetCorlibWithInvalidActionAndFuncOfT(); var sourceB = @"class Program { static void F(object o) { } static void Main() { System.Delegate d; d = F; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (10,13): error CS0648: 'Func<T>' is a type not supported by the language // d = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(10, 13)); } [Fact] public void SystemLinqExpressionsExpression_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (5,48): error CS0518: Predefined type 'System.Linq.Expressions.Expression`1' is not defined or imported // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Linq.Expressions.Expression`1").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_UseSiteErrors() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Linq.Expressions.LambdaExpression { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0648: 'Expression<T>' is a type not supported by the language // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Linq.Expressions.Expression<T>").WithLocation(5, 48)); } // Expression<T> not derived from Expression. private static MetadataReference GetCorlibWithExpressionOfTNotDerivedType() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_01() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_02() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static T F<T>(T t) where T : System.Linq.Expressions.Expression => t; static void Main() { var e = F(() => 1); } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (6,17): error CS0311: The type 'System.Linq.Expressions.Expression<System.Func<int>>' cannot be used as type parameter 'T' in the generic type or method 'Program.F<T>(T)'. There is no implicit reference conversion from 'System.Linq.Expressions.Expression<System.Func<int>>' to 'System.Linq.Expressions.Expression'. // var e = F(() => 1); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "F").WithArguments("Program.F<T>(T)", "System.Linq.Expressions.Expression", "T", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(6, 17)); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_01() { var source = @"using System; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Action<string> a) { Console.WriteLine(""M(Action<string> a)""); } static void F(object o) { } static void Main() { M(F); // C#9: M(Action<string>) } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "M(Action<string> a)"); // Breaking change from C#9 which binds to M(Action<string> a). CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: "M<T>(T t)"); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_02() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(object y) { Console.WriteLine(""C.M(object y)""); } } static class E { public static void M(this object x, Action y) { Console.WriteLine(""E.M(object x, Action y)""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M(object x, Action y) E.M(object x, Action y) "); // Breaking change from C#9 which binds to E.M(object x, Action y). CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"C.M(object y) C.M(object y) "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_03() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(Delegate d) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Action a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M E.M "); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M C.M "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var c = new C(); c.M(() => 1); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M"); } [Fact] public void OverloadResolution_05() { var source = @"using System; class Program { static void Report(string name) { Console.WriteLine(name); } static void FA(Delegate d) { Report(""FA(Delegate)""); } static void FA(Action d) { Report(""FA(Action)""); } static void FB(Delegate d) { Report(""FB(Delegate)""); } static void FB(Func<int> d) { Report(""FB(Func<int>)""); } static void F1() { } static int F2() => 0; static void Main() { FA(F1); FA(F2); FB(F1); FB(F2); FA(() => { }); FA(() => 0); FB(() => { }); FB(() => 0); FA(delegate () { }); FA(delegate () { return 0; }); FB(delegate () { }); FB(delegate () { return 0; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FA(F2); Diagnostic(ErrorCode.ERR_BadArgType, "F2").WithArguments("1", "method group", "System.Delegate").WithLocation(14, 12), // (15,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FB(F1); Diagnostic(ErrorCode.ERR_BadArgType, "F1").WithArguments("1", "method group", "System.Delegate").WithLocation(15, 12), // (18,18): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // FA(() => 0); Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(18, 18), // (19,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // FB(() => { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(19, 15), // (22,26): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // FA(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(22, 26), // (23,12): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // FB(delegate () { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(23, 12)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) "); } [Fact] public void OverloadResolution_06() { var source = @"using System; using System.Linq.Expressions; class Program { static void Report(string name, Expression e) { Console.WriteLine(""{0}: {1}"", name, e); } static void F(Expression e) { Report(""F(Expression)"", e); } static void F(Expression<Func<int>> e) { Report(""F(Expression<Func<int>>)"", e); } static void Main() { F(() => 0); F(() => string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // F(() => string.Empty); Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 17), // (11,17): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // F(() => string.Empty); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "string.Empty").WithArguments("lambda expression").WithLocation(11, 17)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"F(Expression<Func<int>>): () => 0 F(Expression): () => String.Empty "); } [Fact] public void OverloadResolution_07() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) { } static void F(Expression<Func<int>> e) { } static void Main() { F(delegate () { return 0; }); F(delegate () { return string.Empty; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 0; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return string.Empty; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(10, 11)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (9,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 0; }").WithLocation(9, 11), // (10,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return string.Empty; }").WithLocation(10, 11)); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_08() { var source = @"using System; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_09() { var source = @"using System; using System.Linq.Expressions; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Expression e) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Expression<Func<int, int>> e) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_10() { var source = @"using System; using static System.Console; class C { static object M1(object o) => o; static int M1(int i) => i; static int M2(int i) => i; static void Main() { var c = new C(); c.F(M1); c.F(M2); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [Fact] public void OverloadResolution_11() { var source = @"using System; using System.Linq.Expressions; class C { static object M1(object o) => o; static int M1(int i) => i; static void Main() { F1(x => x); F1(M1); F2(x => x); } static void F1(Delegate d) { } static void F2(Expression e) { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F1(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // F2(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 12)); var expectedDiagnostics10AndLater = new[] { // (9,12): error CS8917: The delegate type could not be inferred. // F1(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS8917: The delegate type could not be inferred. // F2(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 12) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_12() { var source = @"using System; #nullable enable var app = new WebApp(); app.Map(""/sub1"", builder => { builder.UseAuth(); }); app.Map(""/sub2"", (IAppBuilder builder) => { builder.UseAuth(); }); class WebApp : IAppBuilder, IRouteBuilder { public void UseAuth() { } } interface IAppBuilder { void UseAuth(); } interface IRouteBuilder { } static class AppBuilderExtensions { public static IAppBuilder Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) => app; } static class RouteBuilderExtensions { public static IRouteBuilder Map(this IRouteBuilder routes, string path, Delegate callback) => routes; } struct PathSring { public PathSring(string? path) { Path = path; } public string? Path { get; } public static implicit operator PathSring(string? s) => new PathSring(s); public static implicit operator string?(PathSring path) => path.Path; }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (8,5): error CS0121: The call is ambiguous between the following methods or properties: 'AppBuilderExtensions.Map(IAppBuilder, PathSring, Action<IAppBuilder>)' and 'RouteBuilderExtensions.Map(IRouteBuilder, string, Delegate)' // app.Map("/sub2", (IAppBuilder builder) => Diagnostic(ErrorCode.ERR_AmbigCall, "Map").WithArguments("AppBuilderExtensions.Map(IAppBuilder, PathSring, System.Action<IAppBuilder>)", "RouteBuilderExtensions.Map(IRouteBuilder, string, System.Delegate)").WithLocation(8, 5) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_13() { var source = @"using System; class Program { static void Main() { F(1, () => { }); F(2, Main); } static void F(object obj, Action a) { } static void F(int i, Delegate d) { } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(object, Action)' and 'Program.F(int, Delegate)' // F(1, () => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(object, System.Action)", "Program.F(int, System.Delegate)").WithLocation(6, 9), // (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(object, Action)' and 'Program.F(int, Delegate)' // F(2, Main); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(object, System.Action)", "Program.F(int, System.Delegate)").WithLocation(7, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_14() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { F(() => 1, 2); } static void F(Expression<Func<object>> f, object obj) { } static void F(Expression e, int i) { } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Expression<Func<object>>, object)' and 'Program.F(Expression, int)' // F(() => 1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Linq.Expressions.Expression<System.Func<object>>, object)", "Program.F(System.Linq.Expressions.Expression, int)").WithLocation(7, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_15() { var source = @"delegate void StringAction(string arg); class Program { static void F<T>(T t) { } static void F(StringAction a) { } static void M(string arg) { } static void Main() { F((string s) => { }); // C#9: F(StringAction) F(M); // C#9: F(StringAction) } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); // Breaking change from C#9 which binds calls to F(StringAction). comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(T)' and 'Program.F(StringAction)' // F((string s) => { }); // C#9: F(StringAction) Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(T)", "Program.F(StringAction)").WithLocation(9, 9), // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(T)' and 'Program.F(StringAction)' // F(M); // C#9: F(StringAction) Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(T)", "Program.F(StringAction)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_16() { var source = @"using System; class Program { static void F(Func<Func<object>> f, int i) => Report(f); static void F(Func<Func<int>> f, object o) => Report(f); static void Main() { F(() => () => 1, 2); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"System.Func`1[System.Func`1[System.Object]]"); // Breaking change from C#9 which binds calls to F(Func<Func<object>>, int). var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Func<Func<object>>, int)' and 'Program.F(Func<Func<int>>, object)' // F(() => () => 1, 2); // C#9: F(Func<Func<object>>, int) Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Func<System.Func<object>>, int)", "Program.F(System.Func<System.Func<int>>, object)").WithLocation(8, 9)); } [Fact] public void OverloadResolution_17() { var source = @"delegate void StringAction(string arg); class Program { static void F<T>(System.Action<T> a) { } static void F(StringAction a) { } static void Main() { F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F(StringAction)").WithLocation(8, 9)); } [Fact] public void OverloadResolution_18() { var source = @"delegate void StringAction(string arg); class Program { static void F0<T>(System.Action<T> a) { } static void F1<T>(System.Action<T> a) { } static void F1(StringAction a) { } static void M(string arg) { } static void Main() { F0(M); F1(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'Program.F0<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F0(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F0").WithArguments("Program.F0<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_19() { var source = @"delegate void MyAction<T>(T arg); class Program { static void F<T>(System.Action<T> a) { } static void F<T>(MyAction<T> a) { } static void M(string arg) { } static void Main() { F((string s) => { }); F(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F<T>(MyAction<T>)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F<T>(MyAction<T>)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.F<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_20() { var source = @"using System; delegate void StringAction(string s); class Program { static void F(Action<string> a) { } static void F(StringAction a) { } static void M(string s) { } static void Main() { F(M); F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F(M); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(10, 9), // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(11, 9)); } [Fact] public void OverloadResolution_21() { var source = @"using System; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Delegate>(); c.F(() => (Action)null); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Delegate]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(1361172, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1361172")] [Fact] public void OverloadResolution_22() { var source = @"using System; using System.Linq.Expressions; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Expression>(); c.F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Linq.Expressions.Expression]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (15,11): error CS0121: The call is ambiguous between the following methods or properties: 'C<T>.F(T)' and 'C<T>.F(Func<T>)' // c.F(() => Expression.Constant(1)); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("C<T>.F(T)", "C<T>.F(System.Func<T>)").WithLocation(15, 11) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [Fact] public void OverloadResolution_23() { var source = @"using System; class Program { static void F(Delegate d) => Console.WriteLine(""F(Delegate d)""); static void F(Func<object> f) => Console.WriteLine(""F(Func<int> f)""); static void Main() { F(() => 1); } }"; string expectedOutput = "F(Func<int> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_24() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) => Console.WriteLine(""F(Expression e)""); static void F(Func<Expression> f) => Console.WriteLine(""F(Func<Expression> f)""); static void Main() { F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<Expression> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); // Breaking change from C#9. var expectedDiagnostics10AndLater = new[] { // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Expression)' and 'Program.F(Func<Expression>)' // F(() => Expression.Constant(1)); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Linq.Expressions.Expression)", "Program.F(System.Func<System.Linq.Expressions.Expression>)").WithLocation(9, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [Fact] public void BestCommonType_01() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { StringIntDelegate d = M; var a1 = new[] { d, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => int.Parse(s), d }; Report(a1[1]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_02() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void F(bool b) { StringIntDelegate d = M; var c1 = b ? d : ((string s) => int.Parse(s)); var c2 = b ? ((string s) => int.Parse(s)) : d; Report(c1); Report(c2); } static void Main() { F(false); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_03() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return (StringIntDelegate)M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return (StringIntDelegate)M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"StringIntDelegate StringIntDelegate"); } [Fact] public void BestCommonType_04() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_05() { var source = @"using System; class Program { static int M1(string s) => s.Length; static int M2(string s) => int.Parse(s); static void Main() { var a1 = new[] { M1, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => s.Length, M2 }; Report(a1[1]); Report(a2[1]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { M1, (string s) => int.Parse(s) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { M1, (string s) => int.Parse(s) }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (string s) => s.Length, M2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (string s) => s.Length, M2 }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_06() { var source = @"using System; class Program { static void F1<T>(T t) { } static T F2<T>() => default; static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object>, F2<string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object>, F2<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object>, F2<string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Func`1[System.Object]"); } [Fact] public void BestCommonType_07() { var source = @"class Program { static void F1<T>(T t) { } static T F2<T>() => default; static T F3<T>(T t) => t; static void Main() { var a1 = new[] { F1<int>, F1<object> }; var a2 = new[] { F2<nint>, F2<System.IntPtr> }; var a3 = new[] { F3<string>, F3<object> }; } }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<int>, F1<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<int>, F1<object> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<nint>, F2<System.IntPtr> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<nint>, F2<System.IntPtr> }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F3<string>, F3<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F3<string>, F3<object> }").WithLocation(10, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_08() { var source = @"#nullable enable using System; class Program { static void F<T>(T t) { } static void Main() { var a1 = new[] { F<string?>, F<string> }; var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<string?>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<string?>, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<(int X, object Y)>, F<(int, dynamic)> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Action`1[System.ValueTuple`2[System.Int32,System.Object]]"); } [Fact] public void BestCommonType_09() { var source = @"using System; class Program { static void Main() { var a1 = new[] { (object o) => { }, (string s) => { } }; var a2 = new[] { () => (object)null, () => (string)null }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object o) => { }, (string s) => { } }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { () => (object)null, () => (string)null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => (object)null, () => (string)null }").WithLocation(7, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,26): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(6, 26), // (6,34): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(6, 34)); } [Fact] public void BestCommonType_10() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<string>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<string>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<string>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000004}`2[System.String,System.Object] <>A{00000001}`2[System.Object,System.String]"); } [Fact] [WorkItem(55909, "https://github.com/dotnet/roslyn/issues/55909")] public void BestCommonType_11() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, object> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, object> }").WithLocation(9, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/55909: ConversionsBase.HasImplicitSignatureConversion() // relies on the variance of FunctionTypeSymbol.GetInternalDelegateType() which fails for synthesized // delegate types where the type parameters are invariant. comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_12() { var source = @"class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, F<string> }; var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; } }"; var expectedDiagnostics = new[] { // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, F<string> }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_13() { var source = @"using System; class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, null }; var a2 = new[] { default, F<string> }; var a3 = new[] { null, default, (object x, ref string y) => { } }; Report(a1[0]); Report(a2[1]); Report(a3[2]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, null }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { default, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { default, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { null, default, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { null, default, (object x, ref string y) => { } }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000001}`1[System.Object] <>A{00000001}`1[System.String] <>A{00000004}`2[System.Object,System.String] "); } /// <summary> /// Best common type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void BestCommonType_NoInferredSignature() { var source = @"class Program { static void F1() { } static int F1(int i) => i; static void F2() { } static void Main() { var a1 = new[] { F1 }; var a2 = new[] { F1, F2 }; var a3 = new[] { F2, F1 }; var a4 = new[] { x => x }; var a5 = new[] { x => x, (int y) => y }; var a6 = new[] { (int y) => y, static x => x }; var a7 = new[] { x => x, F1 }; var a8 = new[] { F1, (int y) => y }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F1, F2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, F2 }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F2, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2, F1 }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var a5 = new[] { x => x, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, (int y) => y }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var a6 = new[] { (int y) => y, static x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (int y) => y, static x => x }").WithLocation(13, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var a8 = new[] { F1, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, (int y) => y }").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18)); } [Fact] public void ArrayInitializer_01() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Func<int>[] { () => 1 }; var a2 = new Expression<Func<int>>[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = $@"System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void ArrayInitializer_02() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Delegate[] { () => 1 }; var a2 = new Expression[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,35): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var a1 = new Delegate[] { () => 1 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 35), // (8,37): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // var a2 = new Expression[] { () => 2 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(8, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]]"); } [Fact] public void ArrayInitializer_03() { var source = @"using System; class Program { static void Main() { var a1 = new[] { () => 1 }; Report(a1[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { () => 1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => 1 }").WithLocation(6, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32]"); } [Fact] public void ConditionalOperator_01() { var source = @"class Program { static void F<T>(T t) { } static void Main() { var c1 = F<object> ?? F<string>; var c2 = ((object o) => { }) ?? ((string s) => { }); var c3 = F<string> ?? ((object o) => { }); } }"; var expectedDiagnostics = new[] { // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // var c1 = F<object> ?? F<string>; Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<object> ?? F<string>").WithArguments("??", "method group", "method group").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'lambda expression' and 'lambda expression' // var c2 = ((object o) => { }) ?? ((string s) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "((object o) => { }) ?? ((string s) => { })").WithArguments("??", "lambda expression", "lambda expression").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'lambda expression' // var c3 = F<string> ?? ((object o) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<string> ?? ((object o) => { })").WithArguments("??", "method group", "lambda expression").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaReturn_01() { var source = @"using System; class Program { static void Main() { var a1 = () => () => 1; var a2 = () => Main; Report(a1()); Report(a2()); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32] System.Action"); } [Fact] public void InferredType_MethodGroup() { var source = @"class Program { static void Main() { System.Delegate d = Main; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } [Fact] public void InferredType_LambdaExpression() { var source = @"class Program { static void Main() { System.Delegate d = () => { }; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } [Fact] public void TypeInference_Constraints_01() { var source = @"using System; using System.Linq.Expressions; class Program { static T F1<T>(T t) where T : Delegate => t; static T F2<T>(T t) where T : Expression => t; static void Main() { Report(F1((int i) => { })); Report(F2(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((int i) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F2<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Action`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_02() { var source = @"using System; using System.Linq.Expressions; class A<T> { public static U F<U>(U u) where U : T => u; } class B { static void Main() { Report(A<object>.F(() => 1)); Report(A<ICloneable>.F(() => 1)); Report(A<Delegate>.F(() => 1)); Report(A<MulticastDelegate>.F(() => 1)); Report(A<Func<int>>.F(() => 1)); Report(A<Expression>.F(() => 1)); Report(A<LambdaExpression>.F(() => 1)); Report(A<Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_03() { var source = @"using System; using System.Linq.Expressions; class A<T, U> where U : T { public static V F<V>(V v) where V : U => v; } class B { static void Main() { Report(A<object, object>.F(() => 1)); Report(A<object, Delegate>.F(() => 1)); Report(A<object, Func<int>>.F(() => 1)); Report(A<Delegate, Func<int>>.F(() => 1)); Report(A<object, Expression>.F(() => 1)); Report(A<object, Expression<Func<int>>>.F(() => 1)); Report(A<Expression, LambdaExpression>.F(() => 1)); Report(A<Expression, Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_MatchingSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(string s) => s.Length; static void F2(string s) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_DistinctSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(object o) => o.GetHashCode(); static void F2(object o) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_01() { var source = @"using System; class Program { static T M<T>(T x, T y) => x; static int F1(int i) => i; static void F1() { } static T F2<T>(T t) => t; static void Main() { var f1 = M(x => x, (int y) => y); var f2 = M(F1, F2<int>); var f3 = M(F2<object>, z => z); Report(f1); Report(f2); Report(f3); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(F1, F2<int>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M(F2<object>, z => z); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(12, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] System.Func`2[System.Object,System.Object] "); } [Fact] public void TypeInference_02() { var source = @"using System; class Program { static T M<T>(T x, T y) where T : class => x ?? y; static T F<T>() => default; static void Main() { var f1 = M(F<object>, null); var f2 = M(default, F<string>); var f3 = M((object x, ref string y) => { }, default); var f4 = M(null, (ref object x, string y) => { }); Report(f1); Report(f2); Report(f3); Report(f4); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(F<object>, null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(8, 18), // (9,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(default, F<string>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(9, 18), // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M((object x, ref string y) => { }, default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f4 = M(null, (ref object x, string y) => { }); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Object] System.Func`1[System.String] <>A{00000004}`2[System.Object,System.String] <>A{00000001}`2[System.Object,System.String] "); } [Fact] public void TypeInference_LowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (string s) => { })); Report(F(() => 2, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (object o) => { })); Report(F(() => 1.0, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (11,22): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(11, 22), // (11,30): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(11, 30), // (12,24): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.0").WithArguments("double", "int").WithLocation(12, 24), // (12,24): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1.0").WithArguments("lambda expression").WithLocation(12, 24) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_02() { var source = @"using System; class Program { static T F<T>(T x, T y) => y; static void Main() { Report(F((string s) => { }, (object o) => { })); Report(F(() => string.Empty, () => new object())); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(7, 16), // (8,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(() => string.Empty, () => new object())); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(8, 16)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,37): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(7, 37), // (7,45): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(7, 45)); } [Fact] public void TypeInference_UpperAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<int>> a2 = null; Report(F1(a1, (string s) => { })); Report(F2(() => 2, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<object>> a2 = null; Report(F1(a1, (object o) => { })); Report(F2(() => string.Empty, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,23): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 23), // (12,31): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 31) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,42): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(10, 50) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F1(ref d1, (string s) => { })); Report(F2(() => 2, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<object> d2 = () => new object(); Report(F1(ref d1, (object o) => { })); Report(F2(() => string.Empty, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,27): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 27), // (12,35): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 35) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(in T x, T y) => y; static T F2<T>(T x, in T y) => y; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,16): error CS0411: The type arguments for method 'Program.F1<T>(in T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(in T, T)").WithLocation(10, 16), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,42): error CS1661: Cannot convert lambda expression to type 'Action<D1<string>>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<D1<string>>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'D1<string>' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "D1<string>").WithLocation(10, 50), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16)); } [Fact] public void TypeInference_Nested_01() { var source = @"delegate void D<T>(T t); class Program { static T F1<T>(T t) => t; static D<T> F2<T>(D<T> d) => d; static void Main() { F2(F1((string s) => { })); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(D<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(D<T>)").WithLocation(8, 9)); } [Fact] public void TypeInference_Nested_02() { var source = @"using System.Linq.Expressions; class Program { static T F1<T>(T x) => throw null; static Expression<T> F2<T>(Expression<T> e) => e; static void Main() { F2(F1((object x1) => 1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((object x1) => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<T>)").WithLocation(8, 9)); } /// <summary> /// Method type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void TypeInference_NoInferredSignature() { var source = @"class Program { static void F1() { } static void F1(int i) { } static void F2() { } static T M1<T>(T t) => t; static T M2<T>(T x, T y) => x; static void Main() { var a1 = M1(F1); var a2 = M2(F1, F2); var a3 = M2(F2, F1); var a4 = M1(x => x); var a5 = M2(x => x, (int y) => y); var a6 = M2((int y) => y, x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a2 = M2(F1, F2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a3 = M2(F2, F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(12, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18), // (14,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a5 = M2(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(14, 18), // (15,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a6 = M2((int y) => y, x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18)); } [Fact] public void Variance() { var source = @"using System; delegate void StringAction(string s); class Program { static void Main() { Action<string> a1 = s => { }; Action<string> a2 = (string s) => { }; Action<string> a3 = (object o) => { }; Action<string> a4 = (Action<object>)((object o) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,29): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(9, 29), // (9,37): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(9, 37)); } [Fact] public void ImplicitlyTypedVariables_01() { var source = @"using System; class Program { static void Main() { var d1 = Main; Report(d1); var d2 = () => { }; Report(d2); var d3 = delegate () { }; Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = Main; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 18), // (8,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 18), // (10,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(10, 18)); comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action"); verifier.VerifyIL("Program.Main", @"{ // Code size 100 (0x64) .maxstack 2 .locals init (System.Action V_0, //d1 System.Action V_1, //d2 System.Action V_2) //d3 IL_0000: nop IL_0001: ldnull IL_0002: ldftn ""void Program.Main()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void Program.Report(System.Delegate)"" IL_0014: nop IL_0015: ldsfld ""System.Action Program.<>c.<>9__0_0"" IL_001a: dup IL_001b: brtrue.s IL_0034 IL_001d: pop IL_001e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0023: ldftn ""void Program.<>c.<Main>b__0_0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: dup IL_002f: stsfld ""System.Action Program.<>c.<>9__0_0"" IL_0034: stloc.1 IL_0035: ldloc.1 IL_0036: call ""void Program.Report(System.Delegate)"" IL_003b: nop IL_003c: ldsfld ""System.Action Program.<>c.<>9__0_1"" IL_0041: dup IL_0042: brtrue.s IL_005b IL_0044: pop IL_0045: ldsfld ""Program.<>c Program.<>c.<>9"" IL_004a: ldftn ""void Program.<>c.<Main>b__0_1()"" IL_0050: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0055: dup IL_0056: stsfld ""System.Action Program.<>c.<>9__0_1"" IL_005b: stloc.2 IL_005c: ldloc.2 IL_005d: call ""void Program.Report(System.Delegate)"" IL_0062: nop IL_0063: ret }"); } [Fact] public void ImplicitlyTypedVariables_02() { var source = @"var d1 = object.ReferenceEquals; var d2 = () => { }; var d3 = delegate () { }; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics( // (1,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = object.ReferenceEquals; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object.ReferenceEquals").WithArguments("inferred delegate type", "10.0").WithLocation(1, 10), // (2,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(2, 10), // (3,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(3, 10)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_03() { var source = @"class Program { static void Main() { ref var d1 = Main; ref var d2 = () => { }; ref var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d1 = Main; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d1 = Main").WithLocation(5, 17), // (5,22): error CS1657: Cannot use 'Main' as a ref or out value because it is a 'method group' // ref var d1 = Main; Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Main").WithArguments("Main", "method group").WithLocation(5, 22), // (6,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d2 = () => { }").WithLocation(6, 17), // (6,22): error CS1510: A ref or out value must be an assignable variable // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "() => { }").WithLocation(6, 22), // (7,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d3 = delegate () { }").WithLocation(7, 17), // (7,22): error CS1510: A ref or out value must be an assignable variable // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate () { }").WithLocation(7, 22)); } [Fact] public void ImplicitlyTypedVariables_04() { var source = @"class Program { static void Main() { using var d1 = Main; using var d2 = () => { }; using var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d1 = Main; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d1 = Main;").WithArguments("System.Action").WithLocation(5, 9), // (6,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d2 = () => { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d2 = () => { };").WithArguments("System.Action").WithLocation(6, 9), // (7,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d3 = delegate () { };").WithArguments("System.Action").WithLocation(7, 9)); } [Fact] public void ImplicitlyTypedVariables_05() { var source = @"class Program { static void Main() { foreach (var d1 in Main) { } foreach (var d2 in () => { }) { } foreach (var d3 in delegate () { }) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? // foreach (var d1 in Main) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group").WithLocation(5, 28), // (6,28): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // foreach (var d2 in () => { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => { }").WithArguments("lambda expression").WithLocation(6, 28), // (7,28): error CS0446: Foreach cannot operate on a 'anonymous method'. Did you intend to invoke the 'anonymous method'? // foreach (var d3 in delegate () { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "delegate () { }").WithArguments("anonymous method").WithLocation(7, 28)); } [Fact] public void ImplicitlyTypedVariables_06() { var source = @"using System; class Program { static void Main() { Func<int> f; var d1 = Main; f = d1; var d2 = object (int x) => x; f = d2; var d3 = delegate () { return string.Empty; }; f = d3; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<int>' // f = d1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("System.Action", "System.Func<int>").WithLocation(8, 13), // (10,13): error CS0029: Cannot implicitly convert type 'System.Func<int, object>' to 'System.Func<int>' // f = d2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("System.Func<int, object>", "System.Func<int>").WithLocation(10, 13), // (12,13): error CS0029: Cannot implicitly convert type 'System.Func<string>' to 'System.Func<int>' // f = d3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("System.Func<string>", "System.Func<int>").WithLocation(12, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Initializer != null); var expectedInfo = new (string?, string?, string?)[] { ("System.Action d1", null, "System.Action"), ("System.Func<System.Int32, System.Object> d2", null, "System.Func<System.Int32, System.Object>"), ("System.Func<System.String> d3", null, "System.Func<System.String>"), }; AssertEx.Equal(expectedInfo, variables.Select(v => getVariableInfo(model, v))); static (string?, string?, string?) getVariableInfo(SemanticModel model, VariableDeclaratorSyntax variable) { var symbol = model.GetDeclaredSymbol(variable); var typeInfo = model.GetTypeInfo(variable.Initializer!.Value); return (symbol?.ToTestDisplayString(), typeInfo.Type?.ToTestDisplayString(), typeInfo.ConvertedType?.ToTestDisplayString()); } } [Fact] public void ImplicitlyTypedVariables_07() { var source = @"class Program { static void Main() { var t = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,13): error CS0815: Cannot assign (method group, lambda expression) to an implicitly-typed variable // var t = (Main, () => { }); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (Main, () => { })").WithArguments("(method group, lambda expression)").WithLocation(5, 13)); } [Fact] public void ImplicitlyTypedVariables_08() { var source = @"class Program { static void Main() { (var x1, var y1) = Main; var (x2, y2) = () => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(5, 14), // (5,22): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(5, 22), // (5,28): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "Main").WithLocation(5, 28), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 14), // (6,18): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(6, 18), // (6,24): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "() => { }").WithLocation(6, 24)); } [Fact] public void ImplicitlyTypedVariables_09() { var source = @"class Program { static void Main() { var (x, y) = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(5, 14), // (5,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] public void ImplicitlyTypedVariables_10() { var source = @"using System; class Program { static void Main() { (var x1, Action y1) = (Main, null); (Action x2, var y2) = (null, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, Action y1) = (Main, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 14), // (7,25): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // (Action x2, var y2) = (null, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)); } [Fact] public void ImplicitlyTypedVariables_11() { var source = @"class Program { static void F(object o) { } static void F(int i) { } static void Main() { var d1 = F; var d2 = x => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d2 = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 18)); } [Fact] public void ImplicitlyTypedVariables_12() { var source = @"class Program { static void F(ref int i) { } static void Main() { var d1 = F; var d2 = (ref int x) => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_13() { var source = @"using System; class Program { static int F() => 0; static void Main() { var d1 = (F); Report(d1); var d2 = (object (int x) => x); Report(d2); var d3 = (delegate () { return string.Empty; }); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; CompileAndVerify(new[] { source, s_utils }, options: TestOptions.DebugExe, expectedOutput: @"System.Func<System.Int32> System.Func<System.Int32, System.Object> System.Func<System.String>"); } [Fact] public void ImplicitlyTypedVariables_14() { var source = @"delegate void D(string s); class Program { static void Main() { (D x, var y) = (() => string.Empty, () => string.Empty); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // (D x, var y) = (() => string.Empty, () => string.Empty); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(6, 19)); } [Fact] public void ImplicitlyTypedVariables_UseSiteErrors() { var source = @"class Program { static void F(object o) { } static void Main() { var d1 = F; var d2 = () => 1; } }"; var comp = CreateEmptyCompilation(source, new[] { GetCorlibWithInvalidActionAndFuncOfT() }); comp.VerifyDiagnostics( // (6,18): error CS0648: 'Action<T>' is a type not supported by the language // var d1 = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(6, 18), // (7,18): error CS0648: 'Func<T>' is a type not supported by the language // var d2 = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(7, 18)); } [Fact] public void BinaryOperator() { var source = @"using System; class Program { static void Main() { var b1 = (() => { }) == null; var b2 = null == Main; var b3 = Main == (() => { }); Console.WriteLine((b1, b2, b3)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0019: Operator '==' cannot be applied to operands of type 'lambda expression' and '<null>' // var b1 = (() => { }) == null; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(() => { }) == null").WithArguments("==", "lambda expression", "<null>").WithLocation(6, 18), // (7,18): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'method group' // var b2 = null == Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "null == Main").WithArguments("==", "<null>", "method group").WithLocation(7, 18), // (8,18): error CS0019: Operator '==' cannot be applied to operands of type 'method group' and 'lambda expression' // var b3 = Main == (() => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main == (() => { })").WithArguments("==", "method group", "lambda expression").WithLocation(8, 18)); CompileAndVerify(source, expectedOutput: "(False, False, False)"); } /// <summary> /// Ensure the conversion group containing the implicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_01() { var source = @"#nullable enable class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } /// <summary> /// Ensure the conversion group containing the explicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_02() { var source = @"#nullable enable class Program { static void Main() { object o; o = (System.Delegate)Main; o = (System.Delegate)(() => { }); o = (System.Delegate)(delegate () { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void SynthesizedDelegateTypes_01() { var source = @"using System; class Program { static void M1<T>(T t) { var d = (ref T t) => t; Report(d); Console.WriteLine(d(ref t)); } static void M2<U>(U u) where U : struct { var d = (ref U u) => u; Report(d); Console.WriteLine(d(ref u)); } static void M3(double value) { var d = (ref double d) => d; Report(d); Console.WriteLine(d(ref value)); } static void Main() { M1(41); M2(42f); M2(43d); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] 41 <>F{00000001}`2[System.Single,System.Single] 42 <>F{00000001}`2[System.Double,System.Double] 43 "); verifier.VerifyIL("Program.M1<T>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__0<T> Program.<>c__0<T>.<>9"" IL_000e: ldftn ""T Program.<>c__0<T>.<M1>b__0_0(ref T)"" IL_0014: newobj ""<>F{00000001}<T, T>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""T <>F{00000001}<T, T>.Invoke(ref T)"" IL_002c: box ""T"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M2<U>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__1<U> Program.<>c__1<U>.<>9"" IL_000e: ldftn ""U Program.<>c__1<U>.<M2>b__1_0(ref U)"" IL_0014: newobj ""<>F{00000001}<U, U>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""U <>F{00000001}<U, U>.Invoke(ref U)"" IL_002c: box ""U"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M3", @"{ // Code size 50 (0x32) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""double Program.<>c.<M3>b__2_0(ref double)"" IL_0014: newobj ""<>F{00000001}<double, double>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""double <>F{00000001}<double, double>.Invoke(ref double)"" IL_002c: call ""void System.Console.WriteLine(double)"" IL_0031: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes(); var variables = nodes.OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(3, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<T, T> d", "T <>F{00000001}<T, T>.Invoke(ref T)"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<U, U> d", "U <>F{00000001}<U, U>.Invoke(ref U)"); VerifyLocalDelegateType(model, variables[2], "<>F{00000001}<System.Double, System.Double> d", "System.Double <>F{00000001}<System.Double, System.Double>.Invoke(ref System.Double)"); var identifiers = nodes.OfType<InvocationExpressionSyntax>().Where(i => i.Expression is IdentifierNameSyntax id && id.Identifier.Text == "Report").Select(i => i.ArgumentList.Arguments[0].Expression).ToArray(); Assert.Equal(3, identifiers.Length); VerifyExpressionType(model, identifiers[0], "<>F{00000001}<T, T> d", "<>F{00000001}<T, T>"); VerifyExpressionType(model, identifiers[1], "<>F{00000001}<U, U> d", "<>F{00000001}<U, U>"); VerifyExpressionType(model, identifiers[2], "<>F{00000001}<System.Double, System.Double> d", "<>F{00000001}<System.Double, System.Double>"); } [Fact] public void SynthesizedDelegateTypes_02() { var source = @"using System; class Program { static void M1(A a, int value) { var d = a.F1; d() = value; } static void M2(B b, float value) { var d = b.F2; d() = value; } static void Main() { var a = new A(); M1(a, 41); var b = new B(); M2(b, 42f); Console.WriteLine((a._f, b._f)); } } class A { public int _f; public ref int F1() => ref _f; } class B { public float _f; } static class E { public static ref float F2(this B b) => ref b._f; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"(41, 42)"); verifier.VerifyIL("Program.M1", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref int A.F1()"" IL_0007: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref int <>F{00000001}<int>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.i4 IL_0013: ret }"); verifier.VerifyIL("Program.M2", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref float E.F2(B)"" IL_0007: newobj ""<>F{00000001}<float>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref float <>F{00000001}<float>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.r4 IL_0013: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(2, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<System.Int32> d", "ref System.Int32 <>F{00000001}<System.Int32>.Invoke()"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<System.Single> d", "ref System.Single <>F{00000001}<System.Single>.Invoke()"); } [Fact] public void SynthesizedDelegateTypes_03() { var source = @"using System; class Program { static void Main() { Report((ref int x, int y) => { }); Report((int x, ref int y) => { }); Report((ref float x, int y) => { }); Report((float x, ref int y) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`2[System.Int32,System.Int32] <>A{00000004}`2[System.Int32,System.Int32] <>A{00000001}`2[System.Single,System.Int32] <>A{00000004}`2[System.Single,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__0_0(ref int, int)"" IL_0014: newobj ""<>A{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__0_1(int, ref int)"" IL_0038: newobj ""<>A{00000004}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__0_2(ref float, int)"" IL_005c: newobj ""<>A{00000001}<float, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__0_3(float, ref int)"" IL_0080: newobj ""<>A{00000004}<float, int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_04() { var source = @"using System; class Program { static int i = 0; static void Main() { Report(int () => i); Report((ref int () => ref i)); Report((ref readonly int () => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__1_0()"" IL_0014: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__1_1()"" IL_0038: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__1_2()"" IL_005c: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_05() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { Report(F1); Report(F2); Report(F3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 52 (0x34) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""int Program.F1()"" IL_0007: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""ref int Program.F2()"" IL_0018: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""ref readonly int Program.F3()"" IL_0029: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ret }"); } [Fact] public void SynthesizedDelegateTypes_06() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { var d1 = F1; var d2 = F2; var d3 = F3; Report(d1); Report(d2); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); } [Fact] public void SynthesizedDelegateTypes_07() { var source = @"using System; class Program { static void Main() { Report(int (ref int i) => i); Report((ref int (ref int i) => ref i)); Report((ref readonly int (ref int i) => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] <>F{00000005}`2[System.Int32,System.Int32] <>F{0000000d}`2[System.Int32,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__0_0(ref int)"" IL_0014: newobj ""<>F{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__0_1(ref int)"" IL_0038: newobj ""<>F{00000005}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__0_2(ref int)"" IL_005c: newobj ""<>F{0000000d}<int, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_08() { var source = @"#pragma warning disable 414 using System; class Program { static int i = 0; static void Main() { Report((int i) => { }); Report((out int i) => { i = 0; }); Report((ref int i) => { }); Report((in int i) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__1_0(int)"" IL_0014: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__1_1(out int)"" IL_0038: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__1_2(ref int)"" IL_005c: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__1_3(in int)"" IL_0080: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_09() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { Report(M1); Report(M2); Report(M3); Report(M4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 69 (0x45) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""void Program.M1(int)"" IL_0007: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""void Program.M2(out int)"" IL_0018: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""void Program.M3(ref int)"" IL_0029: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ldnull IL_0034: ldftn ""void Program.M4(in int)"" IL_003a: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_003f: call ""void Program.Report(System.Delegate)"" IL_0044: ret }"); } [Fact] public void SynthesizedDelegateTypes_10() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { var d1 = M1; var d2 = M2; var d3 = M3; var d4 = M4; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_11() { var source = @"class Program { unsafe static void Main() { var d1 = int* () => (int*)42; var d2 = (int* p) => { }; var d3 = delegate*<void> () => default; var d4 = (delegate*<void> d) => { }; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (5,18): error CS8917: The delegate type could not be inferred. // var d1 = int* () => (int*)42; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "int* () => (int*)42").WithLocation(5, 18), // (6,18): error CS8917: The delegate type could not be inferred. // var d2 = (int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int* p) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d3 = delegate*<void> () => default; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "delegate*<void> () => default").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d4 = (delegate*<void> d) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(delegate*<void> d) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [ConditionalFact(typeof(DesktopOnly))] public void SynthesizedDelegateTypes_12() { var source = @"using System; class Program { static void Main() { var d1 = (TypedReference x) => { }; var d2 = (int x, RuntimeArgumentHandle y) => { }; var d3 = (ArgIterator x) => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = (TypedReference x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(TypedReference x) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d2 = (int x, RuntimeArgumentHandle y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, RuntimeArgumentHandle y) => { }").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d3 = (ArgIterator x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ArgIterator x) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_13() { var source = @"ref struct S<T> { } class Program { static void F1(int x, S<int> y) { } static S<T> F2<T>() => throw null; static void Main() { var d1 = F1; var d2 = F2<object>; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8917: The delegate type could not be inferred. // var d1 = F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(8, 18), // (9,18): error CS8917: The delegate type could not be inferred. // var d2 = F2<object>; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2<object>").WithLocation(9, 18)); } [Fact] public void SynthesizedDelegateTypes_14() { var source = @"class Program { static ref void F() { } static void Main() { var d1 = F; var d2 = (ref void () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (3,16): error CS1547: Keyword 'void' cannot be used in this context // static ref void F() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(3, 16), // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(6, 18), // (7,19): error CS8917: The delegate type could not be inferred. // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 19), // (7,23): error CS1547: Keyword 'void' cannot be used in this context // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 23)); } [Fact] public void SynthesizedDelegateTypes_15() { var source = @"using System; unsafe class Program { static byte*[] F1() => null; static void F2(byte*[] a) { } static byte*[] F3(ref int i) => null; static void F4(ref byte*[] a) { } static void Main() { Report(int*[] () => null); Report((int*[] a) => { }); Report(int*[] (ref int i) => null); Report((ref int*[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32*[]] System.Action`1[System.Int32*[]] <>F{00000001}`2[System.Int32,System.Int32*[]] <>A{00000001}`1[System.Int32*[]] System.Func`1[System.Byte*[]] System.Action`1[System.Byte*[]] <>F{00000001}`2[System.Int32,System.Byte*[]] <>A{00000001}`1[System.Byte*[]] "); } [Fact] public void SynthesizedDelegateTypes_16() { var source = @"using System; unsafe class Program { static delegate*<ref int>[] F1() => null; static void F2(delegate*<ref int, void>[] a) { } static delegate*<ref int>[] F3(ref int i) => null; static void F4(ref delegate*<ref int, void>[] a) { } static void Main() { Report(delegate*<int, ref int>[] () => null); Report((delegate*<int, ref int, void>[] a) => { }); Report(delegate*<int, ref int>[] (ref int i) => null); Report((ref delegate*<int, ref int, void>[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] "); } [Fact] public void SynthesizedDelegateTypes_17() { var source = @"#nullable enable using System; class Program { static void F1(object x, dynamic y) { } static void F2(IntPtr x, nint y) { } static void F3((int x, int y) t) { } static void F4(object? x, object?[] y) { } static void F5(ref object x, dynamic y) { } static void F6(IntPtr x, ref nint y) { } static void F7(ref (int x, int y) t) { } static void F8(object? x, ref object?[] y) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); Report(F5); Report(F6); Report(F7); Report(F8); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`2[System.Object,System.Object] System.Action`2[System.IntPtr,System.IntPtr] System.Action`1[System.ValueTuple`2[System.Int32,System.Int32]] System.Action`2[System.Object,System.Object[]] <>A{00000001}`2[System.Object,System.Object] <>A{00000004}`2[System.IntPtr,System.IntPtr] <>A{00000001}`1[System.ValueTuple`2[System.Int32,System.Int32]] <>A{00000004}`2[System.Object,System.Object[]] "); } /// <summary> /// Synthesized delegate types should only be emitted if used. /// </summary> [Fact] [WorkItem(55896, "https://github.com/dotnet/roslyn/issues/55896")] public void SynthesizedDelegateTypes_18() { var source = @"using System; delegate void D2(object x, ref object y); delegate void D4(out object x, ref object y); class Program { static void F1(ref object x, object y) { } static void F2(object x, ref object y) { } static void Main() { var d1 = F1; D2 d2 = F2; var d3 = (ref object x, out object y) => { y = null; }; D4 d4 = (out object x, ref object y) => { x = null; }; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, validator: validator, expectedOutput: @"<>A{00000001}`2[System.Object,System.Object] D2 <>A{00000009}`2[System.Object,System.Object] D4"); static void validator(PEAssembly assembly) { var reader = assembly.GetMetadataReader(); var actualTypes = reader.GetTypeDefNames().Select(h => reader.GetString(h)).ToArray(); // https://github.com/dotnet/roslyn/issues/55896: Should not include <>A{00000004}`2 or <>A{00000006}`2. string[] expectedTypes = new[] { "<Module>", "<>A{00000001}`2", "<>A{00000004}`2", "<>A{00000006}`2", "<>A{00000009}`2", "D2", "D4", "Program", "<>c", }; AssertEx.Equal(expectedTypes, actualTypes); } } private static void VerifyLocalDelegateType(SemanticModel model, VariableDeclaratorSyntax variable, string expectedLocal, string expectedInvokeMethod) { var local = (ILocalSymbol)model.GetDeclaredSymbol(variable)!; Assert.Equal(expectedLocal, local.ToTestDisplayString()); var delegateType = ((INamedTypeSymbol)local.Type); Assert.Equal(Accessibility.Internal, delegateType.DeclaredAccessibility); Assert.Equal(expectedInvokeMethod, delegateType.DelegateInvokeMethod.ToTestDisplayString()); } private static void VerifyExpressionType(SemanticModel model, ExpressionSyntax variable, string expectedSymbol, string expectedType) { var symbol = model.GetSymbolInfo(variable).Symbol; Assert.Equal(expectedSymbol, symbol.ToTestDisplayString()); var type = model.GetTypeInfo(variable).Type; Assert.Equal(expectedType, type.ToTestDisplayString()); } [Fact] public void TaskRunArgument() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Run(() => { }); } }"; var verifier = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview); var method = (MethodSymbol)verifier.TestData.GetMethodsByName()["Program.<>c.<F>b__0_0()"].Method; Assert.Equal("void Program.<>c.<F>b__0_0()", method.ToTestDisplayString()); verifier.VerifyIL("Program.<>c.<F>b__0_0()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Core/Portable/Collections/BitVector.cs
// 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 System; using System.Collections.Generic; using System.Diagnostics; using Roslyn.Utilities; using Word = System.UInt64; namespace Microsoft.CodeAnalysis { [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct BitVector : IEquatable<BitVector> { private const Word ZeroWord = 0; private const int Log2BitsPerWord = 6; public const int BitsPerWord = 1 << Log2BitsPerWord; // Cannot expose the following two field publicly because this structure is mutable // and might become not null/empty, unless we restrict access to it. private static Word[] s_emptyArray => Array.Empty<Word>(); private static readonly BitVector s_nullValue = default; private static readonly BitVector s_emptyValue = new(0, s_emptyArray, 0); private Word _bits0; private Word[] _bits; private int _capacity; private BitVector(Word bits0, Word[] bits, int capacity) { int requiredWords = WordsForCapacity(capacity); Debug.Assert(requiredWords == 0 || requiredWords <= bits.Length); _bits0 = bits0; _bits = bits; _capacity = capacity; Check(); } public bool Equals(BitVector other) { // Bit arrays only equal if their underlying sets are of the same size return _capacity == other._capacity // and have the same set of bits set && _bits0 == other._bits0 && _bits.AsSpan().SequenceEqual(other._bits.AsSpan()); } public override bool Equals(object? obj) { return obj is BitVector other && Equals(other); } public static bool operator ==(BitVector left, BitVector right) { return left.Equals(right); } public static bool operator !=(BitVector left, BitVector right) { return !left.Equals(right); } public override int GetHashCode() { int bitsHash = _bits0.GetHashCode(); if (_bits != null) { for (int i = 0; i < _bits.Length; i++) { bitsHash = Hash.Combine(_bits[i].GetHashCode(), bitsHash); } } return Hash.Combine(_capacity, bitsHash); } private static int WordsForCapacity(int capacity) { if (capacity <= 0) return 0; int lastIndex = (capacity - 1) >> Log2BitsPerWord; return lastIndex; } public int Capacity => _capacity; [Conditional("DEBUG_BITARRAY")] private void Check() { Debug.Assert(_capacity == 0 || WordsForCapacity(_capacity) <= _bits.Length); } public void EnsureCapacity(int newCapacity) { if (newCapacity > _capacity) { int requiredWords = WordsForCapacity(newCapacity); if (requiredWords > _bits.Length) Array.Resize(ref _bits, requiredWords); _capacity = newCapacity; Check(); } Check(); } public IEnumerable<Word> Words() { if (_capacity > 0) { yield return _bits0; } for (int i = 0, n = _bits?.Length ?? 0; i < n; i++) { yield return _bits![i]; } } public IEnumerable<int> TrueBits() { Check(); if (_bits0 != 0) { for (int bit = 0; bit < BitsPerWord; bit++) { Word mask = ((Word)1) << bit; if ((_bits0 & mask) != 0) { if (bit >= _capacity) yield break; yield return bit; } } } for (int i = 0; i < _bits.Length; i++) { Word w = _bits[i]; if (w != 0) { for (int b = 0; b < BitsPerWord; b++) { Word mask = ((Word)1) << b; if ((w & mask) != 0) { int bit = ((i + 1) << Log2BitsPerWord) | b; if (bit >= _capacity) yield break; yield return bit; } } } } } /// <summary> /// Create BitArray with at least the specified number of bits. /// </summary> public static BitVector Create(int capacity) { int requiredWords = WordsForCapacity(capacity); Word[] bits = (requiredWords == 0) ? s_emptyArray : new Word[requiredWords]; return new BitVector(0, bits, capacity); } /// <summary> /// return a bit array with all bits set from index 0 through bitCount-1 /// </summary> /// <param name="capacity"></param> /// <returns></returns> public static BitVector AllSet(int capacity) { if (capacity == 0) { return Empty; } int requiredWords = WordsForCapacity(capacity); Word[] bits = (requiredWords == 0) ? s_emptyArray : new Word[requiredWords]; int lastWord = requiredWords - 1; Word bits0 = ~ZeroWord; for (int j = 0; j < lastWord; j++) bits[j] = ~ZeroWord; int numTrailingBits = capacity & ((BitsPerWord) - 1); if (numTrailingBits > 0) { Debug.Assert(numTrailingBits <= BitsPerWord); Word lastBits = ~((~ZeroWord) << numTrailingBits); if (lastWord < 0) { bits0 = lastBits; } else { bits[lastWord] = lastBits; } } else if (requiredWords > 0) { bits[lastWord] = ~ZeroWord; } return new BitVector(bits0, bits, capacity); } /// <summary> /// Make a copy of a bit array. /// </summary> /// <returns></returns> public BitVector Clone() { Word[] newBits; if (_bits is null || _bits.Length == 0) { newBits = s_emptyArray; } else { newBits = (Word[])_bits.Clone(); } return new BitVector(_bits0, newBits, _capacity); } /// <summary> /// Invert all the bits in the vector. /// </summary> public void Invert() { _bits0 = ~_bits0; if (!(_bits is null)) { for (int i = 0; i < _bits.Length; i++) { _bits[i] = ~_bits[i]; } } } /// <summary> /// Is the given bit array null? /// </summary> public bool IsNull { get { return _bits == null; } } public static BitVector Null => s_nullValue; public static BitVector Empty => s_emptyValue; /// <summary> /// Modify this bit vector by bitwise AND-ing each element with the other bit vector. /// For the purposes of the intersection, any bits beyond the current length will be treated as zeroes. /// Return true if any changes were made to the bits of this bit vector. /// </summary> public bool IntersectWith(in BitVector other) { bool anyChanged = false; int otherLength = other._bits.Length; var thisBits = _bits; int thisLength = thisBits.Length; if (otherLength > thisLength) otherLength = thisLength; // intersect the inline portion { var oldV = _bits0; var newV = oldV & other._bits0; if (newV != oldV) { _bits0 = newV; anyChanged = true; } } // intersect up to their common length. for (int i = 0; i < otherLength; i++) { var oldV = thisBits[i]; var newV = oldV & other._bits[i]; if (newV != oldV) { thisBits[i] = newV; anyChanged = true; } } // treat the other bit array as being extended with zeroes for (int i = otherLength; i < thisLength; i++) { if (thisBits[i] != 0) { thisBits[i] = 0; anyChanged = true; } } Check(); return anyChanged; } /// <summary> /// Modify this bit vector by '|'ing each element with the other bit vector. /// </summary> /// <returns> /// True if any bits were set as a result of the union. /// </returns> public bool UnionWith(in BitVector other) { bool anyChanged = false; if (other._capacity > _capacity) EnsureCapacity(other._capacity); Word oldbits = _bits0; _bits0 |= other._bits0; if (oldbits != _bits0) anyChanged = true; for (int i = 0; i < other._bits.Length; i++) { oldbits = _bits[i]; _bits[i] |= other._bits[i]; if (_bits[i] != oldbits) anyChanged = true; } Check(); return anyChanged; } public bool this[int index] { get { if (index < 0) throw new IndexOutOfRangeException(); if (index >= _capacity) return false; int i = (index >> Log2BitsPerWord) - 1; var word = (i < 0) ? _bits0 : _bits[i]; return IsTrue(word, index); } set { if (index < 0) throw new IndexOutOfRangeException(); if (index >= _capacity) EnsureCapacity(index + 1); int i = (index >> Log2BitsPerWord) - 1; int b = index & (BitsPerWord - 1); Word mask = ((Word)1) << b; if (i < 0) { if (value) _bits0 |= mask; else _bits0 &= ~mask; } else { if (value) _bits[i] |= mask; else _bits[i] &= ~mask; } } } public void Clear() { _bits0 = 0; if (_bits != null) Array.Clear(_bits, 0, _bits.Length); } public static bool IsTrue(Word word, int index) { int b = index & (BitsPerWord - 1); Word mask = ((Word)1) << b; return (word & mask) != 0; } public static int WordsRequired(int capacity) { if (capacity <= 0) return 0; return WordsForCapacity(capacity) + 1; } internal string GetDebuggerDisplay() { var value = new char[_capacity]; for (int i = 0; i < _capacity; i++) { value[_capacity - i - 1] = this[i] ? '1' : '0'; } return new string(value); } } }
// 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 System; using System.Collections.Generic; using System.Diagnostics; using Roslyn.Utilities; using Word = System.UInt64; namespace Microsoft.CodeAnalysis { [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct BitVector : IEquatable<BitVector> { private const Word ZeroWord = 0; private const int Log2BitsPerWord = 6; public const int BitsPerWord = 1 << Log2BitsPerWord; // Cannot expose the following two field publicly because this structure is mutable // and might become not null/empty, unless we restrict access to it. private static Word[] s_emptyArray => Array.Empty<Word>(); private static readonly BitVector s_nullValue = default; private static readonly BitVector s_emptyValue = new(0, s_emptyArray, 0); private Word _bits0; private Word[] _bits; private int _capacity; private BitVector(Word bits0, Word[] bits, int capacity) { int requiredWords = WordsForCapacity(capacity); Debug.Assert(requiredWords == 0 || requiredWords <= bits.Length); _bits0 = bits0; _bits = bits; _capacity = capacity; Check(); } public bool Equals(BitVector other) { // Bit arrays only equal if their underlying sets are of the same size return _capacity == other._capacity // and have the same set of bits set && _bits0 == other._bits0 && _bits.AsSpan().SequenceEqual(other._bits.AsSpan()); } public override bool Equals(object? obj) { return obj is BitVector other && Equals(other); } public static bool operator ==(BitVector left, BitVector right) { return left.Equals(right); } public static bool operator !=(BitVector left, BitVector right) { return !left.Equals(right); } public override int GetHashCode() { int bitsHash = _bits0.GetHashCode(); if (_bits != null) { for (int i = 0; i < _bits.Length; i++) { bitsHash = Hash.Combine(_bits[i].GetHashCode(), bitsHash); } } return Hash.Combine(_capacity, bitsHash); } private static int WordsForCapacity(int capacity) { if (capacity <= 0) return 0; int lastIndex = (capacity - 1) >> Log2BitsPerWord; return lastIndex; } public int Capacity => _capacity; [Conditional("DEBUG_BITARRAY")] private void Check() { Debug.Assert(_capacity == 0 || WordsForCapacity(_capacity) <= _bits.Length); } public void EnsureCapacity(int newCapacity) { if (newCapacity > _capacity) { int requiredWords = WordsForCapacity(newCapacity); if (requiredWords > _bits.Length) Array.Resize(ref _bits, requiredWords); _capacity = newCapacity; Check(); } Check(); } public IEnumerable<Word> Words() { if (_capacity > 0) { yield return _bits0; } for (int i = 0, n = _bits?.Length ?? 0; i < n; i++) { yield return _bits![i]; } } public IEnumerable<int> TrueBits() { Check(); if (_bits0 != 0) { for (int bit = 0; bit < BitsPerWord; bit++) { Word mask = ((Word)1) << bit; if ((_bits0 & mask) != 0) { if (bit >= _capacity) yield break; yield return bit; } } } for (int i = 0; i < _bits.Length; i++) { Word w = _bits[i]; if (w != 0) { for (int b = 0; b < BitsPerWord; b++) { Word mask = ((Word)1) << b; if ((w & mask) != 0) { int bit = ((i + 1) << Log2BitsPerWord) | b; if (bit >= _capacity) yield break; yield return bit; } } } } } public static BitVector FromWords(Word bits0, Word[] bits, int capacity) { return new BitVector(bits0, bits, capacity); } /// <summary> /// Create BitArray with at least the specified number of bits. /// </summary> public static BitVector Create(int capacity) { int requiredWords = WordsForCapacity(capacity); Word[] bits = (requiredWords == 0) ? s_emptyArray : new Word[requiredWords]; return new BitVector(0, bits, capacity); } /// <summary> /// return a bit array with all bits set from index 0 through bitCount-1 /// </summary> /// <param name="capacity"></param> /// <returns></returns> public static BitVector AllSet(int capacity) { if (capacity == 0) { return Empty; } int requiredWords = WordsForCapacity(capacity); Word[] bits = (requiredWords == 0) ? s_emptyArray : new Word[requiredWords]; int lastWord = requiredWords - 1; Word bits0 = ~ZeroWord; for (int j = 0; j < lastWord; j++) bits[j] = ~ZeroWord; int numTrailingBits = capacity & ((BitsPerWord) - 1); if (numTrailingBits > 0) { Debug.Assert(numTrailingBits <= BitsPerWord); Word lastBits = ~((~ZeroWord) << numTrailingBits); if (lastWord < 0) { bits0 = lastBits; } else { bits[lastWord] = lastBits; } } else if (requiredWords > 0) { bits[lastWord] = ~ZeroWord; } return new BitVector(bits0, bits, capacity); } /// <summary> /// Make a copy of a bit array. /// </summary> /// <returns></returns> public BitVector Clone() { Word[] newBits; if (_bits is null || _bits.Length == 0) { newBits = s_emptyArray; } else { newBits = (Word[])_bits.Clone(); } return new BitVector(_bits0, newBits, _capacity); } /// <summary> /// Invert all the bits in the vector. /// </summary> public void Invert() { _bits0 = ~_bits0; if (!(_bits is null)) { for (int i = 0; i < _bits.Length; i++) { _bits[i] = ~_bits[i]; } } } /// <summary> /// Is the given bit array null? /// </summary> public bool IsNull { get { return _bits == null; } } public static BitVector Null => s_nullValue; public static BitVector Empty => s_emptyValue; /// <summary> /// Modify this bit vector by bitwise AND-ing each element with the other bit vector. /// For the purposes of the intersection, any bits beyond the current length will be treated as zeroes. /// Return true if any changes were made to the bits of this bit vector. /// </summary> public bool IntersectWith(in BitVector other) { bool anyChanged = false; int otherLength = other._bits.Length; var thisBits = _bits; int thisLength = thisBits.Length; if (otherLength > thisLength) otherLength = thisLength; // intersect the inline portion { var oldV = _bits0; var newV = oldV & other._bits0; if (newV != oldV) { _bits0 = newV; anyChanged = true; } } // intersect up to their common length. for (int i = 0; i < otherLength; i++) { var oldV = thisBits[i]; var newV = oldV & other._bits[i]; if (newV != oldV) { thisBits[i] = newV; anyChanged = true; } } // treat the other bit array as being extended with zeroes for (int i = otherLength; i < thisLength; i++) { if (thisBits[i] != 0) { thisBits[i] = 0; anyChanged = true; } } Check(); return anyChanged; } /// <summary> /// Modify this bit vector by '|'ing each element with the other bit vector. /// </summary> /// <returns> /// True if any bits were set as a result of the union. /// </returns> public bool UnionWith(in BitVector other) { bool anyChanged = false; if (other._capacity > _capacity) EnsureCapacity(other._capacity); Word oldbits = _bits0; _bits0 |= other._bits0; if (oldbits != _bits0) anyChanged = true; for (int i = 0; i < other._bits.Length; i++) { oldbits = _bits[i]; _bits[i] |= other._bits[i]; if (_bits[i] != oldbits) anyChanged = true; } Check(); return anyChanged; } public bool this[int index] { get { if (index < 0) throw new IndexOutOfRangeException(); if (index >= _capacity) return false; int i = (index >> Log2BitsPerWord) - 1; var word = (i < 0) ? _bits0 : _bits[i]; return IsTrue(word, index); } set { if (index < 0) throw new IndexOutOfRangeException(); if (index >= _capacity) EnsureCapacity(index + 1); int i = (index >> Log2BitsPerWord) - 1; int b = index & (BitsPerWord - 1); Word mask = ((Word)1) << b; if (i < 0) { if (value) _bits0 |= mask; else _bits0 &= ~mask; } else { if (value) _bits[i] |= mask; else _bits[i] &= ~mask; } } } public void Clear() { _bits0 = 0; if (_bits != null) Array.Clear(_bits, 0, _bits.Length); } public static bool IsTrue(Word word, int index) { int b = index & (BitsPerWord - 1); Word mask = ((Word)1) << b; return (word & mask) != 0; } public static int WordsRequired(int capacity) { if (capacity <= 0) return 0; return WordsForCapacity(capacity) + 1; } internal string GetDebuggerDisplay() { var value = new char[_capacity]; for (int i = 0; i < _capacity; i++) { value[_capacity - i - 1] = this[i] ? '1' : '0'; } return new string(value); } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Core/Portable/Emit/EditAndContinue/DeltaMetadataWriter.cs
// 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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using Microsoft.Cci; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.Emit { internal sealed class DeltaMetadataWriter : MetadataWriter { private readonly EmitBaseline _previousGeneration; private readonly Guid _encId; private readonly DefinitionMap _definitionMap; private readonly SymbolChanges _changes; /// <summary> /// Type definitions containing any changes (includes added types). /// </summary> private readonly List<ITypeDefinition> _changedTypeDefs; private readonly DefinitionIndex<ITypeDefinition> _typeDefs; private readonly DefinitionIndex<IEventDefinition> _eventDefs; private readonly DefinitionIndex<IFieldDefinition> _fieldDefs; private readonly DefinitionIndex<IMethodDefinition> _methodDefs; private readonly DefinitionIndex<IPropertyDefinition> _propertyDefs; private readonly DefinitionIndex<IParameterDefinition> _parameterDefs; private readonly Dictionary<IParameterDefinition, IMethodDefinition> _parameterDefList; private readonly GenericParameterIndex _genericParameters; private readonly EventOrPropertyMapIndex _eventMap; private readonly EventOrPropertyMapIndex _propertyMap; private readonly MethodImplIndex _methodImpls; // For the EncLog table we need to know which things we're emitting custom attributes for so we can // correctly map the attributes to row numbers of existing attributes for that target private readonly Dictionary<EntityHandle, int> _customAttributeParentCounts; // Keep track of which CustomAttributes rows are added in this and previous deltas, over what is in the // original metadata private readonly Dictionary<EntityHandle, ImmutableArray<int>> _customAttributesAdded; private readonly Dictionary<IParameterDefinition, int> _existingParameterDefs; private readonly Dictionary<MethodDefinitionHandle, int> _firstParamRowMap; private readonly HeapOrReferenceIndex<AssemblyIdentity> _assemblyRefIndex; private readonly HeapOrReferenceIndex<string> _moduleRefIndex; private readonly InstanceAndStructuralReferenceIndex<ITypeMemberReference> _memberRefIndex; private readonly InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference> _methodSpecIndex; private readonly TypeReferenceIndex _typeRefIndex; private readonly InstanceAndStructuralReferenceIndex<ITypeReference> _typeSpecIndex; private readonly HeapOrReferenceIndex<BlobHandle> _standAloneSignatureIndex; private readonly Dictionary<IMethodDefinition, AddedOrChangedMethodInfo> _addedOrChangedMethods; public DeltaMetadataWriter( EmitContext context, CommonMessageProvider messageProvider, EmitBaseline previousGeneration, Guid encId, DefinitionMap definitionMap, SymbolChanges changes, CancellationToken cancellationToken) : base(metadata: MakeTablesBuilder(previousGeneration), debugMetadataOpt: (context.Module.DebugInformationFormat == DebugInformationFormat.PortablePdb) ? new MetadataBuilder() : null, dynamicAnalysisDataWriterOpt: null, context: context, messageProvider: messageProvider, metadataOnly: false, deterministic: false, emitTestCoverageData: false, cancellationToken: cancellationToken) { Debug.Assert(previousGeneration != null); Debug.Assert(encId != default(Guid)); Debug.Assert(encId != previousGeneration.EncId); Debug.Assert(context.Module.DebugInformationFormat != DebugInformationFormat.Embedded); _previousGeneration = previousGeneration; _encId = encId; _definitionMap = definitionMap; _changes = changes; var sizes = previousGeneration.TableSizes; _changedTypeDefs = new List<ITypeDefinition>(); _typeDefs = new DefinitionIndex<ITypeDefinition>(this.TryGetExistingTypeDefIndex, sizes[(int)TableIndex.TypeDef]); _eventDefs = new DefinitionIndex<IEventDefinition>(this.TryGetExistingEventDefIndex, sizes[(int)TableIndex.Event]); _fieldDefs = new DefinitionIndex<IFieldDefinition>(this.TryGetExistingFieldDefIndex, sizes[(int)TableIndex.Field]); _methodDefs = new DefinitionIndex<IMethodDefinition>(this.TryGetExistingMethodDefIndex, sizes[(int)TableIndex.MethodDef]); _propertyDefs = new DefinitionIndex<IPropertyDefinition>(this.TryGetExistingPropertyDefIndex, sizes[(int)TableIndex.Property]); _parameterDefs = new DefinitionIndex<IParameterDefinition>(this.TryGetExistingParameterDefIndex, sizes[(int)TableIndex.Param]); _parameterDefList = new Dictionary<IParameterDefinition, IMethodDefinition>(Cci.SymbolEquivalentEqualityComparer.Instance); _genericParameters = new GenericParameterIndex(sizes[(int)TableIndex.GenericParam]); _eventMap = new EventOrPropertyMapIndex(this.TryGetExistingEventMapIndex, sizes[(int)TableIndex.EventMap]); _propertyMap = new EventOrPropertyMapIndex(this.TryGetExistingPropertyMapIndex, sizes[(int)TableIndex.PropertyMap]); _methodImpls = new MethodImplIndex(this, sizes[(int)TableIndex.MethodImpl]); _customAttributeParentCounts = new Dictionary<EntityHandle, int>(); _customAttributesAdded = new Dictionary<EntityHandle, ImmutableArray<int>>(); _firstParamRowMap = new Dictionary<MethodDefinitionHandle, int>(); _existingParameterDefs = new Dictionary<IParameterDefinition, int>(ReferenceEqualityComparer.Instance); _assemblyRefIndex = new HeapOrReferenceIndex<AssemblyIdentity>(this, lastRowId: sizes[(int)TableIndex.AssemblyRef]); _moduleRefIndex = new HeapOrReferenceIndex<string>(this, lastRowId: sizes[(int)TableIndex.ModuleRef]); _memberRefIndex = new InstanceAndStructuralReferenceIndex<ITypeMemberReference>(this, new MemberRefComparer(this), lastRowId: sizes[(int)TableIndex.MemberRef]); _methodSpecIndex = new InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference>(this, new MethodSpecComparer(this), lastRowId: sizes[(int)TableIndex.MethodSpec]); _typeRefIndex = new TypeReferenceIndex(this, lastRowId: sizes[(int)TableIndex.TypeRef]); _typeSpecIndex = new InstanceAndStructuralReferenceIndex<ITypeReference>(this, new TypeSpecComparer(this), lastRowId: sizes[(int)TableIndex.TypeSpec]); _standAloneSignatureIndex = new HeapOrReferenceIndex<BlobHandle>(this, lastRowId: sizes[(int)TableIndex.StandAloneSig]); _addedOrChangedMethods = new Dictionary<IMethodDefinition, AddedOrChangedMethodInfo>(Cci.SymbolEquivalentEqualityComparer.Instance); } private static MetadataBuilder MakeTablesBuilder(EmitBaseline previousGeneration) { return new MetadataBuilder( previousGeneration.UserStringStreamLength, previousGeneration.StringStreamLength, previousGeneration.BlobStreamLength, previousGeneration.GuidStreamLength); } private ImmutableArray<int> GetDeltaTableSizes(ImmutableArray<int> rowCounts) { var sizes = new int[MetadataTokens.TableCount]; rowCounts.CopyTo(sizes); sizes[(int)TableIndex.TypeRef] = _typeRefIndex.Rows.Count; sizes[(int)TableIndex.TypeDef] = _typeDefs.GetAdded().Count; sizes[(int)TableIndex.Field] = _fieldDefs.GetAdded().Count; sizes[(int)TableIndex.MethodDef] = _methodDefs.GetAdded().Count; sizes[(int)TableIndex.Param] = _parameterDefs.GetAdded().Count; sizes[(int)TableIndex.MemberRef] = _memberRefIndex.Rows.Count; sizes[(int)TableIndex.StandAloneSig] = _standAloneSignatureIndex.Rows.Count; sizes[(int)TableIndex.EventMap] = _eventMap.GetAdded().Count; sizes[(int)TableIndex.Event] = _eventDefs.GetAdded().Count; sizes[(int)TableIndex.PropertyMap] = _propertyMap.GetAdded().Count; sizes[(int)TableIndex.Property] = _propertyDefs.GetAdded().Count; sizes[(int)TableIndex.MethodImpl] = _methodImpls.GetAdded().Count; sizes[(int)TableIndex.ModuleRef] = _moduleRefIndex.Rows.Count; sizes[(int)TableIndex.TypeSpec] = _typeSpecIndex.Rows.Count; sizes[(int)TableIndex.AssemblyRef] = _assemblyRefIndex.Rows.Count; sizes[(int)TableIndex.GenericParam] = _genericParameters.GetAdded().Count; sizes[(int)TableIndex.MethodSpec] = _methodSpecIndex.Rows.Count; return ImmutableArray.Create(sizes); } internal EmitBaseline GetDelta(Compilation compilation, Guid encId, MetadataSizes metadataSizes) { var addedOrChangedMethodsByIndex = new Dictionary<int, AddedOrChangedMethodInfo>(); foreach (var pair in _addedOrChangedMethods) { addedOrChangedMethodsByIndex.Add(MetadataTokens.GetRowNumber(GetMethodDefinitionHandle(pair.Key)), pair.Value); } var previousTableSizes = _previousGeneration.TableEntriesAdded; var deltaTableSizes = GetDeltaTableSizes(metadataSizes.RowCounts); var tableSizes = new int[MetadataTokens.TableCount]; for (int i = 0; i < tableSizes.Length; i++) { tableSizes[i] = previousTableSizes[i] + deltaTableSizes[i]; } // If the previous generation is 0 (metadata) get the synthesized members from the current compilation's builder, // otherwise members from the current compilation have already been merged into the baseline. var synthesizedMembers = (_previousGeneration.Ordinal == 0) ? module.GetAllSynthesizedMembers() : _previousGeneration.SynthesizedMembers; var currentGenerationOrdinal = _previousGeneration.Ordinal + 1; var addedTypes = _typeDefs.GetAdded(); var generationOrdinals = CreateDictionary(_previousGeneration.GenerationOrdinals, SymbolEquivalentEqualityComparer.Instance); foreach (var (addedType, _) in addedTypes) { if (_changes.IsReplaced(addedType)) { generationOrdinals[addedType] = currentGenerationOrdinal; } } return _previousGeneration.With( compilation, module, currentGenerationOrdinal, encId, generationOrdinals, typesAdded: AddRange(_previousGeneration.TypesAdded, addedTypes, comparer: SymbolEquivalentEqualityComparer.Instance), eventsAdded: AddRange(_previousGeneration.EventsAdded, _eventDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance), fieldsAdded: AddRange(_previousGeneration.FieldsAdded, _fieldDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance), methodsAdded: AddRange(_previousGeneration.MethodsAdded, _methodDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance), firstParamRowMap: AddRange(_previousGeneration.FirstParamRowMap, _firstParamRowMap), propertiesAdded: AddRange(_previousGeneration.PropertiesAdded, _propertyDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance), eventMapAdded: AddRange(_previousGeneration.EventMapAdded, _eventMap.GetAdded()), propertyMapAdded: AddRange(_previousGeneration.PropertyMapAdded, _propertyMap.GetAdded()), methodImplsAdded: AddRange(_previousGeneration.MethodImplsAdded, _methodImpls.GetAdded()), customAttributesAdded: AddRange(_previousGeneration.CustomAttributesAdded, _customAttributesAdded), tableEntriesAdded: ImmutableArray.Create(tableSizes), // Blob stream is concatenated aligned. blobStreamLengthAdded: metadataSizes.GetAlignedHeapSize(HeapIndex.Blob) + _previousGeneration.BlobStreamLengthAdded, // String stream is concatenated unaligned. stringStreamLengthAdded: metadataSizes.HeapSizes[(int)HeapIndex.String] + _previousGeneration.StringStreamLengthAdded, // UserString stream is concatenated aligned. userStringStreamLengthAdded: metadataSizes.GetAlignedHeapSize(HeapIndex.UserString) + _previousGeneration.UserStringStreamLengthAdded, // Guid stream accumulates on the GUID heap unlike other heaps, so the previous generations are already included. guidStreamLengthAdded: metadataSizes.HeapSizes[(int)HeapIndex.Guid], anonymousTypeMap: ((IPEDeltaAssemblyBuilder)module).GetAnonymousTypeMap(), synthesizedMembers: synthesizedMembers, addedOrChangedMethods: AddRange(_previousGeneration.AddedOrChangedMethods, addedOrChangedMethodsByIndex), debugInformationProvider: _previousGeneration.DebugInformationProvider, localSignatureProvider: _previousGeneration.LocalSignatureProvider); } private static Dictionary<K, V> CreateDictionary<K, V>(IReadOnlyDictionary<K, V> dictionary, IEqualityComparer<K>? comparer) where K : notnull { var result = new Dictionary<K, V>(comparer); foreach (var pair in dictionary) { result.Add(pair.Key, pair.Value); } return result; } private static IReadOnlyDictionary<K, V> AddRange<K, V>(IReadOnlyDictionary<K, V> previous, IReadOnlyDictionary<K, V> current, IEqualityComparer<K>? comparer = null) where K : notnull { if (previous.Count == 0) { return current; } if (current.Count == 0) { return previous; } var result = CreateDictionary(previous, comparer); foreach (var pair in current) { // Use the latest symbol. result[pair.Key] = pair.Value; } return result; } /// <summary> /// Return tokens for all updated debuggable methods. /// </summary> public void GetUpdatedMethodTokens(ArrayBuilder<MethodDefinitionHandle> methods) { foreach (var def in _methodDefs.GetRows()) { // The debugger tries to remap all modified methods, which requires presence of sequence points. if (!_methodDefs.IsAddedNotChanged(def) && def.GetBody(Context)?.SequencePoints.Length > 0) { methods.Add(MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(def))); } } } /// <summary> /// Return tokens for all updated or added types. /// </summary> public void GetChangedTypeTokens(ArrayBuilder<TypeDefinitionHandle> types) { foreach (var def in _changedTypeDefs) { types.Add(GetTypeDefinitionHandle(def)); } } protected override ushort Generation { get { return (ushort)(_previousGeneration.Ordinal + 1); } } protected override Guid EncId { get { return _encId; } } protected override Guid EncBaseId { get { return _previousGeneration.EncId; } } protected override EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def) { return MetadataTokens.EventDefinitionHandle(_eventDefs.GetRowId(def)); } protected override IReadOnlyList<IEventDefinition> GetEventDefs() { return _eventDefs.GetRows(); } protected override FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def) { return MetadataTokens.FieldDefinitionHandle(_fieldDefs.GetRowId(def)); } protected override IReadOnlyList<IFieldDefinition> GetFieldDefs() { return _fieldDefs.GetRows(); } protected override bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle) { bool result = _typeDefs.TryGetRowId(def, out int rowId); handle = MetadataTokens.TypeDefinitionHandle(rowId); return result; } protected override TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def) { return MetadataTokens.TypeDefinitionHandle(_typeDefs.GetRowId(def)); } protected override ITypeDefinition GetTypeDef(TypeDefinitionHandle handle) { return _typeDefs.GetDefinition(MetadataTokens.GetRowNumber(handle)); } protected override IReadOnlyList<ITypeDefinition> GetTypeDefs() { return _typeDefs.GetRows(); } protected override bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle) { bool result = _methodDefs.TryGetRowId(def, out int rowId); handle = MetadataTokens.MethodDefinitionHandle(rowId); return result; } protected override MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def) => MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(def)); protected override IMethodDefinition GetMethodDef(MethodDefinitionHandle index) => _methodDefs.GetDefinition(MetadataTokens.GetRowNumber(index)); protected override IReadOnlyList<IMethodDefinition> GetMethodDefs() => _methodDefs.GetRows(); protected override PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def) => MetadataTokens.PropertyDefinitionHandle(_propertyDefs.GetRowId(def)); protected override IReadOnlyList<IPropertyDefinition> GetPropertyDefs() => _propertyDefs.GetRows(); protected override ParameterHandle GetParameterHandle(IParameterDefinition def) => MetadataTokens.ParameterHandle(_parameterDefs.GetRowId(def)); protected override IReadOnlyList<IParameterDefinition> GetParameterDefs() => _parameterDefs.GetRows(); protected override IReadOnlyList<IGenericParameter> GetGenericParameters() => _genericParameters.GetRows(); // Fields are associated with the type through the EncLog table. protected override FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef) => default; // Methods are associated with the type through the EncLog table. protected override MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef) => default; // Parameters are associated with the method through the EncLog table. protected override ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef) => default; protected override AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference) { var identity = reference.Identity; var versionPattern = reference.AssemblyVersionPattern; if (versionPattern is not null) { RoslynDebug.AssertNotNull(_previousGeneration.InitialBaseline.LazyMetadataSymbols); identity = _previousGeneration.InitialBaseline.LazyMetadataSymbols.AssemblyReferenceIdentityMap[identity.WithVersion(versionPattern)]; } return MetadataTokens.AssemblyReferenceHandle(_assemblyRefIndex.GetOrAdd(identity)); } protected override IReadOnlyList<AssemblyIdentity> GetAssemblyRefs() { return _assemblyRefIndex.Rows; } protected override ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference) { return MetadataTokens.ModuleReferenceHandle(_moduleRefIndex.GetOrAdd(reference)); } protected override IReadOnlyList<string> GetModuleRefs() { return _moduleRefIndex.Rows; } protected override MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference) { return MetadataTokens.MemberReferenceHandle(_memberRefIndex.GetOrAdd(reference)); } protected override IReadOnlyList<ITypeMemberReference> GetMemberRefs() { return _memberRefIndex.Rows; } protected override MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference) { return MetadataTokens.MethodSpecificationHandle(_methodSpecIndex.GetOrAdd(reference)); } protected override IReadOnlyList<IGenericMethodInstanceReference> GetMethodSpecs() { return _methodSpecIndex.Rows; } protected override int GreatestMethodDefIndex => _methodDefs.NextRowId; protected override bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle) { int index; bool result = _typeRefIndex.TryGetValue(reference, out index); handle = MetadataTokens.TypeReferenceHandle(index); return result; } protected override TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference) { return MetadataTokens.TypeReferenceHandle(_typeRefIndex.GetOrAdd(reference)); } protected override IReadOnlyList<ITypeReference> GetTypeRefs() { return _typeRefIndex.Rows; } protected override TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference) { return MetadataTokens.TypeSpecificationHandle(_typeSpecIndex.GetOrAdd(reference)); } protected override IReadOnlyList<ITypeReference> GetTypeSpecs() { return _typeSpecIndex.Rows; } protected override StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle blobIndex) { return MetadataTokens.StandaloneSignatureHandle(_standAloneSignatureIndex.GetOrAdd(blobIndex)); } protected override IReadOnlyList<BlobHandle> GetStandaloneSignatureBlobHandles() { return _standAloneSignatureIndex.Rows; } protected override void OnIndicesCreated() { var module = (IPEDeltaAssemblyBuilder)this.module; module.OnCreatedIndices(this.Context.Diagnostics); } protected override void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef) { var change = _changes.GetChange(typeDef); switch (change) { case SymbolChange.Added: _typeDefs.Add(typeDef); _changedTypeDefs.Add(typeDef); var typeParameters = this.GetConsolidatedTypeParameters(typeDef); if (typeParameters != null) { foreach (var typeParameter in typeParameters) { _genericParameters.Add(typeParameter); } } break; case SymbolChange.Updated: _typeDefs.AddUpdated(typeDef); _changedTypeDefs.Add(typeDef); break; case SymbolChange.ContainsChanges: // Members changed. // We keep this list separately because we don't want to output duplicate typedef entries in the EnC log, // which uses _typeDefs, but it's simpler to let the members output those rows for the updated typedefs // with the right update type. _changedTypeDefs.Add(typeDef); break; case SymbolChange.None: // No changes to type. return; default: throw ExceptionUtilities.UnexpectedValue(change); } int typeRowId = _typeDefs.GetRowId(typeDef); foreach (var eventDef in typeDef.GetEvents(this.Context)) { if (!_eventMap.Contains(typeRowId)) { _eventMap.Add(typeRowId); } this.AddDefIfNecessary(_eventDefs, eventDef); } foreach (var fieldDef in typeDef.GetFields(this.Context)) { this.AddDefIfNecessary(_fieldDefs, fieldDef); } foreach (var methodDef in typeDef.GetMethods(this.Context)) { this.AddDefIfNecessary(_methodDefs, methodDef); var methodChange = _changes.GetChange(methodDef); if (methodChange == SymbolChange.Added) { _firstParamRowMap.Add(GetMethodDefinitionHandle(methodDef), _parameterDefs.NextRowId); foreach (var paramDef in this.GetParametersToEmit(methodDef)) { _parameterDefs.Add(paramDef); _parameterDefList.Add(paramDef, methodDef); } } else if (methodChange == SymbolChange.Updated) { // If we're re-emitting parameters for an existing method we need to find their original row numbers // and reuse them so the EnCLog, EnCMap and CustomAttributes tables refer to the right rows // Unfortunately we have to check the original metadata and deltas separately as nothing tracks the aggregate data // in a way that we can use var handle = GetMethodDefinitionHandle(methodDef); if (_previousGeneration.OriginalMetadata.MetadataReader.GetTableRowCount(TableIndex.MethodDef) >= MetadataTokens.GetRowNumber(handle)) { EmitParametersFromOriginalMetadata(methodDef, handle); } else { EmitParametersFromDelta(methodDef, handle); } } if (methodChange == SymbolChange.Added) { if (methodDef.GenericParameterCount > 0) { foreach (var typeParameter in methodDef.GenericParameters) { _genericParameters.Add(typeParameter); } } } } foreach (var propertyDef in typeDef.GetProperties(this.Context)) { if (!_propertyMap.Contains(typeRowId)) { _propertyMap.Add(typeRowId); } this.AddDefIfNecessary(_propertyDefs, propertyDef); } var implementingMethods = ArrayBuilder<int>.GetInstance(); // First, visit all MethodImplementations and add to this.methodImplList. foreach (var methodImpl in typeDef.GetExplicitImplementationOverrides(Context)) { var methodDef = (IMethodDefinition?)methodImpl.ImplementingMethod.AsDefinition(this.Context); RoslynDebug.AssertNotNull(methodDef); int methodDefRowId = _methodDefs.GetRowId(methodDef); // If there are N existing MethodImpl entries for this MethodDef, // those will be index:1, ..., index:N, so it's sufficient to check for index:1. var key = new MethodImplKey(methodDefRowId, index: 1); if (!_methodImpls.Contains(key)) { implementingMethods.Add(methodDefRowId); this.methodImplList.Add(methodImpl); } } // Next, add placeholders to this.methodImpls for items added above. foreach (var methodDefIndex in implementingMethods) { int index = 1; while (true) { var key = new MethodImplKey(methodDefIndex, index); if (!_methodImpls.Contains(key)) { _methodImpls.Add(key); break; } index++; } } implementingMethods.Free(); } private void EmitParametersFromOriginalMetadata(IMethodDefinition methodDef, MethodDefinitionHandle handle) { var def = _previousGeneration.OriginalMetadata.MetadataReader.GetMethodDefinition(handle); var parameters = def.GetParameters(); var paramDefinitions = this.GetParametersToEmit(methodDef); int i = 0; foreach (var param in parameters) { var paramDef = paramDefinitions[i]; _parameterDefs.AddUpdated(paramDef); _existingParameterDefs.Add(paramDef, MetadataTokens.GetRowNumber(param)); _parameterDefList.Add(paramDef, methodDef); i++; } } private void EmitParametersFromDelta(IMethodDefinition methodDef, MethodDefinitionHandle handle) { var ok = _previousGeneration.FirstParamRowMap.TryGetValue(handle, out var firstRowId); Debug.Assert(ok); foreach (var paramDef in GetParametersToEmit(methodDef)) { _parameterDefs.AddUpdated(paramDef); _existingParameterDefs.Add(paramDef, firstRowId++); _parameterDefList.Add(paramDef, methodDef); } } private bool AddDefIfNecessary<T>(DefinitionIndex<T> defIndex, T def) where T : class, IDefinition { switch (_changes.GetChange(def)) { case SymbolChange.Added: defIndex.Add(def); return true; case SymbolChange.Updated: defIndex.AddUpdated(def); return false; case SymbolChange.ContainsChanges: Debug.Assert(def is INestedTypeDefinition); // Changes to members within nested type only. return false; default: // No changes to member or container. return false; } } protected override ReferenceIndexer CreateReferenceVisitor() { return new DeltaReferenceIndexer(this); } protected override void ReportReferencesToAddedSymbols() { foreach (var typeRef in GetTypeRefs()) { ReportReferencesToAddedSymbol(typeRef.GetInternalSymbol()); } foreach (var memberRef in GetMemberRefs()) { ReportReferencesToAddedSymbol(memberRef.GetInternalSymbol()); } } private void ReportReferencesToAddedSymbol(ISymbolInternal? symbol) { if (symbol != null && _changes.IsAdded(symbol.GetISymbol())) { Context.Diagnostics.Add(messageProvider.CreateDiagnostic( messageProvider.ERR_EncReferenceToAddedMember, GetSymbolLocation(symbol), symbol.Name, symbol.ContainingAssembly.Name)); } } protected override StandaloneSignatureHandle SerializeLocalVariablesSignature(IMethodBody body) { StandaloneSignatureHandle localSignatureHandle; var localVariables = body.LocalVariables; var encInfos = ArrayBuilder<EncLocalInfo>.GetInstance(); if (localVariables.Length > 0) { var writer = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(writer).LocalVariableSignature(localVariables.Length); foreach (ILocalDefinition local in localVariables) { var signature = local.Signature; if (signature == null) { int start = writer.Count; SerializeLocalVariableType(encoder.AddVariable(), local); signature = writer.ToArray(start, writer.Count - start); } else { writer.WriteBytes(signature); } encInfos.Add(CreateEncLocalInfo(local, signature)); } BlobHandle blobIndex = metadata.GetOrAddBlob(writer); localSignatureHandle = GetOrAddStandaloneSignatureHandle(blobIndex); writer.Free(); } else { localSignatureHandle = default; } var info = new AddedOrChangedMethodInfo( body.MethodId, encInfos.ToImmutable(), body.LambdaDebugInfo, body.ClosureDebugInfo, body.StateMachineTypeName, body.StateMachineHoistedLocalSlots, body.StateMachineAwaiterSlots); _addedOrChangedMethods.Add(body.MethodDefinition, info); encInfos.Free(); return localSignatureHandle; } private EncLocalInfo CreateEncLocalInfo(ILocalDefinition localDef, byte[] signature) { if (localDef.SlotInfo.Id.IsNone) { return new EncLocalInfo(signature); } // local type is already translated, but not recursively ITypeReference translatedType = localDef.Type; if (translatedType.GetInternalSymbol() is ITypeSymbolInternal typeSymbol) { translatedType = Context.Module.EncTranslateType(typeSymbol, Context.Diagnostics); } return new EncLocalInfo(localDef.SlotInfo, translatedType, localDef.Constraints, signature); } protected override int AddCustomAttributesToTable(EntityHandle parentHandle, IEnumerable<ICustomAttribute> attributes) { // The base class will write out the actual metadata for us var numAttributesEmitted = base.AddCustomAttributesToTable(parentHandle, attributes); // We need to keep track of all of the things attributes could be associated with in this delta, in order to populate the EncLog and Map tables _customAttributeParentCounts.Add(parentHandle, numAttributesEmitted); return numAttributesEmitted; } public override void PopulateEncTables(ImmutableArray<int> typeSystemRowCounts) { Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncLog] == 0); Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncMap] == 0); PopulateEncLogTableRows(typeSystemRowCounts, out var customAttributeEncMapRows, out var paramEncMapRows); PopulateEncMapTableRows(typeSystemRowCounts, customAttributeEncMapRows, paramEncMapRows); } private void PopulateEncLogTableRows(ImmutableArray<int> rowCounts, out List<int> customAttributeEncMapRows, out List<int> paramEncMapRows) { // The EncLog table is a log of all the operations needed // to update the previous metadata. That means all // new references must be added to the EncLog. var previousSizes = _previousGeneration.TableSizes; var deltaSizes = this.GetDeltaTableSizes(rowCounts); PopulateEncLogTableRows(TableIndex.AssemblyRef, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.ModuleRef, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.MemberRef, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.MethodSpec, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.TypeRef, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.TypeSpec, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.StandAloneSig, previousSizes, deltaSizes); PopulateEncLogTableRows(_typeDefs, TableIndex.TypeDef); PopulateEncLogTableRows(TableIndex.EventMap, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.PropertyMap, previousSizes, deltaSizes); PopulateEncLogTableEventsOrProperties(_eventDefs, TableIndex.Event, EditAndContinueOperation.AddEvent, _eventMap, TableIndex.EventMap); PopulateEncLogTableFieldsOrMethods(_fieldDefs, TableIndex.Field, EditAndContinueOperation.AddField); PopulateEncLogTableFieldsOrMethods(_methodDefs, TableIndex.MethodDef, EditAndContinueOperation.AddMethod); PopulateEncLogTableEventsOrProperties(_propertyDefs, TableIndex.Property, EditAndContinueOperation.AddProperty, _propertyMap, TableIndex.PropertyMap); PopulateEncLogTableParameters(out paramEncMapRows); PopulateEncLogTableRows(TableIndex.Constant, previousSizes, deltaSizes); PopulateEncLogTableCustomAttributes(out customAttributeEncMapRows); PopulateEncLogTableRows(TableIndex.DeclSecurity, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.ClassLayout, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.FieldLayout, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.MethodSemantics, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.MethodImpl, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.ImplMap, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.FieldRva, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.NestedClass, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.GenericParam, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.InterfaceImpl, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.GenericParamConstraint, previousSizes, deltaSizes); } private void PopulateEncLogTableEventsOrProperties<T>( DefinitionIndex<T> index, TableIndex table, EditAndContinueOperation addCode, EventOrPropertyMapIndex map, TableIndex mapTable) where T : class, ITypeDefinitionMember { foreach (var member in index.GetRows()) { if (index.IsAddedNotChanged(member)) { int typeRowId = MetadataTokens.GetRowNumber(GetTypeDefinitionHandle(member.ContainingTypeDefinition)); int mapRowId = map.GetRowId(typeRowId); metadata.AddEncLogEntry( entity: MetadataTokens.Handle(mapTable, mapRowId), code: addCode); } metadata.AddEncLogEntry( entity: MetadataTokens.Handle(table, index.GetRowId(member)), code: EditAndContinueOperation.Default); } } private void PopulateEncLogTableFieldsOrMethods<T>( DefinitionIndex<T> index, TableIndex tableIndex, EditAndContinueOperation addCode) where T : class, ITypeDefinitionMember { foreach (var member in index.GetRows()) { if (index.IsAddedNotChanged(member)) { metadata.AddEncLogEntry( entity: GetTypeDefinitionHandle(member.ContainingTypeDefinition), code: addCode); } metadata.AddEncLogEntry( entity: MetadataTokens.Handle(tableIndex, index.GetRowId(member)), code: EditAndContinueOperation.Default); } } private void PopulateEncLogTableParameters(out List<int> paramEncMapRows) { paramEncMapRows = new List<int>(); var parameterFirstId = _parameterDefs.FirstRowId; int i = 0; foreach (var paramDef in GetParameterDefs()) { var methodDef = _parameterDefList[paramDef]; if (_methodDefs.IsAddedNotChanged(methodDef)) { // For parameters on new methods we emit AddParameter rows for the method too paramEncMapRows.Add(parameterFirstId + i); metadata.AddEncLogEntry( entity: MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(methodDef)), code: EditAndContinueOperation.AddParameter); metadata.AddEncLogEntry( entity: MetadataTokens.ParameterHandle(parameterFirstId + i), code: EditAndContinueOperation.Default); i++; } else { // For previously emitted parameters we just update the Param row var param = GetParameterHandle(paramDef); paramEncMapRows.Add(MetadataTokens.GetRowNumber(param)); metadata.AddEncLogEntry( entity: param, code: EditAndContinueOperation.Default); } } } /// <summary> /// CustomAttributes point to their target via the Parent column so we cannot simply output new rows /// in the delta or we would end up with duplicates, but we also don't want to do complex logic to determine /// which attributes have changes, so we just emit them all. /// This means our logic for emitting CustomAttributes is to update any existing rows, either from the original /// compilation or subsequent deltas, and only add more if we need to. The EncLog table is the thing that tells /// the runtime which row a CustomAttributes row is (ie, new or existing) /// </summary> private void PopulateEncLogTableCustomAttributes(out List<int> customAttributeEncMapRows) { customAttributeEncMapRows = new List<int>(); // List of attributes that need to be emitted to delete a previously emitted attribute var deletedAttributeRows = new List<(int parentRowId, HandleKind kind)>(); var customAttributesAdded = new Dictionary<EntityHandle, ArrayBuilder<int>>(); // The data in _previousGeneration.CustomAttributesAdded is not nicely sorted, or even necessarily contiguous // so we need to map each target onto the rows its attributes occupy so we know which rows to update var lastRowId = _previousGeneration.OriginalMetadata.MetadataReader.GetTableRowCount(TableIndex.CustomAttribute); if (_previousGeneration.CustomAttributesAdded.Count > 0) { lastRowId = _previousGeneration.CustomAttributesAdded.SelectMany(s => s.Value).Max(); } // Iterate through the parents we emitted custom attributes for, in parent order foreach (var (parent, count) in _customAttributeParentCounts.OrderBy(kvp => CodedIndex.HasCustomAttribute(kvp.Key))) { int index = 0; // First we try to update any existing attributes. // GetCustomAttributes does a binary search, so is fast. We presume that the number of rows in the original metadata // greatly outnumbers the amount of parents emitted in this delta so even with repeated searches this is still // quicker than iterating the entire original table, even once. var existingCustomAttributes = _previousGeneration.OriginalMetadata.MetadataReader.GetCustomAttributes(parent); foreach (var attributeHandle in existingCustomAttributes) { int rowId = MetadataTokens.GetRowNumber(attributeHandle); AddLogEntryOrDelete(rowId, parent, add: index < count, customAttributeEncMapRows); index++; } // If we emitted any attributes for this parent in previous deltas then we either need to update // them next, or delete them if necessary if (_previousGeneration.CustomAttributesAdded.TryGetValue(parent, out var rowIds)) { foreach (var rowId in rowIds) { TrackCustomAttributeAdded(rowId, parent); AddLogEntryOrDelete(rowId, parent, add: index < count, customAttributeEncMapRows); index++; } } // Finally if there are still attributes for this parent left, they are additions new to this delta for (int i = index; i < count; i++) { lastRowId++; TrackCustomAttributeAdded(lastRowId, parent); AddEncLogEntry(lastRowId, customAttributeEncMapRows); } } // Save the attributes we've emitted, and the ones from previous deltas, for use in the next generation foreach (var (parent, rowIds) in customAttributesAdded) { _customAttributesAdded.Add(parent, rowIds.ToImmutableAndFree()); } // Add attributes and log entries for everything we've deleted foreach (var row in deletedAttributeRows) { // now emit a "delete" row with a parent that is for the 0 row of the same table as the existing one if (!MetadataTokens.TryGetTableIndex(row.kind, out var tableIndex)) { throw new InvalidOperationException("Trying to delete a custom attribute for a parent kind that doesn't have a matching table index."); } metadata.AddCustomAttribute(MetadataTokens.Handle(tableIndex, 0), MetadataTokens.EntityHandle(TableIndex.MemberRef, 0), value: default); AddEncLogEntry(row.parentRowId, customAttributeEncMapRows); } void AddEncLogEntry(int rowId, List<int> customAttributeEncMapRows) { customAttributeEncMapRows.Add(rowId); metadata.AddEncLogEntry( entity: MetadataTokens.CustomAttributeHandle(rowId), code: EditAndContinueOperation.Default); } void AddLogEntryOrDelete(int rowId, EntityHandle parent, bool add, List<int> customAttributeEncMapRows) { if (add) { // Update this row AddEncLogEntry(rowId, customAttributeEncMapRows); } else { // Delete this row deletedAttributeRows.Add((rowId, parent.Kind)); } } void TrackCustomAttributeAdded(int nextRowId, EntityHandle parent) { if (!customAttributesAdded.TryGetValue(parent, out var existing)) { existing = ArrayBuilder<int>.GetInstance(); customAttributesAdded.Add(parent, existing); } existing.Add(nextRowId); } } private void PopulateEncLogTableRows<T>(DefinitionIndex<T> index, TableIndex tableIndex) where T : class, IDefinition { foreach (var member in index.GetRows()) { metadata.AddEncLogEntry( entity: MetadataTokens.Handle(tableIndex, index.GetRowId(member)), code: EditAndContinueOperation.Default); } } private void PopulateEncLogTableRows(TableIndex tableIndex, ImmutableArray<int> previousSizes, ImmutableArray<int> deltaSizes) { PopulateEncLogTableRows(tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]); } private void PopulateEncLogTableRows(TableIndex tableIndex, int firstRowId, int tokenCount) { for (int i = 0; i < tokenCount; i++) { metadata.AddEncLogEntry( entity: MetadataTokens.Handle(tableIndex, firstRowId + i), code: EditAndContinueOperation.Default); } } private void PopulateEncMapTableRows(ImmutableArray<int> rowCounts, List<int> customAttributeEncMapRows, List<int> paramEncMapRows) { // The EncMap table maps from offset in each table in the delta // metadata to token. As such, the EncMap is a concatenated // list of all tokens in all tables from the delta sorted by table // and, within each table, sorted by row. var tokens = ArrayBuilder<EntityHandle>.GetInstance(); var previousSizes = _previousGeneration.TableSizes; var deltaSizes = this.GetDeltaTableSizes(rowCounts); AddReferencedTokens(tokens, TableIndex.AssemblyRef, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.ModuleRef, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.MemberRef, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.MethodSpec, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.TypeRef, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.TypeSpec, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.StandAloneSig, previousSizes, deltaSizes); AddDefinitionTokens(tokens, _typeDefs, TableIndex.TypeDef); AddDefinitionTokens(tokens, _eventDefs, TableIndex.Event); AddDefinitionTokens(tokens, _fieldDefs, TableIndex.Field); AddDefinitionTokens(tokens, _methodDefs, TableIndex.MethodDef); AddDefinitionTokens(tokens, _propertyDefs, TableIndex.Property); AddRowNumberTokens(tokens, paramEncMapRows, TableIndex.Param); AddReferencedTokens(tokens, TableIndex.Constant, previousSizes, deltaSizes); AddRowNumberTokens(tokens, customAttributeEncMapRows, TableIndex.CustomAttribute); AddReferencedTokens(tokens, TableIndex.DeclSecurity, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.ClassLayout, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.FieldLayout, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.EventMap, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.PropertyMap, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.MethodSemantics, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.MethodImpl, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.ImplMap, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.FieldRva, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.NestedClass, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.GenericParam, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.InterfaceImpl, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.GenericParamConstraint, previousSizes, deltaSizes); tokens.Sort(HandleComparer.Default); // Should not be any duplicates. Debug.Assert(tokens.Distinct().Count() == tokens.Count); foreach (var token in tokens) { metadata.AddEncMapEntry(token); } tokens.Free(); // Populate Portable PDB EncMap table with MethodDebugInformation mapping, // which corresponds 1:1 to MethodDef mapping. if (_debugMetadataOpt != null) { var debugTokens = ArrayBuilder<EntityHandle>.GetInstance(); AddDefinitionTokens(debugTokens, _methodDefs, TableIndex.MethodDebugInformation); debugTokens.Sort(HandleComparer.Default); // Should not be any duplicates. Debug.Assert(debugTokens.Distinct().Count() == debugTokens.Count); foreach (var token in debugTokens) { _debugMetadataOpt.AddEncMapEntry(token); } debugTokens.Free(); } #if DEBUG // The following tables are either represented in the EncMap // or specifically ignored. The rest should be empty. var handledTables = new TableIndex[] { TableIndex.Module, TableIndex.TypeRef, TableIndex.TypeDef, TableIndex.Field, TableIndex.MethodDef, TableIndex.Param, TableIndex.MemberRef, TableIndex.Constant, TableIndex.CustomAttribute, TableIndex.DeclSecurity, TableIndex.ClassLayout, TableIndex.FieldLayout, TableIndex.StandAloneSig, TableIndex.EventMap, TableIndex.Event, TableIndex.PropertyMap, TableIndex.Property, TableIndex.MethodSemantics, TableIndex.MethodImpl, TableIndex.ModuleRef, TableIndex.TypeSpec, TableIndex.ImplMap, // FieldRva is not needed since we only emit fields with explicit mapping // for <PrivateImplementationDetails> and that class is not used in ENC. // If we need FieldRva in the future, we'll need a corresponding test. // (See EditAndContinueTests.FieldRva that was deleted in this change.) //TableIndex.FieldRva, TableIndex.EncLog, TableIndex.EncMap, TableIndex.Assembly, TableIndex.AssemblyRef, TableIndex.MethodSpec, TableIndex.NestedClass, TableIndex.GenericParam, TableIndex.InterfaceImpl, TableIndex.GenericParamConstraint, }; for (int i = 0; i < rowCounts.Length; i++) { if (handledTables.Contains((TableIndex)i)) { continue; } Debug.Assert(rowCounts[i] == 0); } #endif } private static void AddReferencedTokens( ArrayBuilder<EntityHandle> builder, TableIndex tableIndex, ImmutableArray<int> previousSizes, ImmutableArray<int> deltaSizes) { AddReferencedTokens(builder, tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]); } private static void AddReferencedTokens(ArrayBuilder<EntityHandle> builder, TableIndex tableIndex, int firstRowId, int nTokens) { for (int i = 0; i < nTokens; i++) { builder.Add(MetadataTokens.Handle(tableIndex, firstRowId + i)); } } private static void AddDefinitionTokens<T>(ArrayBuilder<EntityHandle> tokens, DefinitionIndex<T> index, TableIndex tableIndex) where T : class, IDefinition { foreach (var member in index.GetRows()) { tokens.Add(MetadataTokens.Handle(tableIndex, index.GetRowId(member))); } } private static void AddRowNumberTokens(ArrayBuilder<EntityHandle> tokens, IEnumerable<int> rowNumbers, TableIndex tableIndex) { foreach (var row in rowNumbers) { tokens.Add(MetadataTokens.Handle(tableIndex, row)); } } protected override void PopulateEventMapTableRows() { foreach (var typeId in _eventMap.GetRows()) { metadata.AddEventMap( declaringType: MetadataTokens.TypeDefinitionHandle(typeId), eventList: MetadataTokens.EventDefinitionHandle(_eventMap.GetRowId(typeId))); } } protected override void PopulatePropertyMapTableRows() { foreach (var typeId in _propertyMap.GetRows()) { metadata.AddPropertyMap( declaringType: MetadataTokens.TypeDefinitionHandle(typeId), propertyList: MetadataTokens.PropertyDefinitionHandle(_propertyMap.GetRowId(typeId))); } } private abstract class DefinitionIndexBase<T> where T : notnull { protected readonly Dictionary<T, int> added; // Definitions added in this generation. protected readonly List<T> rows; // Rows in this generation, containing adds and updates. private readonly int _firstRowId; // First row in this generation. private bool _frozen; public DefinitionIndexBase(int lastRowId, IEqualityComparer<T>? comparer = null) { this.added = new Dictionary<T, int>(comparer); this.rows = new List<T>(); _firstRowId = lastRowId + 1; } public abstract bool TryGetRowId(T item, out int rowId); public int GetRowId(T item) { bool containsItem = TryGetRowId(item, out int rowId); // Fails if we are attempting to make a change that should have been reported as rude, // e.g. the corresponding definitions type don't match, etc. Debug.Assert(containsItem); Debug.Assert(rowId > 0); return rowId; } public bool Contains(T item) => TryGetRowId(item, out _); // A method rather than a property since it freezes the table. public IReadOnlyDictionary<T, int> GetAdded() { this.Freeze(); return this.added; } // A method rather than a property since it freezes the table. public IReadOnlyList<T> GetRows() { this.Freeze(); return this.rows; } public int FirstRowId { get { return _firstRowId; } } public int NextRowId { get { return this.added.Count + _firstRowId; } } public bool IsFrozen { get { return _frozen; } } protected virtual void OnFrozen() { #if DEBUG // Verify the rows are sorted. int prev = 0; foreach (var row in this.rows) { int next = this.added[row]; Debug.Assert(prev < next); prev = next; } #endif } private void Freeze() { if (!_frozen) { _frozen = true; this.OnFrozen(); } } } private sealed class DefinitionIndex<T> : DefinitionIndexBase<T> where T : class, IDefinition { public delegate bool TryGetExistingIndex(T item, out int index); private readonly TryGetExistingIndex _tryGetExistingIndex; // Map of row id to def for all defs. This could be an array indexed // by row id but the array could be large and sparsely populated // if there are many defs in the previous generation but few // references to those defs in the current generation. private readonly Dictionary<int, T> _map; public DefinitionIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId) : base(lastRowId, ReferenceEqualityComparer.Instance) { _tryGetExistingIndex = tryGetExistingIndex; _map = new Dictionary<int, T>(); } public override bool TryGetRowId(T item, out int index) { if (this.added.TryGetValue(item, out index)) { return true; } if (_tryGetExistingIndex(item, out index)) { #if DEBUG Debug.Assert(!_map.TryGetValue(index, out var other) || ((object)other == (object)item)); #endif _map[index] = item; return true; } return false; } public T GetDefinition(int rowId) => _map[rowId]; public void Add(T item) { Debug.Assert(!this.IsFrozen); int index = this.NextRowId; this.added.Add(item, index); _map[index] = item; this.rows.Add(item); } /// <summary> /// Add an item from a previous generation /// that has been updated in this generation. /// </summary> public void AddUpdated(T item) { Debug.Assert(!this.IsFrozen); this.rows.Add(item); } public bool IsAddedNotChanged(T item) => added.ContainsKey(item); protected override void OnFrozen() => rows.Sort((x, y) => GetRowId(x).CompareTo(GetRowId(y))); } private bool TryGetExistingTypeDefIndex(ITypeDefinition item, out int index) { if (_previousGeneration.TypesAdded.TryGetValue(item, out index)) { return true; } TypeDefinitionHandle handle; if (_definitionMap.TryGetTypeHandle(item, out handle)) { index = MetadataTokens.GetRowNumber(handle); Debug.Assert(index > 0); return true; } index = 0; return false; } private bool TryGetExistingEventDefIndex(IEventDefinition item, out int index) { if (_previousGeneration.EventsAdded.TryGetValue(item, out index)) { return true; } EventDefinitionHandle handle; if (_definitionMap.TryGetEventHandle(item, out handle)) { index = MetadataTokens.GetRowNumber(handle); Debug.Assert(index > 0); return true; } index = 0; return false; } private bool TryGetExistingFieldDefIndex(IFieldDefinition item, out int index) { if (_previousGeneration.FieldsAdded.TryGetValue(item, out index)) { return true; } FieldDefinitionHandle handle; if (_definitionMap.TryGetFieldHandle(item, out handle)) { index = MetadataTokens.GetRowNumber(handle); Debug.Assert(index > 0); return true; } index = 0; return false; } private bool TryGetExistingMethodDefIndex(IMethodDefinition item, out int index) { if (_previousGeneration.MethodsAdded.TryGetValue(item, out index)) { return true; } MethodDefinitionHandle handle; if (_definitionMap.TryGetMethodHandle(item, out handle)) { index = MetadataTokens.GetRowNumber(handle); Debug.Assert(index > 0); return true; } index = 0; return false; } private bool TryGetExistingPropertyDefIndex(IPropertyDefinition item, out int index) { if (_previousGeneration.PropertiesAdded.TryGetValue(item, out index)) { return true; } PropertyDefinitionHandle handle; if (_definitionMap.TryGetPropertyHandle(item, out handle)) { index = MetadataTokens.GetRowNumber(handle); Debug.Assert(index > 0); return true; } index = 0; return false; } private bool TryGetExistingParameterDefIndex(IParameterDefinition item, out int index) { return _existingParameterDefs.TryGetValue(item, out index); } private bool TryGetExistingEventMapIndex(int item, out int index) { if (_previousGeneration.EventMapAdded.TryGetValue(item, out index)) { return true; } if (_previousGeneration.TypeToEventMap.TryGetValue(item, out index)) { return true; } index = 0; return false; } private bool TryGetExistingPropertyMapIndex(int item, out int index) { if (_previousGeneration.PropertyMapAdded.TryGetValue(item, out index)) { return true; } if (_previousGeneration.TypeToPropertyMap.TryGetValue(item, out index)) { return true; } index = 0; return false; } private bool TryGetExistingMethodImplIndex(MethodImplKey item, out int index) { if (_previousGeneration.MethodImplsAdded.TryGetValue(item, out index)) { return true; } if (_previousGeneration.MethodImpls.TryGetValue(item, out index)) { return true; } index = 0; return false; } private sealed class GenericParameterIndex : DefinitionIndexBase<IGenericParameter> { public GenericParameterIndex(int lastRowId) : base(lastRowId, ReferenceEqualityComparer.Instance) { } public override bool TryGetRowId(IGenericParameter item, out int index) { return this.added.TryGetValue(item, out index); } public void Add(IGenericParameter item) { Debug.Assert(!this.IsFrozen); int index = this.NextRowId; this.added.Add(item, index); this.rows.Add(item); } } private sealed class EventOrPropertyMapIndex : DefinitionIndexBase<int> { public delegate bool TryGetExistingIndex(int item, out int index); private readonly TryGetExistingIndex _tryGetExistingIndex; public EventOrPropertyMapIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId) : base(lastRowId) { _tryGetExistingIndex = tryGetExistingIndex; } public override bool TryGetRowId(int item, out int index) { if (this.added.TryGetValue(item, out index)) { return true; } if (_tryGetExistingIndex(item, out index)) { return true; } index = 0; return false; } public void Add(int item) { Debug.Assert(!this.IsFrozen); int index = this.NextRowId; this.added.Add(item, index); this.rows.Add(item); } } private sealed class MethodImplIndex : DefinitionIndexBase<MethodImplKey> { private readonly DeltaMetadataWriter _writer; public MethodImplIndex(DeltaMetadataWriter writer, int lastRowId) : base(lastRowId) { _writer = writer; } public override bool TryGetRowId(MethodImplKey item, out int index) { if (this.added.TryGetValue(item, out index)) { return true; } if (_writer.TryGetExistingMethodImplIndex(item, out index)) { return true; } index = 0; return false; } public void Add(MethodImplKey item) { Debug.Assert(!this.IsFrozen); int index = this.NextRowId; this.added.Add(item, index); this.rows.Add(item); } } private sealed class DeltaReferenceIndexer : ReferenceIndexer { private readonly SymbolChanges _changes; public DeltaReferenceIndexer(DeltaMetadataWriter writer) : base(writer) { _changes = writer._changes; } public override void Visit(CommonPEModuleBuilder module) { Visit(module.GetTopLevelTypeDefinitions(metadataWriter.Context)); } public override void Visit(IEventDefinition eventDefinition) { Debug.Assert(this.ShouldVisit(eventDefinition)); base.Visit(eventDefinition); } public override void Visit(IFieldDefinition fieldDefinition) { Debug.Assert(this.ShouldVisit(fieldDefinition)); base.Visit(fieldDefinition); } public override void Visit(ILocalDefinition localDefinition) { if (localDefinition.Signature == null) { base.Visit(localDefinition); } } public override void Visit(IMethodDefinition method) { Debug.Assert(this.ShouldVisit(method)); base.Visit(method); } public override void Visit(Cci.MethodImplementation methodImplementation) { // Unless the implementing method was added, // the method implementation already exists. var methodDef = (IMethodDefinition?)methodImplementation.ImplementingMethod.AsDefinition(this.Context); RoslynDebug.AssertNotNull(methodDef); if (_changes.GetChange(methodDef) == SymbolChange.Added) { base.Visit(methodImplementation); } } public override void Visit(INamespaceTypeDefinition namespaceTypeDefinition) { Debug.Assert(this.ShouldVisit(namespaceTypeDefinition)); base.Visit(namespaceTypeDefinition); } public override void Visit(INestedTypeDefinition nestedTypeDefinition) { Debug.Assert(this.ShouldVisit(nestedTypeDefinition)); base.Visit(nestedTypeDefinition); } public override void Visit(IPropertyDefinition propertyDefinition) { Debug.Assert(this.ShouldVisit(propertyDefinition)); base.Visit(propertyDefinition); } public override void Visit(ITypeDefinition typeDefinition) { if (this.ShouldVisit(typeDefinition)) { base.Visit(typeDefinition); } } public override void Visit(ITypeDefinitionMember typeMember) { if (this.ShouldVisit(typeMember)) { base.Visit(typeMember); } } private bool ShouldVisit(IDefinition def) { return _changes.GetChange(def) != SymbolChange.None; } } } }
// 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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using Microsoft.Cci; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.Emit { internal sealed class DeltaMetadataWriter : MetadataWriter { private readonly EmitBaseline _previousGeneration; private readonly Guid _encId; private readonly DefinitionMap _definitionMap; private readonly SymbolChanges _changes; /// <summary> /// Type definitions containing any changes (includes added types). /// </summary> private readonly List<ITypeDefinition> _changedTypeDefs; private readonly DefinitionIndex<ITypeDefinition> _typeDefs; private readonly DefinitionIndex<IEventDefinition> _eventDefs; private readonly DefinitionIndex<IFieldDefinition> _fieldDefs; private readonly DefinitionIndex<IMethodDefinition> _methodDefs; private readonly DefinitionIndex<IPropertyDefinition> _propertyDefs; private readonly DefinitionIndex<IParameterDefinition> _parameterDefs; private readonly Dictionary<IParameterDefinition, IMethodDefinition> _parameterDefList; private readonly GenericParameterIndex _genericParameters; private readonly EventOrPropertyMapIndex _eventMap; private readonly EventOrPropertyMapIndex _propertyMap; private readonly MethodImplIndex _methodImpls; // For the EncLog table we need to know which things we're emitting custom attributes for so we can // correctly map the attributes to row numbers of existing attributes for that target private readonly Dictionary<EntityHandle, int> _customAttributeParentCounts; // Keep track of which CustomAttributes rows are added in this and previous deltas, over what is in the // original metadata private readonly Dictionary<EntityHandle, ImmutableArray<int>> _customAttributesAdded; private readonly Dictionary<IParameterDefinition, int> _existingParameterDefs; private readonly Dictionary<MethodDefinitionHandle, int> _firstParamRowMap; private readonly HeapOrReferenceIndex<AssemblyIdentity> _assemblyRefIndex; private readonly HeapOrReferenceIndex<string> _moduleRefIndex; private readonly InstanceAndStructuralReferenceIndex<ITypeMemberReference> _memberRefIndex; private readonly InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference> _methodSpecIndex; private readonly TypeReferenceIndex _typeRefIndex; private readonly InstanceAndStructuralReferenceIndex<ITypeReference> _typeSpecIndex; private readonly HeapOrReferenceIndex<BlobHandle> _standAloneSignatureIndex; private readonly Dictionary<IMethodDefinition, AddedOrChangedMethodInfo> _addedOrChangedMethods; public DeltaMetadataWriter( EmitContext context, CommonMessageProvider messageProvider, EmitBaseline previousGeneration, Guid encId, DefinitionMap definitionMap, SymbolChanges changes, CancellationToken cancellationToken) : base(metadata: MakeTablesBuilder(previousGeneration), debugMetadataOpt: (context.Module.DebugInformationFormat == DebugInformationFormat.PortablePdb) ? new MetadataBuilder() : null, dynamicAnalysisDataWriterOpt: null, context: context, messageProvider: messageProvider, metadataOnly: false, deterministic: false, emitTestCoverageData: false, cancellationToken: cancellationToken) { Debug.Assert(previousGeneration != null); Debug.Assert(encId != default(Guid)); Debug.Assert(encId != previousGeneration.EncId); Debug.Assert(context.Module.DebugInformationFormat != DebugInformationFormat.Embedded); _previousGeneration = previousGeneration; _encId = encId; _definitionMap = definitionMap; _changes = changes; var sizes = previousGeneration.TableSizes; _changedTypeDefs = new List<ITypeDefinition>(); _typeDefs = new DefinitionIndex<ITypeDefinition>(this.TryGetExistingTypeDefIndex, sizes[(int)TableIndex.TypeDef]); _eventDefs = new DefinitionIndex<IEventDefinition>(this.TryGetExistingEventDefIndex, sizes[(int)TableIndex.Event]); _fieldDefs = new DefinitionIndex<IFieldDefinition>(this.TryGetExistingFieldDefIndex, sizes[(int)TableIndex.Field]); _methodDefs = new DefinitionIndex<IMethodDefinition>(this.TryGetExistingMethodDefIndex, sizes[(int)TableIndex.MethodDef]); _propertyDefs = new DefinitionIndex<IPropertyDefinition>(this.TryGetExistingPropertyDefIndex, sizes[(int)TableIndex.Property]); _parameterDefs = new DefinitionIndex<IParameterDefinition>(this.TryGetExistingParameterDefIndex, sizes[(int)TableIndex.Param]); _parameterDefList = new Dictionary<IParameterDefinition, IMethodDefinition>(Cci.SymbolEquivalentEqualityComparer.Instance); _genericParameters = new GenericParameterIndex(sizes[(int)TableIndex.GenericParam]); _eventMap = new EventOrPropertyMapIndex(this.TryGetExistingEventMapIndex, sizes[(int)TableIndex.EventMap]); _propertyMap = new EventOrPropertyMapIndex(this.TryGetExistingPropertyMapIndex, sizes[(int)TableIndex.PropertyMap]); _methodImpls = new MethodImplIndex(this, sizes[(int)TableIndex.MethodImpl]); _customAttributeParentCounts = new Dictionary<EntityHandle, int>(); _customAttributesAdded = new Dictionary<EntityHandle, ImmutableArray<int>>(); _firstParamRowMap = new Dictionary<MethodDefinitionHandle, int>(); _existingParameterDefs = new Dictionary<IParameterDefinition, int>(ReferenceEqualityComparer.Instance); _assemblyRefIndex = new HeapOrReferenceIndex<AssemblyIdentity>(this, lastRowId: sizes[(int)TableIndex.AssemblyRef]); _moduleRefIndex = new HeapOrReferenceIndex<string>(this, lastRowId: sizes[(int)TableIndex.ModuleRef]); _memberRefIndex = new InstanceAndStructuralReferenceIndex<ITypeMemberReference>(this, new MemberRefComparer(this), lastRowId: sizes[(int)TableIndex.MemberRef]); _methodSpecIndex = new InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference>(this, new MethodSpecComparer(this), lastRowId: sizes[(int)TableIndex.MethodSpec]); _typeRefIndex = new TypeReferenceIndex(this, lastRowId: sizes[(int)TableIndex.TypeRef]); _typeSpecIndex = new InstanceAndStructuralReferenceIndex<ITypeReference>(this, new TypeSpecComparer(this), lastRowId: sizes[(int)TableIndex.TypeSpec]); _standAloneSignatureIndex = new HeapOrReferenceIndex<BlobHandle>(this, lastRowId: sizes[(int)TableIndex.StandAloneSig]); _addedOrChangedMethods = new Dictionary<IMethodDefinition, AddedOrChangedMethodInfo>(Cci.SymbolEquivalentEqualityComparer.Instance); } private static MetadataBuilder MakeTablesBuilder(EmitBaseline previousGeneration) { return new MetadataBuilder( previousGeneration.UserStringStreamLength, previousGeneration.StringStreamLength, previousGeneration.BlobStreamLength, previousGeneration.GuidStreamLength); } private ImmutableArray<int> GetDeltaTableSizes(ImmutableArray<int> rowCounts) { var sizes = new int[MetadataTokens.TableCount]; rowCounts.CopyTo(sizes); sizes[(int)TableIndex.TypeRef] = _typeRefIndex.Rows.Count; sizes[(int)TableIndex.TypeDef] = _typeDefs.GetAdded().Count; sizes[(int)TableIndex.Field] = _fieldDefs.GetAdded().Count; sizes[(int)TableIndex.MethodDef] = _methodDefs.GetAdded().Count; sizes[(int)TableIndex.Param] = _parameterDefs.GetAdded().Count; sizes[(int)TableIndex.MemberRef] = _memberRefIndex.Rows.Count; sizes[(int)TableIndex.StandAloneSig] = _standAloneSignatureIndex.Rows.Count; sizes[(int)TableIndex.EventMap] = _eventMap.GetAdded().Count; sizes[(int)TableIndex.Event] = _eventDefs.GetAdded().Count; sizes[(int)TableIndex.PropertyMap] = _propertyMap.GetAdded().Count; sizes[(int)TableIndex.Property] = _propertyDefs.GetAdded().Count; sizes[(int)TableIndex.MethodImpl] = _methodImpls.GetAdded().Count; sizes[(int)TableIndex.ModuleRef] = _moduleRefIndex.Rows.Count; sizes[(int)TableIndex.TypeSpec] = _typeSpecIndex.Rows.Count; sizes[(int)TableIndex.AssemblyRef] = _assemblyRefIndex.Rows.Count; sizes[(int)TableIndex.GenericParam] = _genericParameters.GetAdded().Count; sizes[(int)TableIndex.MethodSpec] = _methodSpecIndex.Rows.Count; return ImmutableArray.Create(sizes); } internal EmitBaseline GetDelta(Compilation compilation, Guid encId, MetadataSizes metadataSizes) { var addedOrChangedMethodsByIndex = new Dictionary<int, AddedOrChangedMethodInfo>(); foreach (var pair in _addedOrChangedMethods) { addedOrChangedMethodsByIndex.Add(MetadataTokens.GetRowNumber(GetMethodDefinitionHandle(pair.Key)), pair.Value); } var previousTableSizes = _previousGeneration.TableEntriesAdded; var deltaTableSizes = GetDeltaTableSizes(metadataSizes.RowCounts); var tableSizes = new int[MetadataTokens.TableCount]; for (int i = 0; i < tableSizes.Length; i++) { tableSizes[i] = previousTableSizes[i] + deltaTableSizes[i]; } // If the previous generation is 0 (metadata) get the synthesized members from the current compilation's builder, // otherwise members from the current compilation have already been merged into the baseline. var synthesizedMembers = (_previousGeneration.Ordinal == 0) ? module.GetAllSynthesizedMembers() : _previousGeneration.SynthesizedMembers; var currentGenerationOrdinal = _previousGeneration.Ordinal + 1; var addedTypes = _typeDefs.GetAdded(); var generationOrdinals = CreateDictionary(_previousGeneration.GenerationOrdinals, SymbolEquivalentEqualityComparer.Instance); foreach (var (addedType, _) in addedTypes) { if (_changes.IsReplaced(addedType)) { generationOrdinals[addedType] = currentGenerationOrdinal; } } return _previousGeneration.With( compilation, module, currentGenerationOrdinal, encId, generationOrdinals, typesAdded: AddRange(_previousGeneration.TypesAdded, addedTypes, comparer: SymbolEquivalentEqualityComparer.Instance), eventsAdded: AddRange(_previousGeneration.EventsAdded, _eventDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance), fieldsAdded: AddRange(_previousGeneration.FieldsAdded, _fieldDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance), methodsAdded: AddRange(_previousGeneration.MethodsAdded, _methodDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance), firstParamRowMap: AddRange(_previousGeneration.FirstParamRowMap, _firstParamRowMap), propertiesAdded: AddRange(_previousGeneration.PropertiesAdded, _propertyDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance), eventMapAdded: AddRange(_previousGeneration.EventMapAdded, _eventMap.GetAdded()), propertyMapAdded: AddRange(_previousGeneration.PropertyMapAdded, _propertyMap.GetAdded()), methodImplsAdded: AddRange(_previousGeneration.MethodImplsAdded, _methodImpls.GetAdded()), customAttributesAdded: AddRange(_previousGeneration.CustomAttributesAdded, _customAttributesAdded), tableEntriesAdded: ImmutableArray.Create(tableSizes), // Blob stream is concatenated aligned. blobStreamLengthAdded: metadataSizes.GetAlignedHeapSize(HeapIndex.Blob) + _previousGeneration.BlobStreamLengthAdded, // String stream is concatenated unaligned. stringStreamLengthAdded: metadataSizes.HeapSizes[(int)HeapIndex.String] + _previousGeneration.StringStreamLengthAdded, // UserString stream is concatenated aligned. userStringStreamLengthAdded: metadataSizes.GetAlignedHeapSize(HeapIndex.UserString) + _previousGeneration.UserStringStreamLengthAdded, // Guid stream accumulates on the GUID heap unlike other heaps, so the previous generations are already included. guidStreamLengthAdded: metadataSizes.HeapSizes[(int)HeapIndex.Guid], anonymousTypeMap: ((IPEDeltaAssemblyBuilder)module).GetAnonymousTypeMap(), synthesizedDelegates: ((IPEDeltaAssemblyBuilder)module).GetSynthesizedDelegates(), synthesizedMembers: synthesizedMembers, addedOrChangedMethods: AddRange(_previousGeneration.AddedOrChangedMethods, addedOrChangedMethodsByIndex), debugInformationProvider: _previousGeneration.DebugInformationProvider, localSignatureProvider: _previousGeneration.LocalSignatureProvider); } private static Dictionary<K, V> CreateDictionary<K, V>(IReadOnlyDictionary<K, V> dictionary, IEqualityComparer<K>? comparer) where K : notnull { var result = new Dictionary<K, V>(comparer); foreach (var pair in dictionary) { result.Add(pair.Key, pair.Value); } return result; } private static IReadOnlyDictionary<K, V> AddRange<K, V>(IReadOnlyDictionary<K, V> previous, IReadOnlyDictionary<K, V> current, IEqualityComparer<K>? comparer = null) where K : notnull { if (previous.Count == 0) { return current; } if (current.Count == 0) { return previous; } var result = CreateDictionary(previous, comparer); foreach (var pair in current) { // Use the latest symbol. result[pair.Key] = pair.Value; } return result; } /// <summary> /// Return tokens for all updated debuggable methods. /// </summary> public void GetUpdatedMethodTokens(ArrayBuilder<MethodDefinitionHandle> methods) { foreach (var def in _methodDefs.GetRows()) { // The debugger tries to remap all modified methods, which requires presence of sequence points. if (!_methodDefs.IsAddedNotChanged(def) && def.GetBody(Context)?.SequencePoints.Length > 0) { methods.Add(MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(def))); } } } /// <summary> /// Return tokens for all updated or added types. /// </summary> public void GetChangedTypeTokens(ArrayBuilder<TypeDefinitionHandle> types) { foreach (var def in _changedTypeDefs) { types.Add(GetTypeDefinitionHandle(def)); } } protected override ushort Generation { get { return (ushort)(_previousGeneration.Ordinal + 1); } } protected override Guid EncId { get { return _encId; } } protected override Guid EncBaseId { get { return _previousGeneration.EncId; } } protected override EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def) { return MetadataTokens.EventDefinitionHandle(_eventDefs.GetRowId(def)); } protected override IReadOnlyList<IEventDefinition> GetEventDefs() { return _eventDefs.GetRows(); } protected override FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def) { return MetadataTokens.FieldDefinitionHandle(_fieldDefs.GetRowId(def)); } protected override IReadOnlyList<IFieldDefinition> GetFieldDefs() { return _fieldDefs.GetRows(); } protected override bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle) { bool result = _typeDefs.TryGetRowId(def, out int rowId); handle = MetadataTokens.TypeDefinitionHandle(rowId); return result; } protected override TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def) { return MetadataTokens.TypeDefinitionHandle(_typeDefs.GetRowId(def)); } protected override ITypeDefinition GetTypeDef(TypeDefinitionHandle handle) { return _typeDefs.GetDefinition(MetadataTokens.GetRowNumber(handle)); } protected override IReadOnlyList<ITypeDefinition> GetTypeDefs() { return _typeDefs.GetRows(); } protected override bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle) { bool result = _methodDefs.TryGetRowId(def, out int rowId); handle = MetadataTokens.MethodDefinitionHandle(rowId); return result; } protected override MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def) => MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(def)); protected override IMethodDefinition GetMethodDef(MethodDefinitionHandle index) => _methodDefs.GetDefinition(MetadataTokens.GetRowNumber(index)); protected override IReadOnlyList<IMethodDefinition> GetMethodDefs() => _methodDefs.GetRows(); protected override PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def) => MetadataTokens.PropertyDefinitionHandle(_propertyDefs.GetRowId(def)); protected override IReadOnlyList<IPropertyDefinition> GetPropertyDefs() => _propertyDefs.GetRows(); protected override ParameterHandle GetParameterHandle(IParameterDefinition def) => MetadataTokens.ParameterHandle(_parameterDefs.GetRowId(def)); protected override IReadOnlyList<IParameterDefinition> GetParameterDefs() => _parameterDefs.GetRows(); protected override IReadOnlyList<IGenericParameter> GetGenericParameters() => _genericParameters.GetRows(); // Fields are associated with the type through the EncLog table. protected override FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef) => default; // Methods are associated with the type through the EncLog table. protected override MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef) => default; // Parameters are associated with the method through the EncLog table. protected override ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef) => default; protected override AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference) { var identity = reference.Identity; var versionPattern = reference.AssemblyVersionPattern; if (versionPattern is not null) { RoslynDebug.AssertNotNull(_previousGeneration.InitialBaseline.LazyMetadataSymbols); identity = _previousGeneration.InitialBaseline.LazyMetadataSymbols.AssemblyReferenceIdentityMap[identity.WithVersion(versionPattern)]; } return MetadataTokens.AssemblyReferenceHandle(_assemblyRefIndex.GetOrAdd(identity)); } protected override IReadOnlyList<AssemblyIdentity> GetAssemblyRefs() { return _assemblyRefIndex.Rows; } protected override ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference) { return MetadataTokens.ModuleReferenceHandle(_moduleRefIndex.GetOrAdd(reference)); } protected override IReadOnlyList<string> GetModuleRefs() { return _moduleRefIndex.Rows; } protected override MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference) { return MetadataTokens.MemberReferenceHandle(_memberRefIndex.GetOrAdd(reference)); } protected override IReadOnlyList<ITypeMemberReference> GetMemberRefs() { return _memberRefIndex.Rows; } protected override MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference) { return MetadataTokens.MethodSpecificationHandle(_methodSpecIndex.GetOrAdd(reference)); } protected override IReadOnlyList<IGenericMethodInstanceReference> GetMethodSpecs() { return _methodSpecIndex.Rows; } protected override int GreatestMethodDefIndex => _methodDefs.NextRowId; protected override bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle) { int index; bool result = _typeRefIndex.TryGetValue(reference, out index); handle = MetadataTokens.TypeReferenceHandle(index); return result; } protected override TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference) { return MetadataTokens.TypeReferenceHandle(_typeRefIndex.GetOrAdd(reference)); } protected override IReadOnlyList<ITypeReference> GetTypeRefs() { return _typeRefIndex.Rows; } protected override TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference) { return MetadataTokens.TypeSpecificationHandle(_typeSpecIndex.GetOrAdd(reference)); } protected override IReadOnlyList<ITypeReference> GetTypeSpecs() { return _typeSpecIndex.Rows; } protected override StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle blobIndex) { return MetadataTokens.StandaloneSignatureHandle(_standAloneSignatureIndex.GetOrAdd(blobIndex)); } protected override IReadOnlyList<BlobHandle> GetStandaloneSignatureBlobHandles() { return _standAloneSignatureIndex.Rows; } protected override void OnIndicesCreated() { var module = (IPEDeltaAssemblyBuilder)this.module; module.OnCreatedIndices(this.Context.Diagnostics); } protected override void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef) { var change = _changes.GetChange(typeDef); switch (change) { case SymbolChange.Added: _typeDefs.Add(typeDef); _changedTypeDefs.Add(typeDef); var typeParameters = this.GetConsolidatedTypeParameters(typeDef); if (typeParameters != null) { foreach (var typeParameter in typeParameters) { _genericParameters.Add(typeParameter); } } break; case SymbolChange.Updated: _typeDefs.AddUpdated(typeDef); _changedTypeDefs.Add(typeDef); break; case SymbolChange.ContainsChanges: // Members changed. // We keep this list separately because we don't want to output duplicate typedef entries in the EnC log, // which uses _typeDefs, but it's simpler to let the members output those rows for the updated typedefs // with the right update type. _changedTypeDefs.Add(typeDef); break; case SymbolChange.None: // No changes to type. return; default: throw ExceptionUtilities.UnexpectedValue(change); } int typeRowId = _typeDefs.GetRowId(typeDef); foreach (var eventDef in typeDef.GetEvents(this.Context)) { if (!_eventMap.Contains(typeRowId)) { _eventMap.Add(typeRowId); } this.AddDefIfNecessary(_eventDefs, eventDef); } foreach (var fieldDef in typeDef.GetFields(this.Context)) { this.AddDefIfNecessary(_fieldDefs, fieldDef); } foreach (var methodDef in typeDef.GetMethods(this.Context)) { this.AddDefIfNecessary(_methodDefs, methodDef); var methodChange = _changes.GetChange(methodDef); if (methodChange == SymbolChange.Added) { _firstParamRowMap.Add(GetMethodDefinitionHandle(methodDef), _parameterDefs.NextRowId); foreach (var paramDef in this.GetParametersToEmit(methodDef)) { _parameterDefs.Add(paramDef); _parameterDefList.Add(paramDef, methodDef); } } else if (methodChange == SymbolChange.Updated) { // If we're re-emitting parameters for an existing method we need to find their original row numbers // and reuse them so the EnCLog, EnCMap and CustomAttributes tables refer to the right rows // Unfortunately we have to check the original metadata and deltas separately as nothing tracks the aggregate data // in a way that we can use var handle = GetMethodDefinitionHandle(methodDef); if (_previousGeneration.OriginalMetadata.MetadataReader.GetTableRowCount(TableIndex.MethodDef) >= MetadataTokens.GetRowNumber(handle)) { EmitParametersFromOriginalMetadata(methodDef, handle); } else { EmitParametersFromDelta(methodDef, handle); } } if (methodChange == SymbolChange.Added) { if (methodDef.GenericParameterCount > 0) { foreach (var typeParameter in methodDef.GenericParameters) { _genericParameters.Add(typeParameter); } } } } foreach (var propertyDef in typeDef.GetProperties(this.Context)) { if (!_propertyMap.Contains(typeRowId)) { _propertyMap.Add(typeRowId); } this.AddDefIfNecessary(_propertyDefs, propertyDef); } var implementingMethods = ArrayBuilder<int>.GetInstance(); // First, visit all MethodImplementations and add to this.methodImplList. foreach (var methodImpl in typeDef.GetExplicitImplementationOverrides(Context)) { var methodDef = (IMethodDefinition?)methodImpl.ImplementingMethod.AsDefinition(this.Context); RoslynDebug.AssertNotNull(methodDef); int methodDefRowId = _methodDefs.GetRowId(methodDef); // If there are N existing MethodImpl entries for this MethodDef, // those will be index:1, ..., index:N, so it's sufficient to check for index:1. var key = new MethodImplKey(methodDefRowId, index: 1); if (!_methodImpls.Contains(key)) { implementingMethods.Add(methodDefRowId); this.methodImplList.Add(methodImpl); } } // Next, add placeholders to this.methodImpls for items added above. foreach (var methodDefIndex in implementingMethods) { int index = 1; while (true) { var key = new MethodImplKey(methodDefIndex, index); if (!_methodImpls.Contains(key)) { _methodImpls.Add(key); break; } index++; } } implementingMethods.Free(); } private void EmitParametersFromOriginalMetadata(IMethodDefinition methodDef, MethodDefinitionHandle handle) { var def = _previousGeneration.OriginalMetadata.MetadataReader.GetMethodDefinition(handle); var parameters = def.GetParameters(); var paramDefinitions = this.GetParametersToEmit(methodDef); int i = 0; foreach (var param in parameters) { var paramDef = paramDefinitions[i]; _parameterDefs.AddUpdated(paramDef); _existingParameterDefs.Add(paramDef, MetadataTokens.GetRowNumber(param)); _parameterDefList.Add(paramDef, methodDef); i++; } } private void EmitParametersFromDelta(IMethodDefinition methodDef, MethodDefinitionHandle handle) { var ok = _previousGeneration.FirstParamRowMap.TryGetValue(handle, out var firstRowId); Debug.Assert(ok); foreach (var paramDef in GetParametersToEmit(methodDef)) { _parameterDefs.AddUpdated(paramDef); _existingParameterDefs.Add(paramDef, firstRowId++); _parameterDefList.Add(paramDef, methodDef); } } private bool AddDefIfNecessary<T>(DefinitionIndex<T> defIndex, T def) where T : class, IDefinition { switch (_changes.GetChange(def)) { case SymbolChange.Added: defIndex.Add(def); return true; case SymbolChange.Updated: defIndex.AddUpdated(def); return false; case SymbolChange.ContainsChanges: Debug.Assert(def is INestedTypeDefinition); // Changes to members within nested type only. return false; default: // No changes to member or container. return false; } } protected override ReferenceIndexer CreateReferenceVisitor() { return new DeltaReferenceIndexer(this); } protected override void ReportReferencesToAddedSymbols() { foreach (var typeRef in GetTypeRefs()) { ReportReferencesToAddedSymbol(typeRef.GetInternalSymbol()); } foreach (var memberRef in GetMemberRefs()) { ReportReferencesToAddedSymbol(memberRef.GetInternalSymbol()); } } private void ReportReferencesToAddedSymbol(ISymbolInternal? symbol) { if (symbol != null && _changes.IsAdded(symbol.GetISymbol())) { Context.Diagnostics.Add(messageProvider.CreateDiagnostic( messageProvider.ERR_EncReferenceToAddedMember, GetSymbolLocation(symbol), symbol.Name, symbol.ContainingAssembly.Name)); } } protected override StandaloneSignatureHandle SerializeLocalVariablesSignature(IMethodBody body) { StandaloneSignatureHandle localSignatureHandle; var localVariables = body.LocalVariables; var encInfos = ArrayBuilder<EncLocalInfo>.GetInstance(); if (localVariables.Length > 0) { var writer = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(writer).LocalVariableSignature(localVariables.Length); foreach (ILocalDefinition local in localVariables) { var signature = local.Signature; if (signature == null) { int start = writer.Count; SerializeLocalVariableType(encoder.AddVariable(), local); signature = writer.ToArray(start, writer.Count - start); } else { writer.WriteBytes(signature); } encInfos.Add(CreateEncLocalInfo(local, signature)); } BlobHandle blobIndex = metadata.GetOrAddBlob(writer); localSignatureHandle = GetOrAddStandaloneSignatureHandle(blobIndex); writer.Free(); } else { localSignatureHandle = default; } var info = new AddedOrChangedMethodInfo( body.MethodId, encInfos.ToImmutable(), body.LambdaDebugInfo, body.ClosureDebugInfo, body.StateMachineTypeName, body.StateMachineHoistedLocalSlots, body.StateMachineAwaiterSlots); _addedOrChangedMethods.Add(body.MethodDefinition, info); encInfos.Free(); return localSignatureHandle; } private EncLocalInfo CreateEncLocalInfo(ILocalDefinition localDef, byte[] signature) { if (localDef.SlotInfo.Id.IsNone) { return new EncLocalInfo(signature); } // local type is already translated, but not recursively ITypeReference translatedType = localDef.Type; if (translatedType.GetInternalSymbol() is ITypeSymbolInternal typeSymbol) { translatedType = Context.Module.EncTranslateType(typeSymbol, Context.Diagnostics); } return new EncLocalInfo(localDef.SlotInfo, translatedType, localDef.Constraints, signature); } protected override int AddCustomAttributesToTable(EntityHandle parentHandle, IEnumerable<ICustomAttribute> attributes) { // The base class will write out the actual metadata for us var numAttributesEmitted = base.AddCustomAttributesToTable(parentHandle, attributes); // We need to keep track of all of the things attributes could be associated with in this delta, in order to populate the EncLog and Map tables _customAttributeParentCounts.Add(parentHandle, numAttributesEmitted); return numAttributesEmitted; } public override void PopulateEncTables(ImmutableArray<int> typeSystemRowCounts) { Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncLog] == 0); Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncMap] == 0); PopulateEncLogTableRows(typeSystemRowCounts, out var customAttributeEncMapRows, out var paramEncMapRows); PopulateEncMapTableRows(typeSystemRowCounts, customAttributeEncMapRows, paramEncMapRows); } private void PopulateEncLogTableRows(ImmutableArray<int> rowCounts, out List<int> customAttributeEncMapRows, out List<int> paramEncMapRows) { // The EncLog table is a log of all the operations needed // to update the previous metadata. That means all // new references must be added to the EncLog. var previousSizes = _previousGeneration.TableSizes; var deltaSizes = this.GetDeltaTableSizes(rowCounts); PopulateEncLogTableRows(TableIndex.AssemblyRef, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.ModuleRef, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.MemberRef, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.MethodSpec, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.TypeRef, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.TypeSpec, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.StandAloneSig, previousSizes, deltaSizes); PopulateEncLogTableRows(_typeDefs, TableIndex.TypeDef); PopulateEncLogTableRows(TableIndex.EventMap, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.PropertyMap, previousSizes, deltaSizes); PopulateEncLogTableEventsOrProperties(_eventDefs, TableIndex.Event, EditAndContinueOperation.AddEvent, _eventMap, TableIndex.EventMap); PopulateEncLogTableFieldsOrMethods(_fieldDefs, TableIndex.Field, EditAndContinueOperation.AddField); PopulateEncLogTableFieldsOrMethods(_methodDefs, TableIndex.MethodDef, EditAndContinueOperation.AddMethod); PopulateEncLogTableEventsOrProperties(_propertyDefs, TableIndex.Property, EditAndContinueOperation.AddProperty, _propertyMap, TableIndex.PropertyMap); PopulateEncLogTableParameters(out paramEncMapRows); PopulateEncLogTableRows(TableIndex.Constant, previousSizes, deltaSizes); PopulateEncLogTableCustomAttributes(out customAttributeEncMapRows); PopulateEncLogTableRows(TableIndex.DeclSecurity, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.ClassLayout, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.FieldLayout, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.MethodSemantics, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.MethodImpl, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.ImplMap, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.FieldRva, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.NestedClass, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.GenericParam, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.InterfaceImpl, previousSizes, deltaSizes); PopulateEncLogTableRows(TableIndex.GenericParamConstraint, previousSizes, deltaSizes); } private void PopulateEncLogTableEventsOrProperties<T>( DefinitionIndex<T> index, TableIndex table, EditAndContinueOperation addCode, EventOrPropertyMapIndex map, TableIndex mapTable) where T : class, ITypeDefinitionMember { foreach (var member in index.GetRows()) { if (index.IsAddedNotChanged(member)) { int typeRowId = MetadataTokens.GetRowNumber(GetTypeDefinitionHandle(member.ContainingTypeDefinition)); int mapRowId = map.GetRowId(typeRowId); metadata.AddEncLogEntry( entity: MetadataTokens.Handle(mapTable, mapRowId), code: addCode); } metadata.AddEncLogEntry( entity: MetadataTokens.Handle(table, index.GetRowId(member)), code: EditAndContinueOperation.Default); } } private void PopulateEncLogTableFieldsOrMethods<T>( DefinitionIndex<T> index, TableIndex tableIndex, EditAndContinueOperation addCode) where T : class, ITypeDefinitionMember { foreach (var member in index.GetRows()) { if (index.IsAddedNotChanged(member)) { metadata.AddEncLogEntry( entity: GetTypeDefinitionHandle(member.ContainingTypeDefinition), code: addCode); } metadata.AddEncLogEntry( entity: MetadataTokens.Handle(tableIndex, index.GetRowId(member)), code: EditAndContinueOperation.Default); } } private void PopulateEncLogTableParameters(out List<int> paramEncMapRows) { paramEncMapRows = new List<int>(); var parameterFirstId = _parameterDefs.FirstRowId; int i = 0; foreach (var paramDef in GetParameterDefs()) { var methodDef = _parameterDefList[paramDef]; if (_methodDefs.IsAddedNotChanged(methodDef)) { // For parameters on new methods we emit AddParameter rows for the method too paramEncMapRows.Add(parameterFirstId + i); metadata.AddEncLogEntry( entity: MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(methodDef)), code: EditAndContinueOperation.AddParameter); metadata.AddEncLogEntry( entity: MetadataTokens.ParameterHandle(parameterFirstId + i), code: EditAndContinueOperation.Default); i++; } else { // For previously emitted parameters we just update the Param row var param = GetParameterHandle(paramDef); paramEncMapRows.Add(MetadataTokens.GetRowNumber(param)); metadata.AddEncLogEntry( entity: param, code: EditAndContinueOperation.Default); } } } /// <summary> /// CustomAttributes point to their target via the Parent column so we cannot simply output new rows /// in the delta or we would end up with duplicates, but we also don't want to do complex logic to determine /// which attributes have changes, so we just emit them all. /// This means our logic for emitting CustomAttributes is to update any existing rows, either from the original /// compilation or subsequent deltas, and only add more if we need to. The EncLog table is the thing that tells /// the runtime which row a CustomAttributes row is (ie, new or existing) /// </summary> private void PopulateEncLogTableCustomAttributes(out List<int> customAttributeEncMapRows) { customAttributeEncMapRows = new List<int>(); // List of attributes that need to be emitted to delete a previously emitted attribute var deletedAttributeRows = new List<(int parentRowId, HandleKind kind)>(); var customAttributesAdded = new Dictionary<EntityHandle, ArrayBuilder<int>>(); // The data in _previousGeneration.CustomAttributesAdded is not nicely sorted, or even necessarily contiguous // so we need to map each target onto the rows its attributes occupy so we know which rows to update var lastRowId = _previousGeneration.OriginalMetadata.MetadataReader.GetTableRowCount(TableIndex.CustomAttribute); if (_previousGeneration.CustomAttributesAdded.Count > 0) { lastRowId = _previousGeneration.CustomAttributesAdded.SelectMany(s => s.Value).Max(); } // Iterate through the parents we emitted custom attributes for, in parent order foreach (var (parent, count) in _customAttributeParentCounts.OrderBy(kvp => CodedIndex.HasCustomAttribute(kvp.Key))) { int index = 0; // First we try to update any existing attributes. // GetCustomAttributes does a binary search, so is fast. We presume that the number of rows in the original metadata // greatly outnumbers the amount of parents emitted in this delta so even with repeated searches this is still // quicker than iterating the entire original table, even once. var existingCustomAttributes = _previousGeneration.OriginalMetadata.MetadataReader.GetCustomAttributes(parent); foreach (var attributeHandle in existingCustomAttributes) { int rowId = MetadataTokens.GetRowNumber(attributeHandle); AddLogEntryOrDelete(rowId, parent, add: index < count, customAttributeEncMapRows); index++; } // If we emitted any attributes for this parent in previous deltas then we either need to update // them next, or delete them if necessary if (_previousGeneration.CustomAttributesAdded.TryGetValue(parent, out var rowIds)) { foreach (var rowId in rowIds) { TrackCustomAttributeAdded(rowId, parent); AddLogEntryOrDelete(rowId, parent, add: index < count, customAttributeEncMapRows); index++; } } // Finally if there are still attributes for this parent left, they are additions new to this delta for (int i = index; i < count; i++) { lastRowId++; TrackCustomAttributeAdded(lastRowId, parent); AddEncLogEntry(lastRowId, customAttributeEncMapRows); } } // Save the attributes we've emitted, and the ones from previous deltas, for use in the next generation foreach (var (parent, rowIds) in customAttributesAdded) { _customAttributesAdded.Add(parent, rowIds.ToImmutableAndFree()); } // Add attributes and log entries for everything we've deleted foreach (var row in deletedAttributeRows) { // now emit a "delete" row with a parent that is for the 0 row of the same table as the existing one if (!MetadataTokens.TryGetTableIndex(row.kind, out var tableIndex)) { throw new InvalidOperationException("Trying to delete a custom attribute for a parent kind that doesn't have a matching table index."); } metadata.AddCustomAttribute(MetadataTokens.Handle(tableIndex, 0), MetadataTokens.EntityHandle(TableIndex.MemberRef, 0), value: default); AddEncLogEntry(row.parentRowId, customAttributeEncMapRows); } void AddEncLogEntry(int rowId, List<int> customAttributeEncMapRows) { customAttributeEncMapRows.Add(rowId); metadata.AddEncLogEntry( entity: MetadataTokens.CustomAttributeHandle(rowId), code: EditAndContinueOperation.Default); } void AddLogEntryOrDelete(int rowId, EntityHandle parent, bool add, List<int> customAttributeEncMapRows) { if (add) { // Update this row AddEncLogEntry(rowId, customAttributeEncMapRows); } else { // Delete this row deletedAttributeRows.Add((rowId, parent.Kind)); } } void TrackCustomAttributeAdded(int nextRowId, EntityHandle parent) { if (!customAttributesAdded.TryGetValue(parent, out var existing)) { existing = ArrayBuilder<int>.GetInstance(); customAttributesAdded.Add(parent, existing); } existing.Add(nextRowId); } } private void PopulateEncLogTableRows<T>(DefinitionIndex<T> index, TableIndex tableIndex) where T : class, IDefinition { foreach (var member in index.GetRows()) { metadata.AddEncLogEntry( entity: MetadataTokens.Handle(tableIndex, index.GetRowId(member)), code: EditAndContinueOperation.Default); } } private void PopulateEncLogTableRows(TableIndex tableIndex, ImmutableArray<int> previousSizes, ImmutableArray<int> deltaSizes) { PopulateEncLogTableRows(tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]); } private void PopulateEncLogTableRows(TableIndex tableIndex, int firstRowId, int tokenCount) { for (int i = 0; i < tokenCount; i++) { metadata.AddEncLogEntry( entity: MetadataTokens.Handle(tableIndex, firstRowId + i), code: EditAndContinueOperation.Default); } } private void PopulateEncMapTableRows(ImmutableArray<int> rowCounts, List<int> customAttributeEncMapRows, List<int> paramEncMapRows) { // The EncMap table maps from offset in each table in the delta // metadata to token. As such, the EncMap is a concatenated // list of all tokens in all tables from the delta sorted by table // and, within each table, sorted by row. var tokens = ArrayBuilder<EntityHandle>.GetInstance(); var previousSizes = _previousGeneration.TableSizes; var deltaSizes = this.GetDeltaTableSizes(rowCounts); AddReferencedTokens(tokens, TableIndex.AssemblyRef, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.ModuleRef, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.MemberRef, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.MethodSpec, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.TypeRef, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.TypeSpec, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.StandAloneSig, previousSizes, deltaSizes); AddDefinitionTokens(tokens, _typeDefs, TableIndex.TypeDef); AddDefinitionTokens(tokens, _eventDefs, TableIndex.Event); AddDefinitionTokens(tokens, _fieldDefs, TableIndex.Field); AddDefinitionTokens(tokens, _methodDefs, TableIndex.MethodDef); AddDefinitionTokens(tokens, _propertyDefs, TableIndex.Property); AddRowNumberTokens(tokens, paramEncMapRows, TableIndex.Param); AddReferencedTokens(tokens, TableIndex.Constant, previousSizes, deltaSizes); AddRowNumberTokens(tokens, customAttributeEncMapRows, TableIndex.CustomAttribute); AddReferencedTokens(tokens, TableIndex.DeclSecurity, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.ClassLayout, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.FieldLayout, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.EventMap, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.PropertyMap, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.MethodSemantics, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.MethodImpl, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.ImplMap, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.FieldRva, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.NestedClass, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.GenericParam, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.InterfaceImpl, previousSizes, deltaSizes); AddReferencedTokens(tokens, TableIndex.GenericParamConstraint, previousSizes, deltaSizes); tokens.Sort(HandleComparer.Default); // Should not be any duplicates. Debug.Assert(tokens.Distinct().Count() == tokens.Count); foreach (var token in tokens) { metadata.AddEncMapEntry(token); } tokens.Free(); // Populate Portable PDB EncMap table with MethodDebugInformation mapping, // which corresponds 1:1 to MethodDef mapping. if (_debugMetadataOpt != null) { var debugTokens = ArrayBuilder<EntityHandle>.GetInstance(); AddDefinitionTokens(debugTokens, _methodDefs, TableIndex.MethodDebugInformation); debugTokens.Sort(HandleComparer.Default); // Should not be any duplicates. Debug.Assert(debugTokens.Distinct().Count() == debugTokens.Count); foreach (var token in debugTokens) { _debugMetadataOpt.AddEncMapEntry(token); } debugTokens.Free(); } #if DEBUG // The following tables are either represented in the EncMap // or specifically ignored. The rest should be empty. var handledTables = new TableIndex[] { TableIndex.Module, TableIndex.TypeRef, TableIndex.TypeDef, TableIndex.Field, TableIndex.MethodDef, TableIndex.Param, TableIndex.MemberRef, TableIndex.Constant, TableIndex.CustomAttribute, TableIndex.DeclSecurity, TableIndex.ClassLayout, TableIndex.FieldLayout, TableIndex.StandAloneSig, TableIndex.EventMap, TableIndex.Event, TableIndex.PropertyMap, TableIndex.Property, TableIndex.MethodSemantics, TableIndex.MethodImpl, TableIndex.ModuleRef, TableIndex.TypeSpec, TableIndex.ImplMap, // FieldRva is not needed since we only emit fields with explicit mapping // for <PrivateImplementationDetails> and that class is not used in ENC. // If we need FieldRva in the future, we'll need a corresponding test. // (See EditAndContinueTests.FieldRva that was deleted in this change.) //TableIndex.FieldRva, TableIndex.EncLog, TableIndex.EncMap, TableIndex.Assembly, TableIndex.AssemblyRef, TableIndex.MethodSpec, TableIndex.NestedClass, TableIndex.GenericParam, TableIndex.InterfaceImpl, TableIndex.GenericParamConstraint, }; for (int i = 0; i < rowCounts.Length; i++) { if (handledTables.Contains((TableIndex)i)) { continue; } Debug.Assert(rowCounts[i] == 0); } #endif } private static void AddReferencedTokens( ArrayBuilder<EntityHandle> builder, TableIndex tableIndex, ImmutableArray<int> previousSizes, ImmutableArray<int> deltaSizes) { AddReferencedTokens(builder, tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]); } private static void AddReferencedTokens(ArrayBuilder<EntityHandle> builder, TableIndex tableIndex, int firstRowId, int nTokens) { for (int i = 0; i < nTokens; i++) { builder.Add(MetadataTokens.Handle(tableIndex, firstRowId + i)); } } private static void AddDefinitionTokens<T>(ArrayBuilder<EntityHandle> tokens, DefinitionIndex<T> index, TableIndex tableIndex) where T : class, IDefinition { foreach (var member in index.GetRows()) { tokens.Add(MetadataTokens.Handle(tableIndex, index.GetRowId(member))); } } private static void AddRowNumberTokens(ArrayBuilder<EntityHandle> tokens, IEnumerable<int> rowNumbers, TableIndex tableIndex) { foreach (var row in rowNumbers) { tokens.Add(MetadataTokens.Handle(tableIndex, row)); } } protected override void PopulateEventMapTableRows() { foreach (var typeId in _eventMap.GetRows()) { metadata.AddEventMap( declaringType: MetadataTokens.TypeDefinitionHandle(typeId), eventList: MetadataTokens.EventDefinitionHandle(_eventMap.GetRowId(typeId))); } } protected override void PopulatePropertyMapTableRows() { foreach (var typeId in _propertyMap.GetRows()) { metadata.AddPropertyMap( declaringType: MetadataTokens.TypeDefinitionHandle(typeId), propertyList: MetadataTokens.PropertyDefinitionHandle(_propertyMap.GetRowId(typeId))); } } private abstract class DefinitionIndexBase<T> where T : notnull { protected readonly Dictionary<T, int> added; // Definitions added in this generation. protected readonly List<T> rows; // Rows in this generation, containing adds and updates. private readonly int _firstRowId; // First row in this generation. private bool _frozen; public DefinitionIndexBase(int lastRowId, IEqualityComparer<T>? comparer = null) { this.added = new Dictionary<T, int>(comparer); this.rows = new List<T>(); _firstRowId = lastRowId + 1; } public abstract bool TryGetRowId(T item, out int rowId); public int GetRowId(T item) { bool containsItem = TryGetRowId(item, out int rowId); // Fails if we are attempting to make a change that should have been reported as rude, // e.g. the corresponding definitions type don't match, etc. Debug.Assert(containsItem); Debug.Assert(rowId > 0); return rowId; } public bool Contains(T item) => TryGetRowId(item, out _); // A method rather than a property since it freezes the table. public IReadOnlyDictionary<T, int> GetAdded() { this.Freeze(); return this.added; } // A method rather than a property since it freezes the table. public IReadOnlyList<T> GetRows() { this.Freeze(); return this.rows; } public int FirstRowId { get { return _firstRowId; } } public int NextRowId { get { return this.added.Count + _firstRowId; } } public bool IsFrozen { get { return _frozen; } } protected virtual void OnFrozen() { #if DEBUG // Verify the rows are sorted. int prev = 0; foreach (var row in this.rows) { int next = this.added[row]; Debug.Assert(prev < next); prev = next; } #endif } private void Freeze() { if (!_frozen) { _frozen = true; this.OnFrozen(); } } } private sealed class DefinitionIndex<T> : DefinitionIndexBase<T> where T : class, IDefinition { public delegate bool TryGetExistingIndex(T item, out int index); private readonly TryGetExistingIndex _tryGetExistingIndex; // Map of row id to def for all defs. This could be an array indexed // by row id but the array could be large and sparsely populated // if there are many defs in the previous generation but few // references to those defs in the current generation. private readonly Dictionary<int, T> _map; public DefinitionIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId) : base(lastRowId, ReferenceEqualityComparer.Instance) { _tryGetExistingIndex = tryGetExistingIndex; _map = new Dictionary<int, T>(); } public override bool TryGetRowId(T item, out int index) { if (this.added.TryGetValue(item, out index)) { return true; } if (_tryGetExistingIndex(item, out index)) { #if DEBUG Debug.Assert(!_map.TryGetValue(index, out var other) || ((object)other == (object)item)); #endif _map[index] = item; return true; } return false; } public T GetDefinition(int rowId) => _map[rowId]; public void Add(T item) { Debug.Assert(!this.IsFrozen); int index = this.NextRowId; this.added.Add(item, index); _map[index] = item; this.rows.Add(item); } /// <summary> /// Add an item from a previous generation /// that has been updated in this generation. /// </summary> public void AddUpdated(T item) { Debug.Assert(!this.IsFrozen); this.rows.Add(item); } public bool IsAddedNotChanged(T item) => added.ContainsKey(item); protected override void OnFrozen() => rows.Sort((x, y) => GetRowId(x).CompareTo(GetRowId(y))); } private bool TryGetExistingTypeDefIndex(ITypeDefinition item, out int index) { if (_previousGeneration.TypesAdded.TryGetValue(item, out index)) { return true; } TypeDefinitionHandle handle; if (_definitionMap.TryGetTypeHandle(item, out handle)) { index = MetadataTokens.GetRowNumber(handle); Debug.Assert(index > 0); return true; } index = 0; return false; } private bool TryGetExistingEventDefIndex(IEventDefinition item, out int index) { if (_previousGeneration.EventsAdded.TryGetValue(item, out index)) { return true; } EventDefinitionHandle handle; if (_definitionMap.TryGetEventHandle(item, out handle)) { index = MetadataTokens.GetRowNumber(handle); Debug.Assert(index > 0); return true; } index = 0; return false; } private bool TryGetExistingFieldDefIndex(IFieldDefinition item, out int index) { if (_previousGeneration.FieldsAdded.TryGetValue(item, out index)) { return true; } FieldDefinitionHandle handle; if (_definitionMap.TryGetFieldHandle(item, out handle)) { index = MetadataTokens.GetRowNumber(handle); Debug.Assert(index > 0); return true; } index = 0; return false; } private bool TryGetExistingMethodDefIndex(IMethodDefinition item, out int index) { if (_previousGeneration.MethodsAdded.TryGetValue(item, out index)) { return true; } MethodDefinitionHandle handle; if (_definitionMap.TryGetMethodHandle(item, out handle)) { index = MetadataTokens.GetRowNumber(handle); Debug.Assert(index > 0); return true; } index = 0; return false; } private bool TryGetExistingPropertyDefIndex(IPropertyDefinition item, out int index) { if (_previousGeneration.PropertiesAdded.TryGetValue(item, out index)) { return true; } PropertyDefinitionHandle handle; if (_definitionMap.TryGetPropertyHandle(item, out handle)) { index = MetadataTokens.GetRowNumber(handle); Debug.Assert(index > 0); return true; } index = 0; return false; } private bool TryGetExistingParameterDefIndex(IParameterDefinition item, out int index) { return _existingParameterDefs.TryGetValue(item, out index); } private bool TryGetExistingEventMapIndex(int item, out int index) { if (_previousGeneration.EventMapAdded.TryGetValue(item, out index)) { return true; } if (_previousGeneration.TypeToEventMap.TryGetValue(item, out index)) { return true; } index = 0; return false; } private bool TryGetExistingPropertyMapIndex(int item, out int index) { if (_previousGeneration.PropertyMapAdded.TryGetValue(item, out index)) { return true; } if (_previousGeneration.TypeToPropertyMap.TryGetValue(item, out index)) { return true; } index = 0; return false; } private bool TryGetExistingMethodImplIndex(MethodImplKey item, out int index) { if (_previousGeneration.MethodImplsAdded.TryGetValue(item, out index)) { return true; } if (_previousGeneration.MethodImpls.TryGetValue(item, out index)) { return true; } index = 0; return false; } private sealed class GenericParameterIndex : DefinitionIndexBase<IGenericParameter> { public GenericParameterIndex(int lastRowId) : base(lastRowId, ReferenceEqualityComparer.Instance) { } public override bool TryGetRowId(IGenericParameter item, out int index) { return this.added.TryGetValue(item, out index); } public void Add(IGenericParameter item) { Debug.Assert(!this.IsFrozen); int index = this.NextRowId; this.added.Add(item, index); this.rows.Add(item); } } private sealed class EventOrPropertyMapIndex : DefinitionIndexBase<int> { public delegate bool TryGetExistingIndex(int item, out int index); private readonly TryGetExistingIndex _tryGetExistingIndex; public EventOrPropertyMapIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId) : base(lastRowId) { _tryGetExistingIndex = tryGetExistingIndex; } public override bool TryGetRowId(int item, out int index) { if (this.added.TryGetValue(item, out index)) { return true; } if (_tryGetExistingIndex(item, out index)) { return true; } index = 0; return false; } public void Add(int item) { Debug.Assert(!this.IsFrozen); int index = this.NextRowId; this.added.Add(item, index); this.rows.Add(item); } } private sealed class MethodImplIndex : DefinitionIndexBase<MethodImplKey> { private readonly DeltaMetadataWriter _writer; public MethodImplIndex(DeltaMetadataWriter writer, int lastRowId) : base(lastRowId) { _writer = writer; } public override bool TryGetRowId(MethodImplKey item, out int index) { if (this.added.TryGetValue(item, out index)) { return true; } if (_writer.TryGetExistingMethodImplIndex(item, out index)) { return true; } index = 0; return false; } public void Add(MethodImplKey item) { Debug.Assert(!this.IsFrozen); int index = this.NextRowId; this.added.Add(item, index); this.rows.Add(item); } } private sealed class DeltaReferenceIndexer : ReferenceIndexer { private readonly SymbolChanges _changes; public DeltaReferenceIndexer(DeltaMetadataWriter writer) : base(writer) { _changes = writer._changes; } public override void Visit(CommonPEModuleBuilder module) { Visit(module.GetTopLevelTypeDefinitions(metadataWriter.Context)); } public override void Visit(IEventDefinition eventDefinition) { Debug.Assert(this.ShouldVisit(eventDefinition)); base.Visit(eventDefinition); } public override void Visit(IFieldDefinition fieldDefinition) { Debug.Assert(this.ShouldVisit(fieldDefinition)); base.Visit(fieldDefinition); } public override void Visit(ILocalDefinition localDefinition) { if (localDefinition.Signature == null) { base.Visit(localDefinition); } } public override void Visit(IMethodDefinition method) { Debug.Assert(this.ShouldVisit(method)); base.Visit(method); } public override void Visit(Cci.MethodImplementation methodImplementation) { // Unless the implementing method was added, // the method implementation already exists. var methodDef = (IMethodDefinition?)methodImplementation.ImplementingMethod.AsDefinition(this.Context); RoslynDebug.AssertNotNull(methodDef); if (_changes.GetChange(methodDef) == SymbolChange.Added) { base.Visit(methodImplementation); } } public override void Visit(INamespaceTypeDefinition namespaceTypeDefinition) { Debug.Assert(this.ShouldVisit(namespaceTypeDefinition)); base.Visit(namespaceTypeDefinition); } public override void Visit(INestedTypeDefinition nestedTypeDefinition) { Debug.Assert(this.ShouldVisit(nestedTypeDefinition)); base.Visit(nestedTypeDefinition); } public override void Visit(IPropertyDefinition propertyDefinition) { Debug.Assert(this.ShouldVisit(propertyDefinition)); base.Visit(propertyDefinition); } public override void Visit(ITypeDefinition typeDefinition) { if (this.ShouldVisit(typeDefinition)) { base.Visit(typeDefinition); } } public override void Visit(ITypeDefinitionMember typeMember) { if (this.ShouldVisit(typeMember)) { base.Visit(typeMember); } } private bool ShouldVisit(IDefinition def) { return _changes.GetChange(def) != SymbolChange.None; } } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Core/Portable/Emit/EditAndContinue/EmitBaseline.cs
// 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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { // A MethodImpl entry is a pair of implementing method and implemented // method. However, the implemented method is a MemberRef rather // than a MethodDef (e.g.: I<int>.M) and currently we are not mapping // MemberRefs between generations so it's not possible to track the // implemented method. Instead, recognizing that we do not support // changes to the set of implemented methods for a particular MethodDef, // and that we do not use the implementing methods anywhere, it's // sufficient to track a pair of implementing method and index. internal struct MethodImplKey : IEquatable<MethodImplKey> { internal MethodImplKey(int implementingMethod, int index) { Debug.Assert(implementingMethod > 0); Debug.Assert(index > 0); this.ImplementingMethod = implementingMethod; this.Index = index; } internal readonly int ImplementingMethod; internal readonly int Index; public override bool Equals(object? obj) { return obj is MethodImplKey && Equals((MethodImplKey)obj); } public bool Equals(MethodImplKey other) { return this.ImplementingMethod == other.ImplementingMethod && this.Index == other.Index; } public override int GetHashCode() { return Hash.Combine(this.ImplementingMethod, this.Index); } } /// <summary> /// Represents a module from a previous compilation. Used in Edit and Continue /// to emit the differences in a subsequent compilation. /// </summary> public sealed class EmitBaseline { private static readonly ImmutableArray<int> s_emptyTableSizes = ImmutableArray.Create(new int[MetadataTokens.TableCount]); internal sealed class MetadataSymbols { public readonly IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> AnonymousTypes; /// <summary> /// A map of the assembly identities of the baseline compilation to the identities of the original metadata AssemblyRefs. /// Only includes identities that differ between these two. /// </summary> public readonly ImmutableDictionary<AssemblyIdentity, AssemblyIdentity> AssemblyReferenceIdentityMap; public readonly object MetadataDecoder; public MetadataSymbols(IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypes, object metadataDecoder, ImmutableDictionary<AssemblyIdentity, AssemblyIdentity> assemblyReferenceIdentityMap) { Debug.Assert(anonymousTypes != null); Debug.Assert(metadataDecoder != null); Debug.Assert(assemblyReferenceIdentityMap != null); this.AnonymousTypes = anonymousTypes; this.MetadataDecoder = metadataDecoder; this.AssemblyReferenceIdentityMap = assemblyReferenceIdentityMap; } } /// <summary> /// Creates an <see cref="EmitBaseline"/> from the metadata of the module before editing /// and from a function that maps from a method to an array of local names. /// </summary> /// <param name="module">The metadata of the module before editing.</param> /// <param name="debugInformationProvider"> /// A function that for a method handle returns Edit and Continue debug information emitted by the compiler into the PDB. /// The function shall throw <see cref="InvalidDataException"/> if the debug information can't be read for the specified method. /// This exception and <see cref="IOException"/> are caught and converted to an emit diagnostic. Other exceptions are passed through. /// </param> /// <returns>An <see cref="EmitBaseline"/> for the module.</returns> /// <exception cref="ArgumentException"><paramref name="module"/> is not a PE image.</exception> /// <exception cref="ArgumentNullException"><paramref name="module"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="debugInformationProvider"/> is null.</exception> /// <exception cref="IOException">Error reading module metadata.</exception> /// <exception cref="BadImageFormatException">Module metadata is invalid.</exception> /// <exception cref="ObjectDisposedException">Module has been disposed.</exception> public static EmitBaseline CreateInitialBaseline(ModuleMetadata module, Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> debugInformationProvider) { if (module == null) { throw new ArgumentNullException(nameof(module)); } if (!module.Module.HasIL) { throw new ArgumentException(CodeAnalysisResources.PEImageNotAvailable, nameof(module)); } var hasPortablePdb = module.Module.PEReaderOpt.ReadDebugDirectory().Any(entry => entry.IsPortableCodeView); var localSigProvider = new Func<MethodDefinitionHandle, StandaloneSignatureHandle>(methodHandle => { try { return module.Module.GetMethodBodyOrThrow(methodHandle)?.LocalSignature ?? default; } catch (Exception e) when (e is BadImageFormatException || e is IOException) { throw new InvalidDataException(e.Message, e); } }); return CreateInitialBaseline(module, debugInformationProvider, localSigProvider, hasPortablePdb); } /// <summary> /// Creates an <see cref="EmitBaseline"/> from the metadata of the module before editing /// and from a function that maps from a method to an array of local names. /// </summary> /// <param name="module">The metadata of the module before editing.</param> /// <param name="debugInformationProvider"> /// A function that for a method handle returns Edit and Continue debug information emitted by the compiler into the PDB. /// The function shall throw <see cref="InvalidDataException"/> if the debug information can't be read for the specified method. /// This exception and <see cref="IOException"/> are caught and converted to an emit diagnostic. Other exceptions are passed through. /// </param> /// <param name="localSignatureProvider"> /// A function that for a method handle returns the signature of its local variables. /// The function shall throw <see cref="InvalidDataException"/> if the information can't be read for the specified method. /// This exception and <see cref="IOException"/> are caught and converted to an emit diagnostic. Other exceptions are passed through. /// </param> /// <param name="hasPortableDebugInformation"> /// True if the baseline PDB is portable. /// </param> /// <returns>An <see cref="EmitBaseline"/> for the module.</returns> /// <remarks> /// Only the initial baseline is created using this method; subsequent baselines are created /// automatically when emitting the differences in subsequent compilations. /// /// When an active method (one for which a frame is allocated on a stack) is updated the values of its local variables need to be preserved. /// The mapping of local variable names to their slots in the frame is not included in the metadata and thus needs to be provided by /// <paramref name="debugInformationProvider"/>. /// /// The <paramref name="debugInformationProvider"/> is only needed for the initial generation. The mapping for the subsequent generations /// is carried over through <see cref="EmitBaseline"/>. The compiler assigns slots to named local variables (including named temporary variables) /// it the order in which they appear in the source code. This property allows the compiler to reconstruct the local variable mapping /// for the initial generation. A subsequent generation may add a new variable in between two variables of the previous generation. /// Since the slots of the previous generation variables need to be preserved the only option is to add these new variables to the end. /// The slot ordering thus no longer matches the syntax ordering. It is therefore necessary to pass <see cref="EmitDifferenceResult.Baseline"/> /// to the next generation (rather than e.g. create new <see cref="EmitBaseline"/>s from scratch based on metadata produced by subsequent compilations). /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="module"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="debugInformationProvider"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="localSignatureProvider"/> is null.</exception> /// <exception cref="IOException">Error reading module metadata.</exception> /// <exception cref="BadImageFormatException">Module metadata is invalid.</exception> /// <exception cref="ObjectDisposedException">Module has been disposed.</exception> public static EmitBaseline CreateInitialBaseline( ModuleMetadata module, Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> debugInformationProvider, Func<MethodDefinitionHandle, StandaloneSignatureHandle> localSignatureProvider, bool hasPortableDebugInformation) { if (module == null) { throw new ArgumentNullException(nameof(module)); } if (debugInformationProvider == null) { throw new ArgumentNullException(nameof(debugInformationProvider)); } if (localSignatureProvider == null) { throw new ArgumentNullException(nameof(localSignatureProvider)); } var reader = module.MetadataReader; return new EmitBaseline( null, module, compilation: null, moduleBuilder: null, moduleVersionId: module.GetModuleVersionId(), ordinal: 0, encId: default, hasPortablePdb: hasPortableDebugInformation, generationOrdinals: new Dictionary<Cci.IDefinition, int>(), typesAdded: new Dictionary<Cci.ITypeDefinition, int>(), eventsAdded: new Dictionary<Cci.IEventDefinition, int>(), fieldsAdded: new Dictionary<Cci.IFieldDefinition, int>(), methodsAdded: new Dictionary<Cci.IMethodDefinition, int>(), firstParamRowMap: new Dictionary<MethodDefinitionHandle, int>(), propertiesAdded: new Dictionary<Cci.IPropertyDefinition, int>(), eventMapAdded: new Dictionary<int, int>(), propertyMapAdded: new Dictionary<int, int>(), methodImplsAdded: new Dictionary<MethodImplKey, int>(), customAttributesAdded: new Dictionary<EntityHandle, ImmutableArray<int>>(), tableEntriesAdded: s_emptyTableSizes, blobStreamLengthAdded: 0, stringStreamLengthAdded: 0, userStringStreamLengthAdded: 0, guidStreamLengthAdded: 0, anonymousTypeMap: null, // Unset for initial metadata synthesizedMembers: ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>.Empty, methodsAddedOrChanged: new Dictionary<int, AddedOrChangedMethodInfo>(), debugInformationProvider: debugInformationProvider, localSignatureProvider: localSignatureProvider, typeToEventMap: CalculateTypeEventMap(reader), typeToPropertyMap: CalculateTypePropertyMap(reader), methodImpls: CalculateMethodImpls(reader)); } internal EmitBaseline InitialBaseline { get; } /// <summary> /// The original metadata of the module. /// </summary> public ModuleMetadata OriginalMetadata { get; } // Symbols hydrated from the original metadata. Lazy since we don't know the language at the time the baseline is constructed. internal MetadataSymbols? LazyMetadataSymbols; internal readonly Compilation? Compilation; internal readonly CommonPEModuleBuilder? PEModuleBuilder; internal readonly Guid ModuleVersionId; internal readonly bool HasPortablePdb; /// <summary> /// Metadata generation ordinal. Zero for /// full metadata and non-zero for delta. /// </summary> internal readonly int Ordinal; /// <summary> /// Unique Guid for this delta, or default(Guid) /// if full metadata. /// </summary> internal readonly Guid EncId; /// <summary> /// The latest generation number of each symbol added via <see cref="SemanticEditKind.Replace"/> edit. /// </summary> internal readonly IReadOnlyDictionary<Cci.IDefinition, int> GenerationOrdinals; internal readonly IReadOnlyDictionary<Cci.ITypeDefinition, int> TypesAdded; internal readonly IReadOnlyDictionary<Cci.IEventDefinition, int> EventsAdded; internal readonly IReadOnlyDictionary<Cci.IFieldDefinition, int> FieldsAdded; internal readonly IReadOnlyDictionary<Cci.IMethodDefinition, int> MethodsAdded; internal readonly IReadOnlyDictionary<MethodDefinitionHandle, int> FirstParamRowMap; internal readonly IReadOnlyDictionary<Cci.IPropertyDefinition, int> PropertiesAdded; internal readonly IReadOnlyDictionary<int, int> EventMapAdded; internal readonly IReadOnlyDictionary<int, int> PropertyMapAdded; internal readonly IReadOnlyDictionary<MethodImplKey, int> MethodImplsAdded; internal readonly IReadOnlyDictionary<EntityHandle, ImmutableArray<int>> CustomAttributesAdded; internal readonly ImmutableArray<int> TableEntriesAdded; internal readonly int BlobStreamLengthAdded; internal readonly int StringStreamLengthAdded; internal readonly int UserStringStreamLengthAdded; internal readonly int GuidStreamLengthAdded; /// <summary> /// EnC metadata for methods added or updated since the initial generation, indexed by method row id. /// </summary> internal readonly IReadOnlyDictionary<int, AddedOrChangedMethodInfo> AddedOrChangedMethods; /// <summary> /// Reads EnC debug information of a method from the initial baseline PDB. /// The function shall throw <see cref="InvalidDataException"/> if the debug information can't be read for the specified method. /// This exception and <see cref="IOException"/> are caught and converted to an emit diagnostic. Other exceptions are passed through. /// The function shall return an empty <see cref="EditAndContinueMethodDebugInformation"/> if the method that corresponds to the specified handle /// has no debug information. /// </summary> internal readonly Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> DebugInformationProvider; /// <summary> /// A function that for a method handle returns the signature of its local variables. /// The function shall throw <see cref="InvalidDataException"/> if the information can't be read for the specified method. /// This exception and <see cref="IOException"/> are caught and converted to an emit diagnostic. Other exceptions are passed through. /// The function shall return a nil <see cref="StandaloneSignatureHandle"/> if the method that corresponds to the specified handle /// has no local variables. /// </summary> internal readonly Func<MethodDefinitionHandle, StandaloneSignatureHandle> LocalSignatureProvider; internal readonly ImmutableArray<int> TableSizes; internal readonly IReadOnlyDictionary<int, int> TypeToEventMap; internal readonly IReadOnlyDictionary<int, int> TypeToPropertyMap; internal readonly IReadOnlyDictionary<MethodImplKey, int> MethodImpls; private readonly IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue>? _anonymousTypeMap; internal readonly ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> SynthesizedMembers; private EmitBaseline( EmitBaseline? initialBaseline, ModuleMetadata module, Compilation? compilation, CommonPEModuleBuilder? moduleBuilder, Guid moduleVersionId, int ordinal, Guid encId, bool hasPortablePdb, IReadOnlyDictionary<Cci.IDefinition, int> generationOrdinals, IReadOnlyDictionary<Cci.ITypeDefinition, int> typesAdded, IReadOnlyDictionary<Cci.IEventDefinition, int> eventsAdded, IReadOnlyDictionary<Cci.IFieldDefinition, int> fieldsAdded, IReadOnlyDictionary<Cci.IMethodDefinition, int> methodsAdded, IReadOnlyDictionary<MethodDefinitionHandle, int> firstParamRowMap, IReadOnlyDictionary<Cci.IPropertyDefinition, int> propertiesAdded, IReadOnlyDictionary<int, int> eventMapAdded, IReadOnlyDictionary<int, int> propertyMapAdded, IReadOnlyDictionary<MethodImplKey, int> methodImplsAdded, IReadOnlyDictionary<EntityHandle, ImmutableArray<int>> customAttributesAdded, ImmutableArray<int> tableEntriesAdded, int blobStreamLengthAdded, int stringStreamLengthAdded, int userStringStreamLengthAdded, int guidStreamLengthAdded, IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue>? anonymousTypeMap, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> synthesizedMembers, IReadOnlyDictionary<int, AddedOrChangedMethodInfo> methodsAddedOrChanged, Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> debugInformationProvider, Func<MethodDefinitionHandle, StandaloneSignatureHandle> localSignatureProvider, IReadOnlyDictionary<int, int> typeToEventMap, IReadOnlyDictionary<int, int> typeToPropertyMap, IReadOnlyDictionary<MethodImplKey, int> methodImpls) { Debug.Assert(module != null); Debug.Assert((ordinal == 0) == (encId == default)); Debug.Assert((ordinal == 0) == (initialBaseline == null)); Debug.Assert((ordinal == 0) == (anonymousTypeMap == null)); Debug.Assert(encId != module.GetModuleVersionId()); Debug.Assert(debugInformationProvider != null); Debug.Assert(localSignatureProvider != null); Debug.Assert(typeToEventMap != null); Debug.Assert(typeToPropertyMap != null); Debug.Assert(moduleVersionId != default); Debug.Assert(moduleVersionId == module.GetModuleVersionId()); Debug.Assert(synthesizedMembers != null); Debug.Assert(tableEntriesAdded.Length == MetadataTokens.TableCount); // The size of each table is the total number of entries added in all previous // generations after the initial generation. Depending on the table, some of the // entries may not be available in the current generation (say, a synthesized type // from a method that was not recompiled for instance) Debug.Assert(tableEntriesAdded[(int)TableIndex.TypeDef] >= typesAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.Event] >= eventsAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.Field] >= fieldsAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.MethodDef] >= methodsAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.Property] >= propertiesAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.EventMap] >= eventMapAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.PropertyMap] >= propertyMapAdded.Count); var reader = module.Module.MetadataReader; InitialBaseline = initialBaseline ?? this; OriginalMetadata = module; Compilation = compilation; PEModuleBuilder = moduleBuilder; ModuleVersionId = moduleVersionId; Ordinal = ordinal; EncId = encId; HasPortablePdb = hasPortablePdb; GenerationOrdinals = generationOrdinals; TypesAdded = typesAdded; EventsAdded = eventsAdded; FieldsAdded = fieldsAdded; MethodsAdded = methodsAdded; FirstParamRowMap = firstParamRowMap; PropertiesAdded = propertiesAdded; EventMapAdded = eventMapAdded; PropertyMapAdded = propertyMapAdded; MethodImplsAdded = methodImplsAdded; CustomAttributesAdded = customAttributesAdded; TableEntriesAdded = tableEntriesAdded; BlobStreamLengthAdded = blobStreamLengthAdded; StringStreamLengthAdded = stringStreamLengthAdded; UserStringStreamLengthAdded = userStringStreamLengthAdded; GuidStreamLengthAdded = guidStreamLengthAdded; _anonymousTypeMap = anonymousTypeMap; SynthesizedMembers = synthesizedMembers; AddedOrChangedMethods = methodsAddedOrChanged; DebugInformationProvider = debugInformationProvider; LocalSignatureProvider = localSignatureProvider; TableSizes = CalculateTableSizes(reader, TableEntriesAdded); TypeToEventMap = typeToEventMap; TypeToPropertyMap = typeToPropertyMap; MethodImpls = methodImpls; } internal EmitBaseline With( Compilation compilation, CommonPEModuleBuilder moduleBuilder, int ordinal, Guid encId, IReadOnlyDictionary<Cci.IDefinition, int> generationOrdinals, IReadOnlyDictionary<Cci.ITypeDefinition, int> typesAdded, IReadOnlyDictionary<Cci.IEventDefinition, int> eventsAdded, IReadOnlyDictionary<Cci.IFieldDefinition, int> fieldsAdded, IReadOnlyDictionary<Cci.IMethodDefinition, int> methodsAdded, IReadOnlyDictionary<MethodDefinitionHandle, int> firstParamRowMap, IReadOnlyDictionary<Cci.IPropertyDefinition, int> propertiesAdded, IReadOnlyDictionary<int, int> eventMapAdded, IReadOnlyDictionary<int, int> propertyMapAdded, IReadOnlyDictionary<MethodImplKey, int> methodImplsAdded, IReadOnlyDictionary<EntityHandle, ImmutableArray<int>> customAttributesAdded, ImmutableArray<int> tableEntriesAdded, int blobStreamLengthAdded, int stringStreamLengthAdded, int userStringStreamLengthAdded, int guidStreamLengthAdded, IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> synthesizedMembers, IReadOnlyDictionary<int, AddedOrChangedMethodInfo> addedOrChangedMethods, Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> debugInformationProvider, Func<MethodDefinitionHandle, StandaloneSignatureHandle> localSignatureProvider) { Debug.Assert(_anonymousTypeMap == null || anonymousTypeMap != null); Debug.Assert(_anonymousTypeMap == null || anonymousTypeMap.Count >= _anonymousTypeMap.Count); return new EmitBaseline( InitialBaseline, OriginalMetadata, compilation, moduleBuilder, ModuleVersionId, ordinal, encId, HasPortablePdb, generationOrdinals, typesAdded, eventsAdded, fieldsAdded, methodsAdded, firstParamRowMap, propertiesAdded, eventMapAdded, propertyMapAdded, methodImplsAdded, customAttributesAdded, tableEntriesAdded, blobStreamLengthAdded: blobStreamLengthAdded, stringStreamLengthAdded: stringStreamLengthAdded, userStringStreamLengthAdded: userStringStreamLengthAdded, guidStreamLengthAdded: guidStreamLengthAdded, anonymousTypeMap: anonymousTypeMap, synthesizedMembers: synthesizedMembers, methodsAddedOrChanged: addedOrChangedMethods, debugInformationProvider: debugInformationProvider, localSignatureProvider: localSignatureProvider, typeToEventMap: TypeToEventMap, typeToPropertyMap: TypeToPropertyMap, methodImpls: MethodImpls); } internal IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> AnonymousTypeMap { get { if (Ordinal > 0) { Debug.Assert(_anonymousTypeMap is object); return _anonymousTypeMap; } RoslynDebug.AssertNotNull(LazyMetadataSymbols); return LazyMetadataSymbols.AnonymousTypes; } } internal MetadataReader MetadataReader { get { return this.OriginalMetadata.MetadataReader; } } internal int BlobStreamLength { get { return this.BlobStreamLengthAdded + this.MetadataReader.GetHeapSize(HeapIndex.Blob); } } internal int StringStreamLength { get { return this.StringStreamLengthAdded + this.MetadataReader.GetHeapSize(HeapIndex.String); } } internal int UserStringStreamLength { get { return this.UserStringStreamLengthAdded + this.MetadataReader.GetHeapSize(HeapIndex.UserString); } } internal int GuidStreamLength { get { return this.GuidStreamLengthAdded + this.MetadataReader.GetHeapSize(HeapIndex.Guid); } } private static ImmutableArray<int> CalculateTableSizes(MetadataReader reader, ImmutableArray<int> delta) { var sizes = new int[MetadataTokens.TableCount]; for (int i = 0; i < sizes.Length; i++) { sizes[i] = reader.GetTableRowCount((TableIndex)i) + delta[i]; } return ImmutableArray.Create(sizes); } private static Dictionary<int, int> CalculateTypePropertyMap(MetadataReader reader) { var result = new Dictionary<int, int>(); int rowId = 1; foreach (var parentType in reader.GetTypesWithProperties()) { Debug.Assert(!parentType.IsNil); result.Add(reader.GetRowNumber(parentType), rowId); rowId++; } return result; } private static Dictionary<int, int> CalculateTypeEventMap(MetadataReader reader) { var result = new Dictionary<int, int>(); int rowId = 1; foreach (var parentType in reader.GetTypesWithEvents()) { Debug.Assert(!parentType.IsNil); result.Add(reader.GetRowNumber(parentType), rowId); rowId++; } return result; } private static Dictionary<MethodImplKey, int> CalculateMethodImpls(MetadataReader reader) { var result = new Dictionary<MethodImplKey, int>(); int n = reader.GetTableRowCount(TableIndex.MethodImpl); for (int row = 1; row <= n; row++) { var methodImpl = reader.GetMethodImplementation(MetadataTokens.MethodImplementationHandle(row)); // Hold on to the implementing method def but use a simple // index for the implemented method ref token. (We do not map // member refs currently, and since we don't allow changes to // the set of methods a method def implements, the actual // tokens of the implemented methods are not needed.) int methodDefRow = MetadataTokens.GetRowNumber(methodImpl.MethodBody); int index = 1; while (true) { var key = new MethodImplKey(methodDefRow, index); if (!result.ContainsKey(key)) { result.Add(key, row); break; } index++; } } return result; } internal int GetNextAnonymousTypeIndex(bool fromDelegates = false) { int nextIndex = 0; foreach (var pair in this.AnonymousTypeMap) { if (fromDelegates != pair.Key.IsDelegate) { continue; } int index = pair.Value.UniqueIndex; if (index >= nextIndex) { nextIndex = index + 1; } } return nextIndex; } } }
// 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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { // A MethodImpl entry is a pair of implementing method and implemented // method. However, the implemented method is a MemberRef rather // than a MethodDef (e.g.: I<int>.M) and currently we are not mapping // MemberRefs between generations so it's not possible to track the // implemented method. Instead, recognizing that we do not support // changes to the set of implemented methods for a particular MethodDef, // and that we do not use the implementing methods anywhere, it's // sufficient to track a pair of implementing method and index. internal struct MethodImplKey : IEquatable<MethodImplKey> { internal MethodImplKey(int implementingMethod, int index) { Debug.Assert(implementingMethod > 0); Debug.Assert(index > 0); this.ImplementingMethod = implementingMethod; this.Index = index; } internal readonly int ImplementingMethod; internal readonly int Index; public override bool Equals(object? obj) { return obj is MethodImplKey && Equals((MethodImplKey)obj); } public bool Equals(MethodImplKey other) { return this.ImplementingMethod == other.ImplementingMethod && this.Index == other.Index; } public override int GetHashCode() { return Hash.Combine(this.ImplementingMethod, this.Index); } } /// <summary> /// Represents a module from a previous compilation. Used in Edit and Continue /// to emit the differences in a subsequent compilation. /// </summary> public sealed class EmitBaseline { private static readonly ImmutableArray<int> s_emptyTableSizes = ImmutableArray.Create(new int[MetadataTokens.TableCount]); internal sealed class MetadataSymbols { public readonly IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> AnonymousTypes; public readonly IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> SynthesizedDelegates; /// <summary> /// A map of the assembly identities of the baseline compilation to the identities of the original metadata AssemblyRefs. /// Only includes identities that differ between these two. /// </summary> public readonly ImmutableDictionary<AssemblyIdentity, AssemblyIdentity> AssemblyReferenceIdentityMap; public readonly object MetadataDecoder; public MetadataSymbols( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypes, IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> synthesizedDelegates, object metadataDecoder, ImmutableDictionary<AssemblyIdentity, AssemblyIdentity> assemblyReferenceIdentityMap) { Debug.Assert(anonymousTypes != null); Debug.Assert(synthesizedDelegates != null); Debug.Assert(metadataDecoder != null); Debug.Assert(assemblyReferenceIdentityMap != null); this.AnonymousTypes = anonymousTypes; this.SynthesizedDelegates = synthesizedDelegates; this.MetadataDecoder = metadataDecoder; this.AssemblyReferenceIdentityMap = assemblyReferenceIdentityMap; } } /// <summary> /// Creates an <see cref="EmitBaseline"/> from the metadata of the module before editing /// and from a function that maps from a method to an array of local names. /// </summary> /// <param name="module">The metadata of the module before editing.</param> /// <param name="debugInformationProvider"> /// A function that for a method handle returns Edit and Continue debug information emitted by the compiler into the PDB. /// The function shall throw <see cref="InvalidDataException"/> if the debug information can't be read for the specified method. /// This exception and <see cref="IOException"/> are caught and converted to an emit diagnostic. Other exceptions are passed through. /// </param> /// <returns>An <see cref="EmitBaseline"/> for the module.</returns> /// <exception cref="ArgumentException"><paramref name="module"/> is not a PE image.</exception> /// <exception cref="ArgumentNullException"><paramref name="module"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="debugInformationProvider"/> is null.</exception> /// <exception cref="IOException">Error reading module metadata.</exception> /// <exception cref="BadImageFormatException">Module metadata is invalid.</exception> /// <exception cref="ObjectDisposedException">Module has been disposed.</exception> public static EmitBaseline CreateInitialBaseline(ModuleMetadata module, Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> debugInformationProvider) { if (module == null) { throw new ArgumentNullException(nameof(module)); } if (!module.Module.HasIL) { throw new ArgumentException(CodeAnalysisResources.PEImageNotAvailable, nameof(module)); } var hasPortablePdb = module.Module.PEReaderOpt.ReadDebugDirectory().Any(entry => entry.IsPortableCodeView); var localSigProvider = new Func<MethodDefinitionHandle, StandaloneSignatureHandle>(methodHandle => { try { return module.Module.GetMethodBodyOrThrow(methodHandle)?.LocalSignature ?? default; } catch (Exception e) when (e is BadImageFormatException || e is IOException) { throw new InvalidDataException(e.Message, e); } }); return CreateInitialBaseline(module, debugInformationProvider, localSigProvider, hasPortablePdb); } /// <summary> /// Creates an <see cref="EmitBaseline"/> from the metadata of the module before editing /// and from a function that maps from a method to an array of local names. /// </summary> /// <param name="module">The metadata of the module before editing.</param> /// <param name="debugInformationProvider"> /// A function that for a method handle returns Edit and Continue debug information emitted by the compiler into the PDB. /// The function shall throw <see cref="InvalidDataException"/> if the debug information can't be read for the specified method. /// This exception and <see cref="IOException"/> are caught and converted to an emit diagnostic. Other exceptions are passed through. /// </param> /// <param name="localSignatureProvider"> /// A function that for a method handle returns the signature of its local variables. /// The function shall throw <see cref="InvalidDataException"/> if the information can't be read for the specified method. /// This exception and <see cref="IOException"/> are caught and converted to an emit diagnostic. Other exceptions are passed through. /// </param> /// <param name="hasPortableDebugInformation"> /// True if the baseline PDB is portable. /// </param> /// <returns>An <see cref="EmitBaseline"/> for the module.</returns> /// <remarks> /// Only the initial baseline is created using this method; subsequent baselines are created /// automatically when emitting the differences in subsequent compilations. /// /// When an active method (one for which a frame is allocated on a stack) is updated the values of its local variables need to be preserved. /// The mapping of local variable names to their slots in the frame is not included in the metadata and thus needs to be provided by /// <paramref name="debugInformationProvider"/>. /// /// The <paramref name="debugInformationProvider"/> is only needed for the initial generation. The mapping for the subsequent generations /// is carried over through <see cref="EmitBaseline"/>. The compiler assigns slots to named local variables (including named temporary variables) /// it the order in which they appear in the source code. This property allows the compiler to reconstruct the local variable mapping /// for the initial generation. A subsequent generation may add a new variable in between two variables of the previous generation. /// Since the slots of the previous generation variables need to be preserved the only option is to add these new variables to the end. /// The slot ordering thus no longer matches the syntax ordering. It is therefore necessary to pass <see cref="EmitDifferenceResult.Baseline"/> /// to the next generation (rather than e.g. create new <see cref="EmitBaseline"/>s from scratch based on metadata produced by subsequent compilations). /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="module"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="debugInformationProvider"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="localSignatureProvider"/> is null.</exception> /// <exception cref="IOException">Error reading module metadata.</exception> /// <exception cref="BadImageFormatException">Module metadata is invalid.</exception> /// <exception cref="ObjectDisposedException">Module has been disposed.</exception> public static EmitBaseline CreateInitialBaseline( ModuleMetadata module, Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> debugInformationProvider, Func<MethodDefinitionHandle, StandaloneSignatureHandle> localSignatureProvider, bool hasPortableDebugInformation) { if (module == null) { throw new ArgumentNullException(nameof(module)); } if (debugInformationProvider == null) { throw new ArgumentNullException(nameof(debugInformationProvider)); } if (localSignatureProvider == null) { throw new ArgumentNullException(nameof(localSignatureProvider)); } var reader = module.MetadataReader; return new EmitBaseline( null, module, compilation: null, moduleBuilder: null, moduleVersionId: module.GetModuleVersionId(), ordinal: 0, encId: default, hasPortablePdb: hasPortableDebugInformation, generationOrdinals: new Dictionary<Cci.IDefinition, int>(), typesAdded: new Dictionary<Cci.ITypeDefinition, int>(), eventsAdded: new Dictionary<Cci.IEventDefinition, int>(), fieldsAdded: new Dictionary<Cci.IFieldDefinition, int>(), methodsAdded: new Dictionary<Cci.IMethodDefinition, int>(), firstParamRowMap: new Dictionary<MethodDefinitionHandle, int>(), propertiesAdded: new Dictionary<Cci.IPropertyDefinition, int>(), eventMapAdded: new Dictionary<int, int>(), propertyMapAdded: new Dictionary<int, int>(), methodImplsAdded: new Dictionary<MethodImplKey, int>(), customAttributesAdded: new Dictionary<EntityHandle, ImmutableArray<int>>(), tableEntriesAdded: s_emptyTableSizes, blobStreamLengthAdded: 0, stringStreamLengthAdded: 0, userStringStreamLengthAdded: 0, guidStreamLengthAdded: 0, anonymousTypeMap: null, // Unset for initial metadata synthesizedDelegates: null, // Unset for initial metadata synthesizedMembers: ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>.Empty, methodsAddedOrChanged: new Dictionary<int, AddedOrChangedMethodInfo>(), debugInformationProvider: debugInformationProvider, localSignatureProvider: localSignatureProvider, typeToEventMap: CalculateTypeEventMap(reader), typeToPropertyMap: CalculateTypePropertyMap(reader), methodImpls: CalculateMethodImpls(reader)); } internal EmitBaseline InitialBaseline { get; } /// <summary> /// The original metadata of the module. /// </summary> public ModuleMetadata OriginalMetadata { get; } // Symbols hydrated from the original metadata. Lazy since we don't know the language at the time the baseline is constructed. internal MetadataSymbols? LazyMetadataSymbols; internal readonly Compilation? Compilation; internal readonly CommonPEModuleBuilder? PEModuleBuilder; internal readonly Guid ModuleVersionId; internal readonly bool HasPortablePdb; /// <summary> /// Metadata generation ordinal. Zero for /// full metadata and non-zero for delta. /// </summary> internal readonly int Ordinal; /// <summary> /// Unique Guid for this delta, or default(Guid) /// if full metadata. /// </summary> internal readonly Guid EncId; /// <summary> /// The latest generation number of each symbol added via <see cref="SemanticEditKind.Replace"/> edit. /// </summary> internal readonly IReadOnlyDictionary<Cci.IDefinition, int> GenerationOrdinals; internal readonly IReadOnlyDictionary<Cci.ITypeDefinition, int> TypesAdded; internal readonly IReadOnlyDictionary<Cci.IEventDefinition, int> EventsAdded; internal readonly IReadOnlyDictionary<Cci.IFieldDefinition, int> FieldsAdded; internal readonly IReadOnlyDictionary<Cci.IMethodDefinition, int> MethodsAdded; internal readonly IReadOnlyDictionary<MethodDefinitionHandle, int> FirstParamRowMap; internal readonly IReadOnlyDictionary<Cci.IPropertyDefinition, int> PropertiesAdded; internal readonly IReadOnlyDictionary<int, int> EventMapAdded; internal readonly IReadOnlyDictionary<int, int> PropertyMapAdded; internal readonly IReadOnlyDictionary<MethodImplKey, int> MethodImplsAdded; internal readonly IReadOnlyDictionary<EntityHandle, ImmutableArray<int>> CustomAttributesAdded; internal readonly ImmutableArray<int> TableEntriesAdded; internal readonly int BlobStreamLengthAdded; internal readonly int StringStreamLengthAdded; internal readonly int UserStringStreamLengthAdded; internal readonly int GuidStreamLengthAdded; /// <summary> /// EnC metadata for methods added or updated since the initial generation, indexed by method row id. /// </summary> internal readonly IReadOnlyDictionary<int, AddedOrChangedMethodInfo> AddedOrChangedMethods; /// <summary> /// Reads EnC debug information of a method from the initial baseline PDB. /// The function shall throw <see cref="InvalidDataException"/> if the debug information can't be read for the specified method. /// This exception and <see cref="IOException"/> are caught and converted to an emit diagnostic. Other exceptions are passed through. /// The function shall return an empty <see cref="EditAndContinueMethodDebugInformation"/> if the method that corresponds to the specified handle /// has no debug information. /// </summary> internal readonly Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> DebugInformationProvider; /// <summary> /// A function that for a method handle returns the signature of its local variables. /// The function shall throw <see cref="InvalidDataException"/> if the information can't be read for the specified method. /// This exception and <see cref="IOException"/> are caught and converted to an emit diagnostic. Other exceptions are passed through. /// The function shall return a nil <see cref="StandaloneSignatureHandle"/> if the method that corresponds to the specified handle /// has no local variables. /// </summary> internal readonly Func<MethodDefinitionHandle, StandaloneSignatureHandle> LocalSignatureProvider; internal readonly ImmutableArray<int> TableSizes; internal readonly IReadOnlyDictionary<int, int> TypeToEventMap; internal readonly IReadOnlyDictionary<int, int> TypeToPropertyMap; internal readonly IReadOnlyDictionary<MethodImplKey, int> MethodImpls; private readonly IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue>? _anonymousTypeMap; private readonly IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>? _synthesizedDelegates; internal readonly ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> SynthesizedMembers; private EmitBaseline( EmitBaseline? initialBaseline, ModuleMetadata module, Compilation? compilation, CommonPEModuleBuilder? moduleBuilder, Guid moduleVersionId, int ordinal, Guid encId, bool hasPortablePdb, IReadOnlyDictionary<Cci.IDefinition, int> generationOrdinals, IReadOnlyDictionary<Cci.ITypeDefinition, int> typesAdded, IReadOnlyDictionary<Cci.IEventDefinition, int> eventsAdded, IReadOnlyDictionary<Cci.IFieldDefinition, int> fieldsAdded, IReadOnlyDictionary<Cci.IMethodDefinition, int> methodsAdded, IReadOnlyDictionary<MethodDefinitionHandle, int> firstParamRowMap, IReadOnlyDictionary<Cci.IPropertyDefinition, int> propertiesAdded, IReadOnlyDictionary<int, int> eventMapAdded, IReadOnlyDictionary<int, int> propertyMapAdded, IReadOnlyDictionary<MethodImplKey, int> methodImplsAdded, IReadOnlyDictionary<EntityHandle, ImmutableArray<int>> customAttributesAdded, ImmutableArray<int> tableEntriesAdded, int blobStreamLengthAdded, int stringStreamLengthAdded, int userStringStreamLengthAdded, int guidStreamLengthAdded, IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue>? anonymousTypeMap, IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>? synthesizedDelegates, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> synthesizedMembers, IReadOnlyDictionary<int, AddedOrChangedMethodInfo> methodsAddedOrChanged, Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> debugInformationProvider, Func<MethodDefinitionHandle, StandaloneSignatureHandle> localSignatureProvider, IReadOnlyDictionary<int, int> typeToEventMap, IReadOnlyDictionary<int, int> typeToPropertyMap, IReadOnlyDictionary<MethodImplKey, int> methodImpls) { Debug.Assert(module != null); Debug.Assert((ordinal == 0) == (encId == default)); Debug.Assert((ordinal == 0) == (initialBaseline == null)); Debug.Assert((ordinal == 0) == (anonymousTypeMap == null)); Debug.Assert((ordinal == 0) == (synthesizedDelegates == null)); Debug.Assert(encId != module.GetModuleVersionId()); Debug.Assert(debugInformationProvider != null); Debug.Assert(localSignatureProvider != null); Debug.Assert(typeToEventMap != null); Debug.Assert(typeToPropertyMap != null); Debug.Assert(moduleVersionId != default); Debug.Assert(moduleVersionId == module.GetModuleVersionId()); Debug.Assert(synthesizedMembers != null); Debug.Assert(tableEntriesAdded.Length == MetadataTokens.TableCount); // The size of each table is the total number of entries added in all previous // generations after the initial generation. Depending on the table, some of the // entries may not be available in the current generation (say, a synthesized type // from a method that was not recompiled for instance) Debug.Assert(tableEntriesAdded[(int)TableIndex.TypeDef] >= typesAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.Event] >= eventsAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.Field] >= fieldsAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.MethodDef] >= methodsAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.Property] >= propertiesAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.EventMap] >= eventMapAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.PropertyMap] >= propertyMapAdded.Count); var reader = module.Module.MetadataReader; InitialBaseline = initialBaseline ?? this; OriginalMetadata = module; Compilation = compilation; PEModuleBuilder = moduleBuilder; ModuleVersionId = moduleVersionId; Ordinal = ordinal; EncId = encId; HasPortablePdb = hasPortablePdb; GenerationOrdinals = generationOrdinals; TypesAdded = typesAdded; EventsAdded = eventsAdded; FieldsAdded = fieldsAdded; MethodsAdded = methodsAdded; FirstParamRowMap = firstParamRowMap; PropertiesAdded = propertiesAdded; EventMapAdded = eventMapAdded; PropertyMapAdded = propertyMapAdded; MethodImplsAdded = methodImplsAdded; CustomAttributesAdded = customAttributesAdded; TableEntriesAdded = tableEntriesAdded; BlobStreamLengthAdded = blobStreamLengthAdded; StringStreamLengthAdded = stringStreamLengthAdded; UserStringStreamLengthAdded = userStringStreamLengthAdded; GuidStreamLengthAdded = guidStreamLengthAdded; _anonymousTypeMap = anonymousTypeMap; _synthesizedDelegates = synthesizedDelegates; SynthesizedMembers = synthesizedMembers; AddedOrChangedMethods = methodsAddedOrChanged; DebugInformationProvider = debugInformationProvider; LocalSignatureProvider = localSignatureProvider; TableSizes = CalculateTableSizes(reader, TableEntriesAdded); TypeToEventMap = typeToEventMap; TypeToPropertyMap = typeToPropertyMap; MethodImpls = methodImpls; } internal EmitBaseline With( Compilation compilation, CommonPEModuleBuilder moduleBuilder, int ordinal, Guid encId, IReadOnlyDictionary<Cci.IDefinition, int> generationOrdinals, IReadOnlyDictionary<Cci.ITypeDefinition, int> typesAdded, IReadOnlyDictionary<Cci.IEventDefinition, int> eventsAdded, IReadOnlyDictionary<Cci.IFieldDefinition, int> fieldsAdded, IReadOnlyDictionary<Cci.IMethodDefinition, int> methodsAdded, IReadOnlyDictionary<MethodDefinitionHandle, int> firstParamRowMap, IReadOnlyDictionary<Cci.IPropertyDefinition, int> propertiesAdded, IReadOnlyDictionary<int, int> eventMapAdded, IReadOnlyDictionary<int, int> propertyMapAdded, IReadOnlyDictionary<MethodImplKey, int> methodImplsAdded, IReadOnlyDictionary<EntityHandle, ImmutableArray<int>> customAttributesAdded, ImmutableArray<int> tableEntriesAdded, int blobStreamLengthAdded, int stringStreamLengthAdded, int userStringStreamLengthAdded, int guidStreamLengthAdded, IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> synthesizedDelegates, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> synthesizedMembers, IReadOnlyDictionary<int, AddedOrChangedMethodInfo> addedOrChangedMethods, Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> debugInformationProvider, Func<MethodDefinitionHandle, StandaloneSignatureHandle> localSignatureProvider) { Debug.Assert(_anonymousTypeMap == null || anonymousTypeMap != null); Debug.Assert(_anonymousTypeMap == null || anonymousTypeMap.Count >= _anonymousTypeMap.Count); Debug.Assert(_synthesizedDelegates == null || synthesizedDelegates != null); Debug.Assert(_synthesizedDelegates == null || synthesizedDelegates.Count >= _synthesizedDelegates.Count); return new EmitBaseline( InitialBaseline, OriginalMetadata, compilation, moduleBuilder, ModuleVersionId, ordinal, encId, HasPortablePdb, generationOrdinals, typesAdded, eventsAdded, fieldsAdded, methodsAdded, firstParamRowMap, propertiesAdded, eventMapAdded, propertyMapAdded, methodImplsAdded, customAttributesAdded, tableEntriesAdded, blobStreamLengthAdded: blobStreamLengthAdded, stringStreamLengthAdded: stringStreamLengthAdded, userStringStreamLengthAdded: userStringStreamLengthAdded, guidStreamLengthAdded: guidStreamLengthAdded, anonymousTypeMap: anonymousTypeMap, synthesizedDelegates: synthesizedDelegates, synthesizedMembers: synthesizedMembers, methodsAddedOrChanged: addedOrChangedMethods, debugInformationProvider: debugInformationProvider, localSignatureProvider: localSignatureProvider, typeToEventMap: TypeToEventMap, typeToPropertyMap: TypeToPropertyMap, methodImpls: MethodImpls); } internal IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> AnonymousTypeMap { get { if (Ordinal > 0) { Debug.Assert(_anonymousTypeMap is object); return _anonymousTypeMap; } RoslynDebug.AssertNotNull(LazyMetadataSymbols); return LazyMetadataSymbols.AnonymousTypes; } } internal IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> SynthesizedDelegates { get { if (Ordinal > 0) { Debug.Assert(_synthesizedDelegates is not null); return _synthesizedDelegates; } RoslynDebug.AssertNotNull(LazyMetadataSymbols); return LazyMetadataSymbols.SynthesizedDelegates; } } internal MetadataReader MetadataReader { get { return this.OriginalMetadata.MetadataReader; } } internal int BlobStreamLength { get { return this.BlobStreamLengthAdded + this.MetadataReader.GetHeapSize(HeapIndex.Blob); } } internal int StringStreamLength { get { return this.StringStreamLengthAdded + this.MetadataReader.GetHeapSize(HeapIndex.String); } } internal int UserStringStreamLength { get { return this.UserStringStreamLengthAdded + this.MetadataReader.GetHeapSize(HeapIndex.UserString); } } internal int GuidStreamLength { get { return this.GuidStreamLengthAdded + this.MetadataReader.GetHeapSize(HeapIndex.Guid); } } private static ImmutableArray<int> CalculateTableSizes(MetadataReader reader, ImmutableArray<int> delta) { var sizes = new int[MetadataTokens.TableCount]; for (int i = 0; i < sizes.Length; i++) { sizes[i] = reader.GetTableRowCount((TableIndex)i) + delta[i]; } return ImmutableArray.Create(sizes); } private static Dictionary<int, int> CalculateTypePropertyMap(MetadataReader reader) { var result = new Dictionary<int, int>(); int rowId = 1; foreach (var parentType in reader.GetTypesWithProperties()) { Debug.Assert(!parentType.IsNil); result.Add(reader.GetRowNumber(parentType), rowId); rowId++; } return result; } private static Dictionary<int, int> CalculateTypeEventMap(MetadataReader reader) { var result = new Dictionary<int, int>(); int rowId = 1; foreach (var parentType in reader.GetTypesWithEvents()) { Debug.Assert(!parentType.IsNil); result.Add(reader.GetRowNumber(parentType), rowId); rowId++; } return result; } private static Dictionary<MethodImplKey, int> CalculateMethodImpls(MetadataReader reader) { var result = new Dictionary<MethodImplKey, int>(); int n = reader.GetTableRowCount(TableIndex.MethodImpl); for (int row = 1; row <= n; row++) { var methodImpl = reader.GetMethodImplementation(MetadataTokens.MethodImplementationHandle(row)); // Hold on to the implementing method def but use a simple // index for the implemented method ref token. (We do not map // member refs currently, and since we don't allow changes to // the set of methods a method def implements, the actual // tokens of the implemented methods are not needed.) int methodDefRow = MetadataTokens.GetRowNumber(methodImpl.MethodBody); int index = 1; while (true) { var key = new MethodImplKey(methodDefRow, index); if (!result.ContainsKey(key)) { result.Add(key, row); break; } index++; } } return result; } internal int GetNextAnonymousTypeIndex(bool fromDelegates = false) { int nextIndex = 0; foreach (var pair in this.AnonymousTypeMap) { if (fromDelegates != pair.Key.IsDelegate) { continue; } int index = pair.Value.UniqueIndex; if (index >= nextIndex) { nextIndex = index + 1; } } return nextIndex; } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Core/Portable/Emit/EditAndContinue/IPEDeltaAssemblyBuilder.cs
// 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 System.Collections.Generic; namespace Microsoft.CodeAnalysis.Emit { internal interface IPEDeltaAssemblyBuilder { void OnCreatedIndices(DiagnosticBag diagnostics); IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> GetAnonymousTypeMap(); } }
// 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 System.Collections.Generic; namespace Microsoft.CodeAnalysis.Emit { internal interface IPEDeltaAssemblyBuilder { void OnCreatedIndices(DiagnosticBag diagnostics); IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> GetAnonymousTypeMap(); IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> GetSynthesizedDelegates(); } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Core/Portable/Emit/EditAndContinue/SymbolMatcher.cs
// 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 System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal abstract class SymbolMatcher { public abstract Cci.ITypeReference? MapReference(Cci.ITypeReference reference); public abstract Cci.IDefinition? MapDefinition(Cci.IDefinition definition); public abstract Cci.INamespace? MapNamespace(Cci.INamespace @namespace); public ISymbolInternal? MapDefinitionOrNamespace(ISymbolInternal symbol) { var adapter = symbol.GetCciAdapter(); return (adapter is Cci.IDefinition definition) ? MapDefinition(definition)?.GetInternalSymbol() : MapNamespace((Cci.INamespace)adapter)?.GetInternalSymbol(); } public EmitBaseline MapBaselineToCompilation( EmitBaseline baseline, Compilation targetCompilation, CommonPEModuleBuilder targetModuleBuilder, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> mappedSynthesizedMembers) { // Map all definitions to this compilation. var typesAdded = MapDefinitions(baseline.TypesAdded); var eventsAdded = MapDefinitions(baseline.EventsAdded); var fieldsAdded = MapDefinitions(baseline.FieldsAdded); var methodsAdded = MapDefinitions(baseline.MethodsAdded); var propertiesAdded = MapDefinitions(baseline.PropertiesAdded); var generationOrdinals = MapDefinitions(baseline.GenerationOrdinals); return baseline.With( targetCompilation, targetModuleBuilder, baseline.Ordinal, baseline.EncId, generationOrdinals, typesAdded, eventsAdded, fieldsAdded, methodsAdded, firstParamRowMap: baseline.FirstParamRowMap, propertiesAdded, eventMapAdded: baseline.EventMapAdded, propertyMapAdded: baseline.PropertyMapAdded, methodImplsAdded: baseline.MethodImplsAdded, customAttributesAdded: baseline.CustomAttributesAdded, tableEntriesAdded: baseline.TableEntriesAdded, blobStreamLengthAdded: baseline.BlobStreamLengthAdded, stringStreamLengthAdded: baseline.StringStreamLengthAdded, userStringStreamLengthAdded: baseline.UserStringStreamLengthAdded, guidStreamLengthAdded: baseline.GuidStreamLengthAdded, anonymousTypeMap: MapAnonymousTypes(baseline.AnonymousTypeMap), synthesizedMembers: mappedSynthesizedMembers, addedOrChangedMethods: MapAddedOrChangedMethods(baseline.AddedOrChangedMethods), debugInformationProvider: baseline.DebugInformationProvider, localSignatureProvider: baseline.LocalSignatureProvider); } private IReadOnlyDictionary<K, V> MapDefinitions<K, V>(IReadOnlyDictionary<K, V> items) where K : class, Cci.IDefinition { var result = new Dictionary<K, V>(Cci.SymbolEquivalentEqualityComparer.Instance); foreach (var pair in items) { var key = (K?)MapDefinition(pair.Key); // Result may be null if the definition was deleted, or if the definition // was synthesized (e.g.: an iterator type) and the method that generated // the synthesized definition was unchanged and not recompiled. if (key != null) { result.Add(key, pair.Value); } } return result; } private IReadOnlyDictionary<int, AddedOrChangedMethodInfo> MapAddedOrChangedMethods(IReadOnlyDictionary<int, AddedOrChangedMethodInfo> addedOrChangedMethods) { var result = new Dictionary<int, AddedOrChangedMethodInfo>(); foreach (var pair in addedOrChangedMethods) { result.Add(pair.Key, pair.Value.MapTypes(this)); } return result; } private IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> MapAnonymousTypes(IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap) { var result = new Dictionary<AnonymousTypeKey, AnonymousTypeValue>(); foreach (var pair in anonymousTypeMap) { var key = pair.Key; var value = pair.Value; var type = (Cci.ITypeDefinition?)MapDefinition(value.Type); RoslynDebug.Assert(type != null); result.Add(key, new AnonymousTypeValue(value.Name, value.UniqueIndex, type)); } return result; } /// <summary> /// Merges synthesized members generated during lowering of the current compilation with aggregate synthesized members /// from all previous source generations (gen >= 1). /// </summary> /// <remarks> /// Suppose {S -> {A, B, D}, T -> {E, F}} are all synthesized members in previous generations, /// and {S' -> {A', B', C}, U -> {G, H}} members are generated in the current compilation. /// /// Where X matches X' via this matcher, i.e. X' is from the new compilation and /// represents the same metadata entity as X in the previous compilation. /// /// Then the resulting collection shall have the following entries: /// {S' -> {A', B', C, D}, U -> {G, H}, T -> {E, F}} /// </remarks> internal ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> MapSynthesizedMembers( ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> previousMembers, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> newMembers) { // Note: we can't just return previous members if there are no new members, since we still need to map the symbols to the new compilation. if (previousMembers.Count == 0) { return newMembers; } var synthesizedMembersBuilder = ImmutableDictionary.CreateBuilder<ISymbolInternal, ImmutableArray<ISymbolInternal>>(); synthesizedMembersBuilder.AddRange(newMembers); foreach (var pair in previousMembers) { var previousContainer = pair.Key; var members = pair.Value; var mappedContainer = MapDefinitionOrNamespace(previousContainer); if (mappedContainer == null) { // No update to any member of the container type. synthesizedMembersBuilder.Add(previousContainer, members); continue; } if (!newMembers.TryGetValue(mappedContainer, out var newSynthesizedMembers)) { // The container has been updated but the update didn't produce any synthesized members. synthesizedMembersBuilder.Add(mappedContainer, members); continue; } // The container has been updated and synthesized members produced. // They might be new or replacing existing ones. Merge existing with new. var memberBuilder = ArrayBuilder<ISymbolInternal>.GetInstance(); memberBuilder.AddRange(newSynthesizedMembers); foreach (var member in members) { var mappedMember = MapDefinitionOrNamespace(member); if (mappedMember != null) { // If the matcher found a member in the current compilation corresponding to previous memberDef, // then the member has to be synthesized and produced as a result of a method update // and thus already contained in newSynthesizedMembers. Debug.Assert(newSynthesizedMembers.Contains(mappedMember)); } else { memberBuilder.Add(member); } } synthesizedMembersBuilder[mappedContainer] = memberBuilder.ToImmutableAndFree(); } return synthesizedMembersBuilder.ToImmutable(); } } }
// 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 System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal abstract class SymbolMatcher { public abstract Cci.ITypeReference? MapReference(Cci.ITypeReference reference); public abstract Cci.IDefinition? MapDefinition(Cci.IDefinition definition); public abstract Cci.INamespace? MapNamespace(Cci.INamespace @namespace); public ISymbolInternal? MapDefinitionOrNamespace(ISymbolInternal symbol) { var adapter = symbol.GetCciAdapter(); return (adapter is Cci.IDefinition definition) ? MapDefinition(definition)?.GetInternalSymbol() : MapNamespace((Cci.INamespace)adapter)?.GetInternalSymbol(); } public EmitBaseline MapBaselineToCompilation( EmitBaseline baseline, Compilation targetCompilation, CommonPEModuleBuilder targetModuleBuilder, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> mappedSynthesizedMembers) { // Map all definitions to this compilation. var typesAdded = MapDefinitions(baseline.TypesAdded); var eventsAdded = MapDefinitions(baseline.EventsAdded); var fieldsAdded = MapDefinitions(baseline.FieldsAdded); var methodsAdded = MapDefinitions(baseline.MethodsAdded); var propertiesAdded = MapDefinitions(baseline.PropertiesAdded); var generationOrdinals = MapDefinitions(baseline.GenerationOrdinals); return baseline.With( targetCompilation, targetModuleBuilder, baseline.Ordinal, baseline.EncId, generationOrdinals, typesAdded, eventsAdded, fieldsAdded, methodsAdded, firstParamRowMap: baseline.FirstParamRowMap, propertiesAdded, eventMapAdded: baseline.EventMapAdded, propertyMapAdded: baseline.PropertyMapAdded, methodImplsAdded: baseline.MethodImplsAdded, customAttributesAdded: baseline.CustomAttributesAdded, tableEntriesAdded: baseline.TableEntriesAdded, blobStreamLengthAdded: baseline.BlobStreamLengthAdded, stringStreamLengthAdded: baseline.StringStreamLengthAdded, userStringStreamLengthAdded: baseline.UserStringStreamLengthAdded, guidStreamLengthAdded: baseline.GuidStreamLengthAdded, anonymousTypeMap: MapAnonymousTypes(baseline.AnonymousTypeMap), synthesizedDelegates: MapSynthesizedDelegates(baseline.SynthesizedDelegates), synthesizedMembers: mappedSynthesizedMembers, addedOrChangedMethods: MapAddedOrChangedMethods(baseline.AddedOrChangedMethods), debugInformationProvider: baseline.DebugInformationProvider, localSignatureProvider: baseline.LocalSignatureProvider); } private IReadOnlyDictionary<K, V> MapDefinitions<K, V>(IReadOnlyDictionary<K, V> items) where K : class, Cci.IDefinition { var result = new Dictionary<K, V>(Cci.SymbolEquivalentEqualityComparer.Instance); foreach (var pair in items) { var key = (K?)MapDefinition(pair.Key); // Result may be null if the definition was deleted, or if the definition // was synthesized (e.g.: an iterator type) and the method that generated // the synthesized definition was unchanged and not recompiled. if (key != null) { result.Add(key, pair.Value); } } return result; } private IReadOnlyDictionary<int, AddedOrChangedMethodInfo> MapAddedOrChangedMethods(IReadOnlyDictionary<int, AddedOrChangedMethodInfo> addedOrChangedMethods) { var result = new Dictionary<int, AddedOrChangedMethodInfo>(); foreach (var pair in addedOrChangedMethods) { result.Add(pair.Key, pair.Value.MapTypes(this)); } return result; } private IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> MapAnonymousTypes(IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap) { var result = new Dictionary<AnonymousTypeKey, AnonymousTypeValue>(); foreach (var (key, value) in anonymousTypeMap) { var type = (Cci.ITypeDefinition?)MapDefinition(value.Type); RoslynDebug.Assert(type != null); result.Add(key, new AnonymousTypeValue(value.Name, value.UniqueIndex, type)); } return result; } private IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> MapSynthesizedDelegates(IReadOnlyDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> synthesizedDelegates) { var result = new Dictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>(); foreach (var (key, value) in synthesizedDelegates) { var delegateTypeDef = (Cci.ITypeDefinition?)MapDefinition(value.Delegate); RoslynDebug.Assert(delegateTypeDef != null); result.Add(key, new SynthesizedDelegateValue(delegateTypeDef)); } return result; } /// <summary> /// Merges synthesized members generated during lowering of the current compilation with aggregate synthesized members /// from all previous source generations (gen >= 1). /// </summary> /// <remarks> /// Suppose {S -> {A, B, D}, T -> {E, F}} are all synthesized members in previous generations, /// and {S' -> {A', B', C}, U -> {G, H}} members are generated in the current compilation. /// /// Where X matches X' via this matcher, i.e. X' is from the new compilation and /// represents the same metadata entity as X in the previous compilation. /// /// Then the resulting collection shall have the following entries: /// {S' -> {A', B', C, D}, U -> {G, H}, T -> {E, F}} /// </remarks> internal ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> MapSynthesizedMembers( ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> previousMembers, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> newMembers) { // Note: we can't just return previous members if there are no new members, since we still need to map the symbols to the new compilation. if (previousMembers.Count == 0) { return newMembers; } var synthesizedMembersBuilder = ImmutableDictionary.CreateBuilder<ISymbolInternal, ImmutableArray<ISymbolInternal>>(); synthesizedMembersBuilder.AddRange(newMembers); foreach (var pair in previousMembers) { var previousContainer = pair.Key; var members = pair.Value; var mappedContainer = MapDefinitionOrNamespace(previousContainer); if (mappedContainer == null) { // No update to any member of the container type. synthesizedMembersBuilder.Add(previousContainer, members); continue; } if (!newMembers.TryGetValue(mappedContainer, out var newSynthesizedMembers)) { // The container has been updated but the update didn't produce any synthesized members. synthesizedMembersBuilder.Add(mappedContainer, members); continue; } // The container has been updated and synthesized members produced. // They might be new or replacing existing ones. Merge existing with new. var memberBuilder = ArrayBuilder<ISymbolInternal>.GetInstance(); memberBuilder.AddRange(newSynthesizedMembers); foreach (var member in members) { var mappedMember = MapDefinitionOrNamespace(member); if (mappedMember != null) { // If the matcher found a member in the current compilation corresponding to previous memberDef, // then the member has to be synthesized and produced as a result of a method update // and thus already contained in newSynthesizedMembers. Debug.Assert(newSynthesizedMembers.Contains(mappedMember)); } else { memberBuilder.Add(member); } } synthesizedMembersBuilder[mappedContainer] = memberBuilder.ToImmutableAndFree(); } return synthesizedMembersBuilder.ToImmutable(); } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Test/Core/Compilation/CompilationDifference.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.DiaSymReader.Tools; using Microsoft.Metadata.Tools; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class CompilationDifference { public readonly ImmutableArray<byte> MetadataDelta; public readonly ImmutableArray<byte> ILDelta; public readonly ImmutableArray<byte> PdbDelta; internal readonly CompilationTestData TestData; public readonly EmitDifferenceResult EmitResult; internal CompilationDifference( ImmutableArray<byte> metadata, ImmutableArray<byte> il, ImmutableArray<byte> pdb, CompilationTestData testData, EmitDifferenceResult result) { MetadataDelta = metadata; ILDelta = il; PdbDelta = pdb; TestData = testData; EmitResult = result; } public EmitBaseline NextGeneration { get { return EmitResult.Baseline; } } internal PinnedMetadata GetMetadata() { return new PinnedMetadata(MetadataDelta); } public void VerifyIL( string expectedIL, [CallerLineNumber] int callerLine = 0, [CallerFilePath] string callerPath = null) { string actualIL = ILDelta.GetMethodIL(); AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine); } public void VerifyLocalSignature( string qualifiedMethodName, string expectedSignature, [CallerLineNumber] int callerLine = 0, [CallerFilePath] string callerPath = null) { var ilBuilder = TestData.GetMethodData(qualifiedMethodName).ILBuilder; string actualSignature = ILBuilderVisualizer.LocalSignatureToString(ilBuilder, ToLocalInfo); AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, actualSignature, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine); } internal void VerifyIL( string qualifiedMethodName, string expectedIL, Func<Cci.ILocalDefinition, ILVisualizer.LocalInfo> mapLocal = null, MethodDefinitionHandle methodToken = default, [CallerFilePath] string callerPath = null, [CallerLineNumber] int callerLine = 0) { var ilBuilder = TestData.GetMethodData(qualifiedMethodName).ILBuilder; Dictionary<int, string> sequencePointMarkers = null; if (!methodToken.IsNil) { string actualPdb = PdbToXmlConverter.DeltaPdbToXml(new ImmutableMemoryStream(PdbDelta), new[] { MetadataTokens.GetToken(methodToken) }); sequencePointMarkers = ILValidation.GetSequencePointMarkers(actualPdb); Assert.True(sequencePointMarkers.Count > 0, $"No sequence points found in:{Environment.NewLine}{actualPdb}"); } string actualIL = ILBuilderVisualizer.ILBuilderToString(ilBuilder, mapLocal ?? ToLocalInfo, sequencePointMarkers); AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine); } internal string GetMethodIL(string qualifiedMethodName) { return ILBuilderVisualizer.ILBuilderToString(this.TestData.GetMethodData(qualifiedMethodName).ILBuilder, ToLocalInfo); } private static ILVisualizer.LocalInfo ToLocalInfo(Cci.ILocalDefinition local) { var signature = local.Signature; if (signature == null) { return new ILVisualizer.LocalInfo(local.Name, local.Type, local.IsPinned, local.IsReference); } else { // Decode simple types only. var typeName = (signature.Length == 1) ? GetTypeName((SignatureTypeCode)signature[0]) : null; return new ILVisualizer.LocalInfo(null, typeName ?? "[unchanged]", false, false); } } private static string GetTypeName(SignatureTypeCode typeCode) { switch (typeCode) { case SignatureTypeCode.Boolean: return "[bool]"; case SignatureTypeCode.Int32: return "[int]"; case SignatureTypeCode.String: return "[string]"; case SignatureTypeCode.Object: return "[object]"; default: return null; } } public void VerifySynthesizedMembers(params string[] expectedSynthesizedTypesAndMemberCounts) { var actual = EmitResult.Baseline.SynthesizedMembers.Select(e => e.Key.ToString() + ": {" + string.Join(", ", e.Value.Select(v => v.Name)) + "}"); AssertEx.SetEqual(expectedSynthesizedTypesAndMemberCounts, actual, itemSeparator: "\r\n"); } public void VerifySynthesizedFields(string typeName, params string[] expectedSynthesizedTypesAndMemberCounts) { var actual = EmitResult.Baseline.SynthesizedMembers.Single(e => e.Key.ToString() == typeName).Value.Where(s => s.Kind == SymbolKind.Field).Select(s => (IFieldSymbol)s.GetISymbol()).Select(f => f.Name + ": " + f.Type); AssertEx.SetEqual(expectedSynthesizedTypesAndMemberCounts, actual, itemSeparator: "\r\n"); } public void VerifyUpdatedMethods(params string[] expectedMethodTokens) { AssertEx.Equal( expectedMethodTokens, EmitResult.UpdatedMethods.Select(methodHandle => $"0x{MetadataTokens.GetToken(methodHandle):X8}")); } } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.DiaSymReader.Tools; using Microsoft.Metadata.Tools; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class CompilationDifference { public readonly ImmutableArray<byte> MetadataDelta; public readonly ImmutableArray<byte> ILDelta; public readonly ImmutableArray<byte> PdbDelta; internal readonly CompilationTestData TestData; public readonly EmitDifferenceResult EmitResult; internal CompilationDifference( ImmutableArray<byte> metadata, ImmutableArray<byte> il, ImmutableArray<byte> pdb, CompilationTestData testData, EmitDifferenceResult result) { MetadataDelta = metadata; ILDelta = il; PdbDelta = pdb; TestData = testData; EmitResult = result; } public EmitBaseline NextGeneration { get { return EmitResult.Baseline; } } internal PinnedMetadata GetMetadata() { return new PinnedMetadata(MetadataDelta); } public void VerifyIL( string expectedIL, [CallerLineNumber] int callerLine = 0, [CallerFilePath] string callerPath = null) { string actualIL = ILDelta.GetMethodIL(); AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine); } public void VerifyLocalSignature( string qualifiedMethodName, string expectedSignature, [CallerLineNumber] int callerLine = 0, [CallerFilePath] string callerPath = null) { var ilBuilder = TestData.GetMethodData(qualifiedMethodName).ILBuilder; string actualSignature = ILBuilderVisualizer.LocalSignatureToString(ilBuilder, ToLocalInfo); AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, actualSignature, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine); } internal void VerifyIL( string qualifiedMethodName, string expectedIL, Func<Cci.ILocalDefinition, ILVisualizer.LocalInfo> mapLocal = null, MethodDefinitionHandle methodToken = default, [CallerFilePath] string callerPath = null, [CallerLineNumber] int callerLine = 0) { var ilBuilder = TestData.GetMethodData(qualifiedMethodName).ILBuilder; Dictionary<int, string> sequencePointMarkers = null; if (!methodToken.IsNil) { string actualPdb = PdbToXmlConverter.DeltaPdbToXml(new ImmutableMemoryStream(PdbDelta), new[] { MetadataTokens.GetToken(methodToken) }); sequencePointMarkers = ILValidation.GetSequencePointMarkers(actualPdb); Assert.True(sequencePointMarkers.Count > 0, $"No sequence points found in:{Environment.NewLine}{actualPdb}"); } string actualIL = ILBuilderVisualizer.ILBuilderToString(ilBuilder, mapLocal ?? ToLocalInfo, sequencePointMarkers); AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine); } internal string GetMethodIL(string qualifiedMethodName) { return ILBuilderVisualizer.ILBuilderToString(this.TestData.GetMethodData(qualifiedMethodName).ILBuilder, ToLocalInfo); } private static ILVisualizer.LocalInfo ToLocalInfo(Cci.ILocalDefinition local) { var signature = local.Signature; if (signature == null) { return new ILVisualizer.LocalInfo(local.Name, local.Type, local.IsPinned, local.IsReference); } else { // Decode simple types only. var typeName = (signature.Length == 1) ? GetTypeName((SignatureTypeCode)signature[0]) : null; return new ILVisualizer.LocalInfo(null, typeName ?? "[unchanged]", false, false); } } private static string GetTypeName(SignatureTypeCode typeCode) { switch (typeCode) { case SignatureTypeCode.Boolean: return "[bool]"; case SignatureTypeCode.Int32: return "[int]"; case SignatureTypeCode.String: return "[string]"; case SignatureTypeCode.Object: return "[object]"; default: return null; } } public void VerifySynthesizedMembers(params string[] expectedSynthesizedTypesAndMemberCounts) { var actual = EmitResult.Baseline.SynthesizedMembers.Select(e => e.Key.ToString() + ": {" + string.Join(", ", e.Value.Select(v => v.Name)) + "}"); AssertEx.SetEqual(expectedSynthesizedTypesAndMemberCounts, actual, itemSeparator: ",\r\n", itemInspector: s => $"\"{s}\""); } public void VerifySynthesizedFields(string typeName, params string[] expectedSynthesizedTypesAndMemberCounts) { var actual = EmitResult.Baseline.SynthesizedMembers.Single(e => e.Key.ToString() == typeName).Value.Where(s => s.Kind == SymbolKind.Field).Select(s => (IFieldSymbol)s.GetISymbol()).Select(f => f.Name + ": " + f.Type); AssertEx.SetEqual(expectedSynthesizedTypesAndMemberCounts, actual, itemSeparator: "\r\n"); } public void VerifyUpdatedMethods(params string[] expectedMethodTokens) { AssertEx.Equal( expectedMethodTokens, EmitResult.UpdatedMethods.Select(methodHandle => $"0x{MetadataTokens.GetToken(methodHandle):X8}")); } } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/PEDeltaAssemblyBuilder.vb
' 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. Imports System.Collections.Immutable Imports System.Globalization Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Namespace Microsoft.CodeAnalysis.VisualBasic.Emit Friend NotInheritable Class PEDeltaAssemblyBuilder Inherits PEAssemblyBuilderBase Implements IPEDeltaAssemblyBuilder Private ReadOnly _previousGeneration As EmitBaseline Private ReadOnly _previousDefinitions As VisualBasicDefinitionMap Private ReadOnly _changes As SymbolChanges Private ReadOnly _deepTranslator As VisualBasicSymbolMatcher.DeepTranslator Public Sub New(sourceAssembly As SourceAssemblySymbol, emitOptions As EmitOptions, outputKind As OutputKind, serializationProperties As ModulePropertiesForSerialization, manifestResources As IEnumerable(Of ResourceDescription), previousGeneration As EmitBaseline, edits As IEnumerable(Of SemanticEdit), isAddedSymbol As Func(Of ISymbol, Boolean)) MyBase.New(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, additionalTypes:=ImmutableArray(Of NamedTypeSymbol).Empty) Dim initialBaseline = previousGeneration.InitialBaseline Dim context = New EmitContext(Me, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) ' Hydrate symbols from initial metadata. Once we do so it is important to reuse these symbols across all generations, ' in order for the symbol matcher to be able to use reference equality once it maps symbols to initial metadata. Dim metadataSymbols = GetOrCreateMetadataSymbols(initialBaseline, sourceAssembly.DeclaringCompilation) Dim metadataDecoder = DirectCast(metadataSymbols.MetadataDecoder, MetadataDecoder) Dim metadataAssembly = DirectCast(metadataDecoder.ModuleSymbol.ContainingAssembly, PEAssemblySymbol) Dim matchToMetadata = New VisualBasicSymbolMatcher(initialBaseline.LazyMetadataSymbols.AnonymousTypes, sourceAssembly, context, metadataAssembly) Dim matchToPrevious As VisualBasicSymbolMatcher = Nothing If previousGeneration.Ordinal > 0 Then Dim previousAssembly = DirectCast(previousGeneration.Compilation, VisualBasicCompilation).SourceAssembly Dim previousContext = New EmitContext(DirectCast(previousGeneration.PEModuleBuilder, PEModuleBuilder), Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) matchToPrevious = New VisualBasicSymbolMatcher( previousGeneration.AnonymousTypeMap, sourceAssembly:=sourceAssembly, sourceContext:=context, otherAssembly:=previousAssembly, otherContext:=previousContext, otherSynthesizedMembersOpt:=previousGeneration.SynthesizedMembers) End If _previousDefinitions = New VisualBasicDefinitionMap(edits, metadataDecoder, matchToMetadata, matchToPrevious) _previousGeneration = previousGeneration _changes = New VisualBasicSymbolChanges(_previousDefinitions, edits, isAddedSymbol) ' Workaround for https://github.com/dotnet/roslyn/issues/3192. ' When compiling state machine we stash types of awaiters and state-machine hoisted variables, ' so that next generation can look variables up and reuse their slots if possible. ' ' When we are about to allocate a slot for a lifted variable while compiling the next generation ' we map its type to the previous generation and then check the slot types that we stashed earlier. ' If the variable type matches we reuse it. In order to compare the previous variable type with the current one ' both need to be completely lowered (translated). Standard translation only goes one level deep. ' Generic arguments are not translated until they are needed by metadata writer. ' ' In order to get the fully lowered form we run the type symbols of stashed variables through a deep translator ' that translates the symbol recursively. _deepTranslator = New VisualBasicSymbolMatcher.DeepTranslator(sourceAssembly.GetSpecialType(SpecialType.System_Object)) End Sub Friend Overrides Function EncTranslateLocalVariableType(type As TypeSymbol, diagnostics As DiagnosticBag) As ITypeReference ' Note: The translator is Not aware of synthesized types. If type is a synthesized type it won't get mapped. ' In such case use the type itself. This can only happen for variables storing lambda display classes. Dim visited = DirectCast(_deepTranslator.Visit(type), TypeSymbol) Debug.Assert(visited IsNot Nothing OrElse TypeOf type Is LambdaFrame OrElse TypeOf DirectCast(type, NamedTypeSymbol).ConstructedFrom Is LambdaFrame) Return Translate(If(visited, type), Nothing, diagnostics) End Function Public Overrides ReadOnly Property EncSymbolChanges As SymbolChanges Get Return _changes End Get End Property Public Overrides ReadOnly Property PreviousGeneration As EmitBaseline Get Return _previousGeneration End Get End Property Private Shared Function GetOrCreateMetadataSymbols(initialBaseline As EmitBaseline, compilation As VisualBasicCompilation) As EmitBaseline.MetadataSymbols If initialBaseline.LazyMetadataSymbols IsNot Nothing Then Return initialBaseline.LazyMetadataSymbols End If Dim originalMetadata = initialBaseline.OriginalMetadata ' The purpose of this compilation is to provide PE symbols for original metadata. ' We need to transfer the references from the current source compilation but don't need its syntax trees. Dim metadataCompilation = compilation.RemoveAllSyntaxTrees() Dim assemblyReferenceIdentityMap As ImmutableDictionary(Of AssemblyIdentity, AssemblyIdentity) = Nothing Dim metadataAssembly = metadataCompilation.GetBoundReferenceManager().CreatePEAssemblyForAssemblyMetadata(AssemblyMetadata.Create(originalMetadata), MetadataImportOptions.All, assemblyReferenceIdentityMap) Dim metadataDecoder = New MetadataDecoder(metadataAssembly.PrimaryModule) Dim metadataAnonymousTypes = GetAnonymousTypeMapFromMetadata(originalMetadata.MetadataReader, metadataDecoder) Dim metadataSymbols = New EmitBaseline.MetadataSymbols(metadataAnonymousTypes, metadataDecoder, assemblyReferenceIdentityMap) Return InterlockedOperations.Initialize(initialBaseline.LazyMetadataSymbols, metadataSymbols) End Function ' friend for testing Friend Overloads Shared Function GetAnonymousTypeMapFromMetadata(reader As MetadataReader, metadataDecoder As MetadataDecoder) As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue) ' In general, the anonymous type name Is 'VB$Anonymous' ('Type'|'Delegate') '_' (submission-index '_')? index module-id ' but EnC Is not supported for modules nor submissions. Hence we only look for type names with no module id and no submission index: ' e.g. VB$AnonymousType_123, VB$AnonymousDelegate_123 Dim result = New Dictionary(Of AnonymousTypeKey, AnonymousTypeValue) For Each handle In reader.TypeDefinitions Dim def = reader.GetTypeDefinition(handle) If Not def.Namespace.IsNil Then Continue For End If If Not reader.StringComparer.StartsWith(def.Name, GeneratedNameConstants.AnonymousTypeOrDelegateCommonPrefix) Then Continue For End If Dim metadataName = reader.GetString(def.Name) Dim arity As Short = 0 Dim name = MetadataHelpers.InferTypeArityAndUnmangleMetadataName(metadataName, arity) Dim index As Integer = 0 If TryParseAnonymousTypeTemplateName(GeneratedNameConstants.AnonymousTypeTemplateNamePrefix, name, index) Then Dim type = DirectCast(metadataDecoder.GetTypeOfToken(handle), NamedTypeSymbol) Dim key = GetAnonymousTypeKey(type) Dim value = New AnonymousTypeValue(name, index, type.GetCciAdapter()) result.Add(key, value) ElseIf TryParseAnonymousTypeTemplateName(GeneratedNameConstants.AnonymousDelegateTemplateNamePrefix, name, index) Then Dim type = DirectCast(metadataDecoder.GetTypeOfToken(handle), NamedTypeSymbol) Dim key = GetAnonymousDelegateKey(type) Dim value = New AnonymousTypeValue(name, index, type.GetCciAdapter()) result.Add(key, value) End If Next Return result End Function Friend Shared Function TryParseAnonymousTypeTemplateName(prefix As String, name As String, <Out()> ByRef index As Integer) As Boolean If name.StartsWith(prefix, StringComparison.Ordinal) AndAlso Integer.TryParse(name.Substring(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, index) Then Return True End If index = -1 Return False End Function Private Shared Function GetAnonymousTypeKey(type As NamedTypeSymbol) As AnonymousTypeKey ' The key is the set of properties that correspond to type parameters. ' For each type parameter, get the name of the property of that type. Dim n = type.TypeParameters.Length If n = 0 Then Return New AnonymousTypeKey(ImmutableArray(Of AnonymousTypeKeyField).Empty) End If ' Properties indexed by type parameter ordinal. Dim properties = New AnonymousTypeKeyField(n - 1) {} For Each member In type.GetMembers() If member.Kind <> SymbolKind.Property Then Continue For End If Dim [property] = DirectCast(member, PropertySymbol) Dim propertyType = [property].Type If propertyType.TypeKind = TypeKind.TypeParameter Then Dim typeParameter = DirectCast(propertyType, TypeParameterSymbol) Debug.Assert(TypeSymbol.Equals(DirectCast(typeParameter.ContainingSymbol, TypeSymbol), type, TypeCompareKind.ConsiderEverything)) Dim index = typeParameter.Ordinal Debug.Assert(properties(index).Name Is Nothing) ' ReadOnly anonymous type properties were 'Key' properties. properties(index) = New AnonymousTypeKeyField([property].Name, isKey:=[property].IsReadOnly, ignoreCase:=True) End If Next Debug.Assert(properties.All(Function(f) Not String.IsNullOrEmpty(f.Name))) Return New AnonymousTypeKey(ImmutableArray.Create(properties)) End Function Private Shared Function GetAnonymousDelegateKey(type As NamedTypeSymbol) As AnonymousTypeKey Debug.Assert(type.BaseTypeNoUseSiteDiagnostics.SpecialType = SpecialType.System_MulticastDelegate) ' The key is the set of parameter names to the Invoke method, ' where the parameters are of the type parameters. Dim members = type.GetMembers(WellKnownMemberNames.DelegateInvokeName) Debug.Assert(members.Length = 1 AndAlso members(0).Kind = SymbolKind.Method) Dim method = DirectCast(members(0), MethodSymbol) Debug.Assert(method.Parameters.Length + If(method.IsSub, 0, 1) = type.TypeParameters.Length) Dim parameters = ArrayBuilder(Of AnonymousTypeKeyField).GetInstance() parameters.AddRange(method.Parameters.SelectAsArray(Function(p) New AnonymousTypeKeyField(p.Name, isKey:=p.IsByRef, ignoreCase:=True))) parameters.Add(New AnonymousTypeKeyField(AnonymousTypeDescriptor.GetReturnParameterName(Not method.IsSub), isKey:=False, ignoreCase:=True)) Return New AnonymousTypeKey(parameters.ToImmutableAndFree(), isDelegate:=True) End Function Friend ReadOnly Property PreviousDefinitions As VisualBasicDefinitionMap Get Return _previousDefinitions End Get End Property Friend Overrides ReadOnly Property SupportsPrivateImplClass As Boolean Get ' Disable <PrivateImplementationDetails> in ENC since the ' CLR does Not support adding non-private members. Return False End Get End Property Friend Overloads Function GetAnonymousTypeMap() As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue) Implements IPEDeltaAssemblyBuilder.GetAnonymousTypeMap Dim anonymousTypes = Compilation.AnonymousTypeManager.GetAnonymousTypeMap() ' Should contain all entries in previous generation. Debug.Assert(_previousGeneration.AnonymousTypeMap.All(Function(p) anonymousTypes.ContainsKey(p.Key))) Return anonymousTypes End Function Friend Overrides Function TryCreateVariableSlotAllocator(method As MethodSymbol, topLevelMethod As MethodSymbol, diagnostics As DiagnosticBag) As VariableSlotAllocator Return _previousDefinitions.TryCreateVariableSlotAllocator(_previousGeneration, Compilation, method, topLevelMethod, diagnostics) End Function Friend Overrides Function GetPreviousAnonymousTypes() As ImmutableArray(Of AnonymousTypeKey) Return ImmutableArray.CreateRange(_previousGeneration.AnonymousTypeMap.Keys) End Function Friend Overrides Function GetNextAnonymousTypeIndex(fromDelegates As Boolean) As Integer Return _previousGeneration.GetNextAnonymousTypeIndex(fromDelegates) End Function Friend Overrides Function TryGetAnonymousTypeName(template As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean Debug.Assert(Compilation Is template.DeclaringCompilation) Return _previousDefinitions.TryGetAnonymousTypeName(template, name, index) End Function Public Overrides Iterator Function GetTopLevelTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) For Each typeDef In GetAnonymousTypeDefinitions(context) Yield typeDef Next For Each typeDef In GetTopLevelTypeDefinitionsCore(context) Yield typeDef Next End Function Public Overrides Function GetTopLevelSourceTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) Return _changes.GetTopLevelSourceTypeDefinitions(context) End Function Friend Sub OnCreatedIndices(diagnostics As DiagnosticBag) Implements IPEDeltaAssemblyBuilder.OnCreatedIndices Dim embeddedTypesManager = Me.EmbeddedTypesManagerOpt If embeddedTypesManager IsNot Nothing Then For Each embeddedType In embeddedTypesManager.EmbeddedTypesMap.Keys diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_EncNoPIAReference, embeddedType.AdaptedNamedTypeSymbol), Location.None) Next End If End Sub Friend Overrides ReadOnly Property AllowOmissionOfConditionalCalls As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property LinkedAssembliesDebugInfo As IEnumerable(Of String) Get ' This debug information is only emitted for the benefit of legacy EE. ' Since EnC requires Roslyn and Roslyn doesn't need this information we don't emit it during EnC. Return SpecializedCollections.EmptyEnumerable(Of String)() End Get End Property End Class End Namespace
' 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. Imports System.Collections.Immutable Imports System.Globalization Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Namespace Microsoft.CodeAnalysis.VisualBasic.Emit Friend NotInheritable Class PEDeltaAssemblyBuilder Inherits PEAssemblyBuilderBase Implements IPEDeltaAssemblyBuilder Private ReadOnly _previousGeneration As EmitBaseline Private ReadOnly _previousDefinitions As VisualBasicDefinitionMap Private ReadOnly _changes As SymbolChanges Private ReadOnly _deepTranslator As VisualBasicSymbolMatcher.DeepTranslator Public Sub New(sourceAssembly As SourceAssemblySymbol, emitOptions As EmitOptions, outputKind As OutputKind, serializationProperties As ModulePropertiesForSerialization, manifestResources As IEnumerable(Of ResourceDescription), previousGeneration As EmitBaseline, edits As IEnumerable(Of SemanticEdit), isAddedSymbol As Func(Of ISymbol, Boolean)) MyBase.New(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, additionalTypes:=ImmutableArray(Of NamedTypeSymbol).Empty) Dim initialBaseline = previousGeneration.InitialBaseline Dim context = New EmitContext(Me, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) ' Hydrate symbols from initial metadata. Once we do so it is important to reuse these symbols across all generations, ' in order for the symbol matcher to be able to use reference equality once it maps symbols to initial metadata. Dim metadataSymbols = GetOrCreateMetadataSymbols(initialBaseline, sourceAssembly.DeclaringCompilation) Dim metadataDecoder = DirectCast(metadataSymbols.MetadataDecoder, MetadataDecoder) Dim metadataAssembly = DirectCast(metadataDecoder.ModuleSymbol.ContainingAssembly, PEAssemblySymbol) Dim matchToMetadata = New VisualBasicSymbolMatcher(initialBaseline.LazyMetadataSymbols.AnonymousTypes, sourceAssembly, context, metadataAssembly) Dim matchToPrevious As VisualBasicSymbolMatcher = Nothing If previousGeneration.Ordinal > 0 Then Dim previousAssembly = DirectCast(previousGeneration.Compilation, VisualBasicCompilation).SourceAssembly Dim previousContext = New EmitContext(DirectCast(previousGeneration.PEModuleBuilder, PEModuleBuilder), Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) matchToPrevious = New VisualBasicSymbolMatcher( previousGeneration.AnonymousTypeMap, sourceAssembly:=sourceAssembly, sourceContext:=context, otherAssembly:=previousAssembly, otherContext:=previousContext, otherSynthesizedMembersOpt:=previousGeneration.SynthesizedMembers) End If _previousDefinitions = New VisualBasicDefinitionMap(edits, metadataDecoder, matchToMetadata, matchToPrevious) _previousGeneration = previousGeneration _changes = New VisualBasicSymbolChanges(_previousDefinitions, edits, isAddedSymbol) ' Workaround for https://github.com/dotnet/roslyn/issues/3192. ' When compiling state machine we stash types of awaiters and state-machine hoisted variables, ' so that next generation can look variables up and reuse their slots if possible. ' ' When we are about to allocate a slot for a lifted variable while compiling the next generation ' we map its type to the previous generation and then check the slot types that we stashed earlier. ' If the variable type matches we reuse it. In order to compare the previous variable type with the current one ' both need to be completely lowered (translated). Standard translation only goes one level deep. ' Generic arguments are not translated until they are needed by metadata writer. ' ' In order to get the fully lowered form we run the type symbols of stashed variables through a deep translator ' that translates the symbol recursively. _deepTranslator = New VisualBasicSymbolMatcher.DeepTranslator(sourceAssembly.GetSpecialType(SpecialType.System_Object)) End Sub Friend Overrides Function EncTranslateLocalVariableType(type As TypeSymbol, diagnostics As DiagnosticBag) As ITypeReference ' Note: The translator is Not aware of synthesized types. If type is a synthesized type it won't get mapped. ' In such case use the type itself. This can only happen for variables storing lambda display classes. Dim visited = DirectCast(_deepTranslator.Visit(type), TypeSymbol) Debug.Assert(visited IsNot Nothing OrElse TypeOf type Is LambdaFrame OrElse TypeOf DirectCast(type, NamedTypeSymbol).ConstructedFrom Is LambdaFrame) Return Translate(If(visited, type), Nothing, diagnostics) End Function Public Overrides ReadOnly Property EncSymbolChanges As SymbolChanges Get Return _changes End Get End Property Public Overrides ReadOnly Property PreviousGeneration As EmitBaseline Get Return _previousGeneration End Get End Property Private Shared Function GetOrCreateMetadataSymbols(initialBaseline As EmitBaseline, compilation As VisualBasicCompilation) As EmitBaseline.MetadataSymbols If initialBaseline.LazyMetadataSymbols IsNot Nothing Then Return initialBaseline.LazyMetadataSymbols End If Dim originalMetadata = initialBaseline.OriginalMetadata ' The purpose of this compilation is to provide PE symbols for original metadata. ' We need to transfer the references from the current source compilation but don't need its syntax trees. Dim metadataCompilation = compilation.RemoveAllSyntaxTrees() Dim assemblyReferenceIdentityMap As ImmutableDictionary(Of AssemblyIdentity, AssemblyIdentity) = Nothing Dim metadataAssembly = metadataCompilation.GetBoundReferenceManager().CreatePEAssemblyForAssemblyMetadata(AssemblyMetadata.Create(originalMetadata), MetadataImportOptions.All, assemblyReferenceIdentityMap) Dim metadataDecoder = New MetadataDecoder(metadataAssembly.PrimaryModule) Dim metadataAnonymousTypes = GetAnonymousTypeMapFromMetadata(originalMetadata.MetadataReader, metadataDecoder) ' VB synthesized delegates are handled as anonymous types in the map above Dim synthesizedDelegates = SpecializedCollections.EmptyReadOnlyDictionary(Of SynthesizedDelegateKey, SynthesizedDelegateValue) Dim metadataSymbols = New EmitBaseline.MetadataSymbols(metadataAnonymousTypes, synthesizedDelegates, metadataDecoder, assemblyReferenceIdentityMap) Return InterlockedOperations.Initialize(initialBaseline.LazyMetadataSymbols, metadataSymbols) End Function ' friend for testing Friend Overloads Shared Function GetAnonymousTypeMapFromMetadata(reader As MetadataReader, metadataDecoder As MetadataDecoder) As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue) ' In general, the anonymous type name Is 'VB$Anonymous' ('Type'|'Delegate') '_' (submission-index '_')? index module-id ' but EnC Is not supported for modules nor submissions. Hence we only look for type names with no module id and no submission index: ' e.g. VB$AnonymousType_123, VB$AnonymousDelegate_123 Dim result = New Dictionary(Of AnonymousTypeKey, AnonymousTypeValue) For Each handle In reader.TypeDefinitions Dim def = reader.GetTypeDefinition(handle) If Not def.Namespace.IsNil Then Continue For End If If Not reader.StringComparer.StartsWith(def.Name, GeneratedNameConstants.AnonymousTypeOrDelegateCommonPrefix) Then Continue For End If Dim metadataName = reader.GetString(def.Name) Dim arity As Short = 0 Dim name = MetadataHelpers.InferTypeArityAndUnmangleMetadataName(metadataName, arity) Dim index As Integer = 0 If TryParseAnonymousTypeTemplateName(GeneratedNameConstants.AnonymousTypeTemplateNamePrefix, name, index) Then Dim type = DirectCast(metadataDecoder.GetTypeOfToken(handle), NamedTypeSymbol) Dim key = GetAnonymousTypeKey(type) Dim value = New AnonymousTypeValue(name, index, type.GetCciAdapter()) result.Add(key, value) ElseIf TryParseAnonymousTypeTemplateName(GeneratedNameConstants.AnonymousDelegateTemplateNamePrefix, name, index) Then Dim type = DirectCast(metadataDecoder.GetTypeOfToken(handle), NamedTypeSymbol) Dim key = GetAnonymousDelegateKey(type) Dim value = New AnonymousTypeValue(name, index, type.GetCciAdapter()) result.Add(key, value) End If Next Return result End Function Friend Shared Function TryParseAnonymousTypeTemplateName(prefix As String, name As String, <Out()> ByRef index As Integer) As Boolean If name.StartsWith(prefix, StringComparison.Ordinal) AndAlso Integer.TryParse(name.Substring(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, index) Then Return True End If index = -1 Return False End Function Private Shared Function GetAnonymousTypeKey(type As NamedTypeSymbol) As AnonymousTypeKey ' The key is the set of properties that correspond to type parameters. ' For each type parameter, get the name of the property of that type. Dim n = type.TypeParameters.Length If n = 0 Then Return New AnonymousTypeKey(ImmutableArray(Of AnonymousTypeKeyField).Empty) End If ' Properties indexed by type parameter ordinal. Dim properties = New AnonymousTypeKeyField(n - 1) {} For Each member In type.GetMembers() If member.Kind <> SymbolKind.Property Then Continue For End If Dim [property] = DirectCast(member, PropertySymbol) Dim propertyType = [property].Type If propertyType.TypeKind = TypeKind.TypeParameter Then Dim typeParameter = DirectCast(propertyType, TypeParameterSymbol) Debug.Assert(TypeSymbol.Equals(DirectCast(typeParameter.ContainingSymbol, TypeSymbol), type, TypeCompareKind.ConsiderEverything)) Dim index = typeParameter.Ordinal Debug.Assert(properties(index).Name Is Nothing) ' ReadOnly anonymous type properties were 'Key' properties. properties(index) = New AnonymousTypeKeyField([property].Name, isKey:=[property].IsReadOnly, ignoreCase:=True) End If Next Debug.Assert(properties.All(Function(f) Not String.IsNullOrEmpty(f.Name))) Return New AnonymousTypeKey(ImmutableArray.Create(properties)) End Function Private Shared Function GetAnonymousDelegateKey(type As NamedTypeSymbol) As AnonymousTypeKey Debug.Assert(type.BaseTypeNoUseSiteDiagnostics.SpecialType = SpecialType.System_MulticastDelegate) ' The key is the set of parameter names to the Invoke method, ' where the parameters are of the type parameters. Dim members = type.GetMembers(WellKnownMemberNames.DelegateInvokeName) Debug.Assert(members.Length = 1 AndAlso members(0).Kind = SymbolKind.Method) Dim method = DirectCast(members(0), MethodSymbol) Debug.Assert(method.Parameters.Length + If(method.IsSub, 0, 1) = type.TypeParameters.Length) Dim parameters = ArrayBuilder(Of AnonymousTypeKeyField).GetInstance() parameters.AddRange(method.Parameters.SelectAsArray(Function(p) New AnonymousTypeKeyField(p.Name, isKey:=p.IsByRef, ignoreCase:=True))) parameters.Add(New AnonymousTypeKeyField(AnonymousTypeDescriptor.GetReturnParameterName(Not method.IsSub), isKey:=False, ignoreCase:=True)) Return New AnonymousTypeKey(parameters.ToImmutableAndFree(), isDelegate:=True) End Function Friend ReadOnly Property PreviousDefinitions As VisualBasicDefinitionMap Get Return _previousDefinitions End Get End Property Friend Overrides ReadOnly Property SupportsPrivateImplClass As Boolean Get ' Disable <PrivateImplementationDetails> in ENC since the ' CLR does Not support adding non-private members. Return False End Get End Property Friend Overloads Function GetAnonymousTypeMap() As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue) Implements IPEDeltaAssemblyBuilder.GetAnonymousTypeMap Dim anonymousTypes = Compilation.AnonymousTypeManager.GetAnonymousTypeMap() ' Should contain all entries in previous generation. Debug.Assert(_previousGeneration.AnonymousTypeMap.All(Function(p) anonymousTypes.ContainsKey(p.Key))) Return anonymousTypes End Function Friend Overloads Function GetSynthesizedDelegates() As IReadOnlyDictionary(Of SynthesizedDelegateKey, SynthesizedDelegateValue) Implements IPEDeltaAssemblyBuilder.GetSynthesizedDelegates ' VB synthesized delegates are handled as anonymous types in the method above Return SpecializedCollections.EmptyReadOnlyDictionary(Of SynthesizedDelegateKey, SynthesizedDelegateValue) End Function Friend Overrides Function TryCreateVariableSlotAllocator(method As MethodSymbol, topLevelMethod As MethodSymbol, diagnostics As DiagnosticBag) As VariableSlotAllocator Return _previousDefinitions.TryCreateVariableSlotAllocator(_previousGeneration, Compilation, method, topLevelMethod, diagnostics) End Function Friend Overrides Function GetPreviousAnonymousTypes() As ImmutableArray(Of AnonymousTypeKey) Return ImmutableArray.CreateRange(_previousGeneration.AnonymousTypeMap.Keys) End Function Friend Overrides Function GetNextAnonymousTypeIndex(fromDelegates As Boolean) As Integer Return _previousGeneration.GetNextAnonymousTypeIndex(fromDelegates) End Function Friend Overrides Function TryGetAnonymousTypeName(template As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean Debug.Assert(Compilation Is template.DeclaringCompilation) Return _previousDefinitions.TryGetAnonymousTypeName(template, name, index) End Function Public Overrides Iterator Function GetTopLevelTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) For Each typeDef In GetAnonymousTypeDefinitions(context) Yield typeDef Next For Each typeDef In GetTopLevelTypeDefinitionsCore(context) Yield typeDef Next End Function Public Overrides Function GetTopLevelSourceTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) Return _changes.GetTopLevelSourceTypeDefinitions(context) End Function Friend Sub OnCreatedIndices(diagnostics As DiagnosticBag) Implements IPEDeltaAssemblyBuilder.OnCreatedIndices Dim embeddedTypesManager = Me.EmbeddedTypesManagerOpt If embeddedTypesManager IsNot Nothing Then For Each embeddedType In embeddedTypesManager.EmbeddedTypesMap.Keys diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_EncNoPIAReference, embeddedType.AdaptedNamedTypeSymbol), Location.None) Next End If End Sub Friend Overrides ReadOnly Property AllowOmissionOfConditionalCalls As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property LinkedAssembliesDebugInfo As IEnumerable(Of String) Get ' This debug information is only emitted for the benefit of legacy EE. ' Since EnC requires Roslyn and Roslyn doesn't need this information we don't emit it during EnC. Return SpecializedCollections.EmptyEnumerable(Of String)() End Get End Property End Class End Namespace
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/CSharpTest/EditAndContinue/StatementEditingTests.cs
// 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. #nullable disable using System.IO; using System.Linq; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EditAndContinue; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class StatementEditingTests : EditingTestBase { #region Strings [Fact] public void StringLiteral_update() { var src1 = @" var x = ""Hello1""; "; var src2 = @" var x = ""Hello2""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = \"Hello1\"]@8 -> [x = \"Hello2\"]@8"); } [Fact] public void InterpolatedStringText_update() { var src1 = @" var x = $""Hello1""; "; var src2 = @" var x = $""Hello2""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello1\"]@8 -> [x = $\"Hello2\"]@8"); } [Fact] public void Interpolation_update() { var src1 = @" var x = $""Hello{123}""; "; var src2 = @" var x = $""Hello{124}""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello{123}\"]@8 -> [x = $\"Hello{124}\"]@8"); } [Fact] public void InterpolationFormatClause_update() { var src1 = @" var x = $""Hello{123:N1}""; "; var src2 = @" var x = $""Hello{123:N2}""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello{123:N1}\"]@8 -> [x = $\"Hello{123:N2}\"]@8"); } #endregion #region Variable Declaration [Fact] public void VariableDeclaration_Insert() { var src1 = "if (x == 1) { x++; }"; var src2 = "var x = 1; if (x == 1) { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [var x = 1;]@2", "Insert [var x = 1]@2", "Insert [x = 1]@6"); } [Fact] public void VariableDeclaration_Update() { var src1 = "int x = F(1), y = G(2);"; var src2 = "int x = F(3), y = G(4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x = F(1)]@6 -> [x = F(3)]@6", "Update [y = G(2)]@16 -> [y = G(4)]@16"); } [Fact] public void ParenthesizedVariableDeclaration_Update() { var src1 = @" var (x1, (x2, x3)) = (1, (2, true)); var (a1, a2) = (1, () => { return 7; }); "; var src2 = @" var (x1, (x2, x4)) = (1, (2, true)); var (a1, a3) = (1, () => { return 8; }); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x3]@18 -> [x4]@18", "Update [a2]@51 -> [a3]@51"); } [Fact] public void ParenthesizedVariableDeclaration_Insert() { var src1 = @"var (z1, z2) = (1, 2);"; var src2 = @"var (z1, z2, z3) = (1, 2, 5);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (z1, z2) = (1, 2);]@2 -> [var (z1, z2, z3) = (1, 2, 5);]@2", "Insert [z3]@15"); } [Fact] public void ParenthesizedVariableDeclaration_Delete() { var src1 = @"var (y1, y2, y3) = (1, 2, 7);"; var src2 = @"var (y1, y2) = (1, 4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (y1, y2, y3) = (1, 2, 7);]@2 -> [var (y1, y2) = (1, 4);]@2", "Delete [y3]@15"); } [Fact] public void ParenthesizedVariableDeclaration_Insert_Mixed1() { var src1 = @"int a; (var z1, a) = (1, 2);"; var src2 = @"int a; (var z1, a, var z3) = (1, 2, 5);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var z1, a) = (1, 2);]@9 -> [(var z1, a, var z3) = (1, 2, 5);]@9", "Insert [z3]@25"); } [Fact] public void ParenthesizedVariableDeclaration_Insert_Mixed2() { var src1 = @"int a; (var z1, var z2) = (1, 2);"; var src2 = @"int a; (var z1, var z2, a) = (1, 2, 5);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var z1, var z2) = (1, 2);]@9 -> [(var z1, var z2, a) = (1, 2, 5);]@9"); } [Fact] public void ParenthesizedVariableDeclaration_Delete_Mixed1() { var src1 = @"int a; (var y1, var y2, a) = (1, 2, 7);"; var src2 = @"int a; (var y1, var y2) = (1, 4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var y1, var y2, a) = (1, 2, 7);]@9 -> [(var y1, var y2) = (1, 4);]@9"); } [Fact] public void ParenthesizedVariableDeclaration_Delete_Mixed2() { var src1 = @"int a; (var y1, a, var y3) = (1, 2, 7);"; var src2 = @"int a; (var y1, a) = (1, 4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var y1, a, var y3) = (1, 2, 7);]@9 -> [(var y1, a) = (1, 4);]@9", "Delete [y3]@25"); } [Fact] public void VariableDeclaraions_Reorder() { var src1 = @"var (a, b) = (1, 2); var (c, d) = (3, 4);"; var src2 = @"var (c, d) = (3, 4); var (a, b) = (1, 2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [var (c, d) = (3, 4);]@23 -> @2"); } [Fact] public void VariableDeclaraions_Reorder_Mixed() { var src1 = @"int a; (a, int b) = (1, 2); (int c, int d) = (3, 4);"; var src2 = @"int a; (int c, int d) = (3, 4); (a, int b) = (1, 2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [(int c, int d) = (3, 4);]@30 -> @9"); } [Fact] public void VariableNames_Reorder() { var src1 = @"var (a, b) = (1, 2);"; var src2 = @"var (b, a) = (2, 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (a, b) = (1, 2);]@2 -> [var (b, a) = (2, 1);]@2", "Reorder [b]@10 -> @7"); } [Fact] public void VariableNames_Reorder_Mixed() { var src1 = @"int a; (a, int b) = (1, 2);"; var src2 = @"int a; (int b, a) = (2, 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(a, int b) = (1, 2);]@9 -> [(int b, a) = (2, 1);]@9"); } [Fact] public void VariableNamesAndDeclaraions_Reorder() { var src1 = @"var (a, b) = (1, 2); var (c, d) = (3, 4);"; var src2 = @"var (d, c) = (3, 4); var (a, b) = (1, 2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [var (c, d) = (3, 4);]@23 -> @2", "Reorder [d]@31 -> @7"); } [Fact] public void ParenthesizedVariableDeclaration_Reorder() { var src1 = @"var (a, (b, c)) = (1, (2, 3));"; var src2 = @"var ((b, c), a) = ((2, 3), 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((b, c), a) = ((2, 3), 1);]@2", "Reorder [a]@7 -> @15"); } [Fact] public void ParenthesizedVariableDeclaration_DoubleReorder() { var src1 = @"var (a, (b, c)) = (1, (2, 3));"; var src2 = @"var ((c, b), a) = ((2, 3), 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((c, b), a) = ((2, 3), 1);]@2", "Reorder [b]@11 -> @11", "Reorder [c]@14 -> @8"); } [Fact] public void ParenthesizedVariableDeclaration_ComplexReorder() { var src1 = @"var (a, (b, c)) = (1, (2, 3)); var (x, (y, z)) = (4, (5, 6));"; var src2 = @"var (x, (y, z)) = (4, (5, 6)); var ((c, b), a) = (1, (2, 3)); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [var (x, (y, z)) = (4, (5, 6));]@33 -> @2", "Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((c, b), a) = (1, (2, 3));]@33", "Reorder [b]@11 -> @42", "Reorder [c]@14 -> @39"); } #endregion #region Switch Statement [Fact] public void Switch1() { var src1 = "switch (a) { case 1: f(); break; } switch (b) { case 2: g(); break; }"; var src2 = "switch (b) { case 2: f(); break; } switch (a) { case 1: g(); break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [switch (b) { case 2: g(); break; }]@37 -> @2", "Update [case 1: f(); break;]@15 -> [case 2: f(); break;]@15", "Move [case 1: f(); break;]@15 -> @15", "Update [case 2: g(); break;]@50 -> [case 1: g(); break;]@50", "Move [case 2: g(); break;]@50 -> @50"); } [Fact] public void Switch_Case_Reorder() { var src1 = "switch (expr) { case 1: f(); break; case 2: case 3: case 4: g(); break; }"; var src2 = "switch (expr) { case 2: case 3: case 4: g(); break; case 1: f(); break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [case 2: case 3: case 4: g(); break;]@40 -> @18"); } [Fact] public void Switch_Case_Update() { var src1 = "switch (expr) { case 1: f(); break; }"; var src2 = "switch (expr) { case 2: f(); break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: f(); break;]@18 -> [case 2: f(); break;]@18"); } [Fact] public void CasePatternLabel_UpdateDelete() { var src1 = @" switch(shape) { case Point p: return 0; case Circle c: return 1; } "; var src2 = @" switch(shape) { case Circle circle: return 1; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c: return 1;]@55 -> [case Circle circle: return 1;]@26", "Update [c]@67 -> [circle]@38", "Delete [case Point p: return 0;]@26", "Delete [case Point p:]@26", "Delete [p]@37", "Delete [return 0;]@40"); } #endregion #region Switch Expression [Fact] public void MethodUpdate_UpdateSwitchExpression1() { var src1 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 1 }; }"; var src2 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 2 }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, _ => 2 };]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateSwitchExpression2() { var src1 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 1 }; }"; var src2 = @" class C { static int F(int a) => a switch { 1 => 0, _ => 2 }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 1 => 0, _ => 2 };]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateSwitchExpression3() { var src1 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 1 }; }"; var src2 = @" class C { static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 };]@18"); edits.VerifyRudeDiagnostics(); } #endregion #region Try Catch Finally [Fact] public void TryInsert1() { var src1 = "x++;"; var src2 = "try { x++; } catch { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { x++; } catch { }]@2", "Insert [{ x++; }]@6", "Insert [catch { }]@15", "Move [x++;]@2 -> @8", "Insert [{ }]@21"); } [Fact] public void TryInsert2() { var src1 = "{ x++; }"; var src2 = "try { x++; } catch { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { x++; } catch { }]@2", "Move [{ x++; }]@2 -> @6", "Insert [catch { }]@15", "Insert [{ }]@21"); } [Fact] public void TryDelete1() { var src1 = "try { x++; } catch { }"; var src2 = "x++;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [x++;]@8 -> @2", "Delete [try { x++; } catch { }]@2", "Delete [{ x++; }]@6", "Delete [catch { }]@15", "Delete [{ }]@21"); } [Fact] public void TryDelete2() { var src1 = "try { x++; } catch { }"; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ x++; }]@6 -> @2", "Delete [try { x++; } catch { }]@2", "Delete [catch { }]@15", "Delete [{ }]@21"); } [Fact] public void TryReorder() { var src1 = "try { x++; } catch { /*1*/ } try { y++; } catch { /*2*/ }"; var src2 = "try { y++; } catch { /*2*/ } try { x++; } catch { /*1*/ } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [try { y++; } catch { /*2*/ }]@31 -> @2"); } [Fact] public void Finally_DeleteHeader() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } finally { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*3*/ }]@47 -> @39", "Delete [finally { /*3*/ }]@39"); } [Fact] public void Finally_InsertHeader() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [finally { /*3*/ }]@39", "Move [{ /*3*/ }]@39 -> @47"); } [Fact] public void CatchUpdate() { var src1 = "try { } catch (Exception e) { }"; var src2 = "try { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(Exception e)]@16 -> [(IOException e)]@16"); } [Fact] public void CatchInsert() { var src1 = "try { /*1*/ } catch (Exception e) { /*2*/ } "; var src2 = "try { /*1*/ } catch (IOException e) { /*3*/ } catch (Exception e) { /*2*/ } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch (IOException e) { /*3*/ }]@16", "Insert [(IOException e)]@22", "Insert [{ /*3*/ }]@38"); } [Fact] public void CatchBodyUpdate() { var src1 = "try { } catch (E e) { x++; }"; var src2 = "try { } catch (E e) { y++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x++;]@24 -> [y++;]@24"); } [Fact] public void CatchDelete() { var src1 = "try { } catch (IOException e) { } catch (Exception e) { } "; var src2 = "try { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [catch (Exception e) { }]@36", "Delete [(Exception e)]@42", "Delete [{ }]@56"); } [Fact] public void CatchReorder1() { var src1 = "try { } catch (IOException e) { } catch (Exception e) { } "; var src2 = "try { } catch (Exception e) { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [catch (Exception e) { }]@36 -> @10"); } [Fact] public void CatchReorder2() { var src1 = "try { } catch (IOException e) { } catch (Exception e) { } catch { }"; var src2 = "try { } catch (A e) { } catch (Exception e) { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [catch (Exception e) { }]@36 -> @26", "Reorder [catch { }]@60 -> @10", "Insert [(A e)]@16"); } [Fact] public void CatchFilterReorder2() { var src1 = "try { } catch (Exception e) when (e != null) { } catch (Exception e) { } catch { }"; var src2 = "try { } catch when (s == 1) { } catch (Exception e) { } catch (Exception e) when (e != null) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [catch (Exception e) { }]@51 -> @34", "Reorder [catch { }]@75 -> @10", "Insert [when (s == 1)]@16"); } [Fact] public void CatchInsertDelete() { var src1 = @" try { x++; } catch (E e) { /*1*/ } catch (Exception e) { /*2*/ } try { Console.WriteLine(); } finally { /*3*/ }"; var src2 = @" try { x++; } catch (Exception e) { /*2*/ } try { Console.WriteLine(); } catch (E e) { /*1*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch (E e) { /*1*/ }]@79", "Insert [(E e)]@85", "Move [{ /*1*/ }]@29 -> @91", "Delete [catch (E e) { /*1*/ }]@17", "Delete [(E e)]@23"); } [Fact] public void Catch_DeleteHeader1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch (E2 e) { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*3*/ }]@52 -> @39", "Delete [catch (E2 e) { /*3*/ }]@39", "Delete [(E2 e)]@45"); } [Fact] public void Catch_InsertHeader1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch (E2 e) { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch (E2 e) { /*3*/ }]@39", "Insert [(E2 e)]@45", "Move [{ /*3*/ }]@39 -> @52"); } [Fact] public void Catch_DeleteHeader2() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*3*/ }]@45 -> @39", "Delete [catch { /*3*/ }]@39"); } [Fact] public void Catch_InsertHeader2() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch { /*3*/ }]@39", "Move [{ /*3*/ }]@39 -> @45"); } [Fact] public void Catch_InsertFilter1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [when (e == null)]@29"); } [Fact] public void Catch_InsertFilter2() { var src1 = "try { /*1*/ } catch when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [(E1 e)]@22"); } [Fact] public void Catch_InsertFilter3() { var src1 = "try { /*1*/ } catch { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [(E1 e)]@22", "Insert [when (e == null)]@29"); } [Fact] public void Catch_DeleteDeclaration1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ }"; var src2 = "try { /*1*/ } catch { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [(E1 e)]@22"); } [Fact] public void Catch_DeleteFilter1() { var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [when (e == null)]@29"); } [Fact] public void Catch_DeleteFilter2() { var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [(E1 e)]@22"); } [Fact] public void Catch_DeleteFilter3() { var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [(E1 e)]@22", "Delete [when (e == null)]@29"); } [Fact] public void TryCatchFinally_DeleteHeader() { var src1 = "try { /*1*/ } catch { /*2*/ } finally { /*3*/ }"; var src2 = "{ /*1*/ } { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*1*/ }]@6 -> @2", "Move [{ /*2*/ }]@22 -> @12", "Move [{ /*3*/ }]@40 -> @22", "Delete [try { /*1*/ } catch { /*2*/ } finally { /*3*/ }]@2", "Delete [catch { /*2*/ }]@16", "Delete [finally { /*3*/ }]@32"); } [Fact] public void TryCatchFinally_InsertHeader() { var src1 = "{ /*1*/ } { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch { /*2*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { /*1*/ } catch { /*2*/ } finally { /*3*/ }]@2", "Move [{ /*1*/ }]@2 -> @6", "Insert [catch { /*2*/ }]@16", "Insert [finally { /*3*/ }]@32", "Move [{ /*2*/ }]@12 -> @22", "Move [{ /*3*/ }]@22 -> @40"); } [Fact] public void TryFilterFinally_InsertHeader() { var src1 = "{ /*1*/ } if (a == 1) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch when (a == 1) { /*2*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { /*1*/ } catch when (a == 1) { /*2*/ } finally { /*3*/ }]@2", "Move [{ /*1*/ }]@2 -> @6", "Insert [catch when (a == 1) { /*2*/ }]@16", "Insert [finally { /*3*/ }]@46", "Insert [when (a == 1)]@22", "Move [{ /*2*/ }]@24 -> @36", "Move [{ /*3*/ }]@34 -> @54", "Delete [if (a == 1) { /*2*/ }]@12"); } #endregion #region Blocks [Fact] public void Block_Insert() { var src1 = ""; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [{ x++; }]@2", "Insert [x++;]@4"); } [Fact] public void Block_Delete() { var src1 = "{ x++; }"; var src2 = ""; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [{ x++; }]@2", "Delete [x++;]@4"); } [Fact] public void Block_Reorder() { var src1 = "{ x++; } { y++; }"; var src2 = "{ y++; } { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [{ y++; }]@11 -> @2"); } [Fact] public void Block_AddLine() { var src1 = "{ x++; }"; var src2 = @"{ // x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(); } #endregion #region Checked/Unchecked [Fact] public void Checked_Insert() { var src1 = ""; var src2 = "checked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [checked { x++; }]@2", "Insert [{ x++; }]@10", "Insert [x++;]@12"); } [Fact] public void Checked_Delete() { var src1 = "checked { x++; }"; var src2 = ""; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [checked { x++; }]@2", "Delete [{ x++; }]@10", "Delete [x++;]@12"); } [Fact] public void Checked_Update() { var src1 = "checked { x++; }"; var src2 = "unchecked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [checked { x++; }]@2 -> [unchecked { x++; }]@2"); } [Fact] public void Checked_DeleteHeader() { var src1 = "checked { x++; }"; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ x++; }]@10 -> @2", "Delete [checked { x++; }]@2"); } [Fact] public void Checked_InsertHeader() { var src1 = "{ x++; }"; var src2 = "checked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [checked { x++; }]@2", "Move [{ x++; }]@2 -> @10"); } [Fact] public void Unchecked_InsertHeader() { var src1 = "{ x++; }"; var src2 = "unchecked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [unchecked { x++; }]@2", "Move [{ x++; }]@2 -> @12"); } #endregion #region Unsafe [Fact] public void Unsafe_Insert() { var src1 = ""; var src2 = "unsafe { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [unsafe { x++; }]@2", "Insert [{ x++; }]@9", "Insert [x++;]@11"); } [Fact] public void Unsafe_Delete() { var src1 = "unsafe { x++; }"; var src2 = ""; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [unsafe { x++; }]@2", "Delete [{ x++; }]@9", "Delete [x++;]@11"); } [Fact] public void Unsafe_DeleteHeader() { var src1 = "unsafe { x++; }"; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ x++; }]@9 -> @2", "Delete [unsafe { x++; }]@2"); } [Fact] public void Unsafe_InsertHeader() { var src1 = "{ x++; }"; var src2 = "unsafe { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [unsafe { x++; }]@2", "Move [{ x++; }]@2 -> @9"); } #endregion #region Using Statement [Fact] public void Using1() { var src1 = @"using (a) { using (b) { Goo(); } }"; var src2 = @"using (a) { using (c) { using (b) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [using (c) { using (b) { Goo(); } }]@14", "Insert [{ using (b) { Goo(); } }]@24", "Move [using (b) { Goo(); }]@14 -> @26"); } [Fact] public void Using_DeleteHeader() { var src1 = @"using (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@12 -> @2", "Delete [using (a) { Goo(); }]@2"); } [Fact] public void Using_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"using (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [using (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @12"); } #endregion #region Lock Statement [Fact] public void Lock1() { var src1 = @"lock (a) { lock (b) { Goo(); } }"; var src2 = @"lock (a) { lock (c) { lock (b) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [lock (c) { lock (b) { Goo(); } }]@13", "Insert [{ lock (b) { Goo(); } }]@22", "Move [lock (b) { Goo(); }]@13 -> @24"); } [Fact] public void Lock_DeleteHeader() { var src1 = @"lock (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@11 -> @2", "Delete [lock (a) { Goo(); }]@2"); } [Fact] public void Lock_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"lock (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [lock (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @11"); } #endregion #region ForEach Statement [Fact] public void ForEach1() { var src1 = @"foreach (var a in e) { foreach (var b in f) { Goo(); } }"; var src2 = @"foreach (var a in e) { foreach (var c in g) { foreach (var b in f) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [foreach (var c in g) { foreach (var b in f) { Goo(); } }]@25", "Insert [{ foreach (var b in f) { Goo(); } }]@46", "Move [foreach (var b in f) { Goo(); }]@25 -> @48"); var actual = ToMatchingPairs(edits.Match); var expected = new MatchingPairs { { "foreach (var a in e) { foreach (var b in f) { Goo(); } }", "foreach (var a in e) { foreach (var c in g) { foreach (var b in f) { Goo(); } } }" }, { "{ foreach (var b in f) { Goo(); } }", "{ foreach (var c in g) { foreach (var b in f) { Goo(); } } }" }, { "foreach (var b in f) { Goo(); }", "foreach (var b in f) { Goo(); }" }, { "{ Goo(); }", "{ Goo(); }" }, { "Goo();", "Goo();" } }; expected.AssertEqual(actual); } [Fact] public void ForEach_Swap1() { var src1 = @"foreach (var a in e) { foreach (var b in f) { Goo(); } }"; var src2 = @"foreach (var b in f) { foreach (var a in e) { Goo(); } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [foreach (var b in f) { Goo(); }]@25 -> @2", "Move [foreach (var a in e) { foreach (var b in f) { Goo(); } }]@2 -> @25", "Move [Goo();]@48 -> @48"); var actual = ToMatchingPairs(edits.Match); var expected = new MatchingPairs { { "foreach (var a in e) { foreach (var b in f) { Goo(); } }", "foreach (var a in e) { Goo(); }" }, { "{ foreach (var b in f) { Goo(); } }", "{ Goo(); }" }, { "foreach (var b in f) { Goo(); }", "foreach (var b in f) { foreach (var a in e) { Goo(); } }" }, { "{ Goo(); }", "{ foreach (var a in e) { Goo(); } }" }, { "Goo();", "Goo();" } }; expected.AssertEqual(actual); } [Fact] public void Foreach_DeleteHeader() { var src1 = @"foreach (var a in b) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@23 -> @2", "Delete [foreach (var a in b) { Goo(); }]@2"); } [Fact] public void Foreach_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"foreach (var a in b) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [foreach (var a in b) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @23"); } [Fact] public void ForeachVariable_Update1() { var src1 = @" foreach (var (a1, a2) in e) { } foreach ((var b1, var b2) in e) { } foreach (var a in e1) { } "; var src2 = @" foreach (var (a1, a3) in e) { } foreach ((var b3, int b2) in e) { } foreach (_ in e1) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach ((var b1, var b2) in e) { }]@37 -> [foreach ((var b3, int b2) in e) { }]@37", "Update [foreach (var a in e1) { }]@74 -> [foreach (_ in e1) { }]@74", "Update [a2]@22 -> [a3]@22", "Update [b1]@51 -> [b3]@51"); } [Fact] public void ForeachVariable_Update2() { var src1 = @" foreach (_ in e2) { } foreach (_ in e3) { A(); } "; var src2 = @" foreach (var b in e2) { } foreach (_ in e4) { A(); } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach (_ in e2) { }]@4 -> [foreach (var b in e2) { }]@4", "Update [foreach (_ in e3) { A(); }]@27 -> [foreach (_ in e4) { A(); }]@31"); } [Fact] public void ForeachVariable_Insert() { var src1 = @" foreach (var (a3, a4) in e) { } foreach ((var b4, var b5) in e) { } "; var src2 = @" foreach (var (a3, a5, a4) in e) { } foreach ((var b6, var b4, var b5) in e) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach (var (a3, a4) in e) { }]@4 -> [foreach (var (a3, a5, a4) in e) { }]@4", "Update [foreach ((var b4, var b5) in e) { }]@37 -> [foreach ((var b6, var b4, var b5) in e) { }]@41", "Insert [a5]@22", "Insert [b6]@55"); } [Fact] public void ForeachVariable_Delete() { var src1 = @" foreach (var (a11, a12, a13) in e) { F(); } foreach ((var b7, var b8, var b9) in e) { G(); } "; var src2 = @" foreach (var (a12, a13) in e1) { F(); } foreach ((var b7, var b9) in e) { G(); } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach (var (a11, a12, a13) in e) { F(); }]@4 -> [foreach (var (a12, a13) in e1) { F(); }]@4", "Update [foreach ((var b7, var b8, var b9) in e) { G(); }]@49 -> [foreach ((var b7, var b9) in e) { G(); }]@45", "Delete [a11]@18", "Delete [b8]@71"); } [Fact] public void ForeachVariable_Reorder() { var src1 = @" foreach (var (a, b) in e1) { } foreach ((var x, var y) in e2) { } "; var src2 = @" foreach ((var x, var y) in e2) { } foreach (var (a, b) in e1) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [foreach ((var x, var y) in e2) { }]@36 -> @4"); } [Fact] public void ForeachVariableEmbedded_Reorder() { var src1 = @" foreach (var (a, b) in e1) { foreach ((var x, var y) in e2) { } } "; var src2 = @" foreach ((var x, var y) in e2) { } foreach (var (a, b) in e1) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [foreach ((var x, var y) in e2) { }]@39 -> @4"); } #endregion #region For Statement [Fact] public void For1() { var src1 = @"for (int a = 0; a < 10; a++) { for (int a = 0; a < 20; a++) { Goo(); } }"; var src2 = @"for (int a = 0; a < 10; a++) { for (int b = 0; b < 10; b++) { for (int a = 0; a < 20; a++) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [for (int b = 0; b < 10; b++) { for (int a = 0; a < 20; a++) { Goo(); } }]@33", "Insert [int b = 0]@38", "Insert [b < 10]@49", "Insert [b++]@57", "Insert [{ for (int a = 0; a < 20; a++) { Goo(); } }]@62", "Insert [b = 0]@42", "Move [for (int a = 0; a < 20; a++) { Goo(); }]@33 -> @64"); } [Fact] public void For_DeleteHeader() { var src1 = @"for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@43 -> @2", "Delete [for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }]@2", "Delete [int i = 10, j = 0]@7", "Delete [i = 10]@11", "Delete [j = 0]@19", "Delete [i > j]@26", "Delete [i--]@33", "Delete [j++]@38"); } [Fact] public void For_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }]@2", "Insert [int i = 10, j = 0]@7", "Insert [i > j]@26", "Insert [i--]@33", "Insert [j++]@38", "Move [{ Goo(); }]@2 -> @43", "Insert [i = 10]@11", "Insert [j = 0]@19"); } [Fact] public void For_DeclaratorsToInitializers() { var src1 = @"for (var i = 10; i < 10; i++) { }"; var src2 = @"for (i = 10; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [i = 10]@7", "Delete [var i = 10]@7", "Delete [i = 10]@11"); } [Fact] public void For_InitializersToDeclarators() { var src1 = @"for (i = 10, j = 0; i < 10; i++) { }"; var src2 = @"for (var i = 10, j = 0; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [var i = 10, j = 0]@7", "Insert [i = 10]@11", "Insert [j = 0]@19", "Delete [i = 10]@7", "Delete [j = 0]@15"); } [Fact] public void For_Declarations_Reorder() { var src1 = @"for (var i = 10, j = 0; i > j; i++, j++) { }"; var src2 = @"for (var j = 0, i = 10; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Reorder [j = 0]@19 -> @11"); } [Fact] public void For_Declarations_Insert() { var src1 = @"for (var i = 0, j = 1; i > j; i++, j++) { }"; var src2 = @"for (var i = 0, j = 1, k = 2; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var i = 0, j = 1]@7 -> [var i = 0, j = 1, k = 2]@7", "Insert [k = 2]@25"); } [Fact] public void For_Declarations_Delete() { var src1 = @"for (var i = 0, j = 1, k = 2; i > j; i++, j++) { }"; var src2 = @"for (var i = 0, j = 1; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var i = 0, j = 1, k = 2]@7 -> [var i = 0, j = 1]@7", "Delete [k = 2]@25"); } [Fact] public void For_Initializers_Reorder() { var src1 = @"for (i = 10, j = 0; i > j; i++, j++) { }"; var src2 = @"for (j = 0, i = 10; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Reorder [j = 0]@15 -> @7"); } [Fact] public void For_Initializers_Insert() { var src1 = @"for (i = 10; i < 10; i++) { }"; var src2 = @"for (i = 10, j = 0; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Insert [j = 0]@15"); } [Fact] public void For_Initializers_Delete() { var src1 = @"for (i = 10, j = 0; i < 10; i++) { }"; var src2 = @"for (i = 10; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Delete [j = 0]@15"); } [Fact] public void For_Initializers_Update() { var src1 = @"for (i = 1; i < 10; i++) { }"; var src2 = @"for (i = 2; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [i = 1]@7 -> [i = 2]@7"); } [Fact] public void For_Initializers_Update_Lambda() { var src1 = @"for (int i = 10, j = F(() => 1); i > j; i++) { }"; var src2 = @"for (int i = 10, j = F(() => 2); i > j; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [() => 1]@25 -> [() => 2]@25"); } [Fact] public void For_Condition_Update() { var src1 = @"for (int i = 0; i < 10; i++) { }"; var src2 = @"for (int i = 0; i < 20; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [i < 10]@18 -> [i < 20]@18"); } [Fact] public void For_Condition_Lambda() { var src1 = @"for (int i = 0; F(() => 1); i++) { }"; var src2 = @"for (int i = 0; F(() => 2); i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [() => 1]@20 -> [() => 2]@20"); } [Fact] public void For_Incrementors_Reorder() { var src1 = @"for (int i = 10, j = 0; i > j; i--, j++) { }"; var src2 = @"for (int i = 10, j = 0; i > j; j++, i--) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Reorder [j++]@38 -> @33"); } [Fact] public void For_Incrementors_Insert() { var src1 = @"for (int i = 10, j = 0; i > j; i--) { }"; var src2 = @"for (int i = 10, j = 0; i > j; j++, i--) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Insert [j++]@33"); } [Fact] public void For_Incrementors_Delete() { var src1 = @"for (int i = 10, j = 0; i > j; j++, i--) { }"; var src2 = @"for (int i = 10, j = 0; i > j; j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Delete [i--]@38"); } [Fact] public void For_Incrementors_Update() { var src1 = @"for (int i = 10, j = 0; i > j; j++) { }"; var src2 = @"for (int i = 10, j = 0; i > j; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [j++]@33 -> [i++]@33"); } [Fact] public void For_Incrementors_Update_Lambda() { var src1 = @"for (int i = 10, j = 0; i > j; F(() => 1)) { }"; var src2 = @"for (int i = 10, j = 0; i > j; F(() => 2)) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [() => 1]@35 -> [() => 2]@35"); } #endregion #region While Statement [Fact] public void While1() { var src1 = @"while (a) { while (b) { Goo(); } }"; var src2 = @"while (a) { while (c) { while (b) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [while (c) { while (b) { Goo(); } }]@14", "Insert [{ while (b) { Goo(); } }]@24", "Move [while (b) { Goo(); }]@14 -> @26"); } [Fact] public void While_DeleteHeader() { var src1 = @"while (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@12 -> @2", "Delete [while (a) { Goo(); }]@2"); } [Fact] public void While_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"while (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [while (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @12"); } #endregion #region Do Statement [Fact] public void Do1() { var src1 = @"do { do { Goo(); } while (b); } while (a);"; var src2 = @"do { do { do { Goo(); } while(b); } while(c); } while(a);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [do { do { Goo(); } while(b); } while(c);]@7", "Insert [{ do { Goo(); } while(b); }]@10", "Move [do { Goo(); } while (b);]@7 -> @12"); } [Fact] public void Do_DeleteHeader() { var src1 = @"do { Goo(); } while (a);"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@5 -> @2", "Delete [do { Goo(); } while (a);]@2"); } [Fact] public void Do_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"do { Goo(); } while (a);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [do { Goo(); } while (a);]@2", "Move [{ Goo(); }]@2 -> @5"); } #endregion #region If Statement [Fact] public void IfStatement_TestExpression_Update() { var src1 = "var x = 1; if (x == 1) { x++; }"; var src2 = "var x = 1; if (x == 2) { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (x == 1) { x++; }]@13 -> [if (x == 2) { x++; }]@13"); } [Fact] public void ElseClause_Insert() { var src1 = "if (x == 1) x++; "; var src2 = "if (x == 1) x++; else y++;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [else y++;]@19", "Insert [y++;]@24"); } [Fact] public void ElseClause_InsertMove() { var src1 = "if (x == 1) x++; else y++;"; var src2 = "if (x == 1) x++; else if (x == 2) y++;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (x == 2) y++;]@24", "Move [y++;]@24 -> @36"); } [Fact] public void If1() { var src1 = @"if (a) if (b) Goo();"; var src2 = @"if (a) if (c) if (b) Goo();"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (c) if (b) Goo();]@9", "Move [if (b) Goo();]@9 -> @16"); } [Fact] public void If_DeleteHeader() { var src1 = @"if (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@9 -> @2", "Delete [if (a) { Goo(); }]@2"); } [Fact] public void If_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"if (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @9"); } [Fact] public void Else_DeleteHeader() { var src1 = @"if (a) { Goo(/*1*/); } else { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(/*2*/); }]@30 -> @25", "Delete [else { Goo(/*2*/); }]@25"); } [Fact] public void Else_InsertHeader() { var src1 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } else { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [else { Goo(/*2*/); }]@25", "Move [{ Goo(/*2*/); }]@25 -> @30"); } [Fact] public void ElseIf_DeleteHeader() { var src1 = @"if (a) { Goo(/*1*/); } else if (b) { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(/*2*/); }]@37 -> @25", "Delete [else if (b) { Goo(/*2*/); }]@25", "Delete [if (b) { Goo(/*2*/); }]@30"); } [Fact] public void ElseIf_InsertHeader() { var src1 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } else if (b) { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [else if (b) { Goo(/*2*/); }]@25", "Insert [if (b) { Goo(/*2*/); }]@30", "Move [{ Goo(/*2*/); }]@25 -> @37"); } [Fact] public void IfElseElseIf_InsertHeader() { var src1 = @"{ /*1*/ } { /*2*/ } { /*3*/ }"; var src2 = @"if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }]@2", "Move [{ /*1*/ }]@2 -> @9", "Insert [else if (b) { /*2*/ } else { /*3*/ }]@19", "Insert [if (b) { /*2*/ } else { /*3*/ }]@24", "Move [{ /*2*/ }]@12 -> @31", "Insert [else { /*3*/ }]@41", "Move [{ /*3*/ }]@22 -> @46"); } [Fact] public void IfElseElseIf_DeleteHeader() { var src1 = @"if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }"; var src2 = @"{ /*1*/ } { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*1*/ }]@9 -> @2", "Move [{ /*2*/ }]@31 -> @12", "Move [{ /*3*/ }]@46 -> @22", "Delete [if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }]@2", "Delete [else if (b) { /*2*/ } else { /*3*/ }]@19", "Delete [if (b) { /*2*/ } else { /*3*/ }]@24", "Delete [else { /*3*/ }]@41"); } #endregion #region Switch Statement [Fact] public void SwitchStatement_Update_Expression() { var src1 = "var x = 1; switch (x + 1) { case 1: break; }"; var src2 = "var x = 1; switch (x + 2) { case 1: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [switch (x + 1) { case 1: break; }]@13 -> [switch (x + 2) { case 1: break; }]@13"); } [Fact] public void SwitchStatement_Update_SectionLabel() { var src1 = "var x = 1; switch (x) { case 1: break; }"; var src2 = "var x = 1; switch (x) { case 2: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: break;]@26 -> [case 2: break;]@26"); } [Fact] public void SwitchStatement_Update_AddSectionLabel() { var src1 = "var x = 1; switch (x) { case 1: break; }"; var src2 = "var x = 1; switch (x) { case 1: case 2: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: break;]@26 -> [case 1: case 2: break;]@26"); } [Fact] public void SwitchStatement_Update_DeleteSectionLabel() { var src1 = "var x = 1; switch (x) { case 1: case 2: break; }"; var src2 = "var x = 1; switch (x) { case 1: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: case 2: break;]@26 -> [case 1: break;]@26"); } [Fact] public void SwitchStatement_Update_BlockInSection() { var src1 = "var x = 1; switch (x) { case 1: { x++; break; } }"; var src2 = "var x = 1; switch (x) { case 1: { x--; break; } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x++;]@36 -> [x--;]@36"); } [Fact] public void SwitchStatement_Update_BlockInDefaultSection() { var src1 = "var x = 1; switch (x) { default: { x++; break; } }"; var src2 = "var x = 1; switch (x) { default: { x--; break; } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x++;]@37 -> [x--;]@37"); } [Fact] public void SwitchStatement_Insert_Section() { var src1 = "var x = 1; switch (x) { case 1: break; }"; var src2 = "var x = 1; switch (x) { case 1: break; case 2: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [case 2: break;]@41", "Insert [break;]@49"); } [Fact] public void SwitchStatement_Delete_Section() { var src1 = "var x = 1; switch (x) { case 1: break; case 2: break; }"; var src2 = "var x = 1; switch (x) { case 1: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [case 2: break;]@41", "Delete [break;]@49"); } #endregion #region Lambdas [Fact] public void Lambdas_InVariableDeclarator() { var src1 = "Action x = a => a, y = b => b;"; var src2 = "Action x = (a) => a, y = b => b + 1;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [a => a]@13 -> [(a) => a]@13", "Update [b => b]@25 -> [b => b + 1]@27", "Insert [(a)]@13", "Insert [a]@14", "Delete [a]@13"); } [Fact] public void Lambdas_InExpressionStatement() { var src1 = "F(a => a, b => b);"; var src2 = "F(b => b, a => a+1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [b => b]@12 -> @4", "Update [a => a]@4 -> [a => a+1]@12"); } [Fact] public void Lambdas_ReorderArguments() { var src1 = "F(G(a => {}), G(b => {}));"; var src2 = "F(G(b => {}), G(a => {}));"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [b => {}]@18 -> @6"); } [Fact] public void Lambdas_InWhile() { var src1 = "while (F(a => a)) { /*1*/ }"; var src2 = "do { /*1*/ } while (F(a => a));"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [do { /*1*/ } while (F(a => a));]@2", "Move [{ /*1*/ }]@20 -> @5", "Move [a => a]@11 -> @24", "Delete [while (F(a => a)) { /*1*/ }]@2"); } [Fact] public void Lambdas_InLambda_ChangeInLambdaSignature() { var src1 = "F(() => { G(x => y); });"; var src2 = "F(q => { G(() => y); });"; var edits = GetMethodEdits(src1, src2); // changes were made to the outer lambda signature: edits.VerifyEdits( "Update [() => { G(x => y); }]@4 -> [q => { G(() => y); }]@4", "Insert [q]@4", "Delete [()]@4"); } [Fact] public void Lambdas_InLambda_ChangeOnlyInLambdaBody() { var src1 = "F(() => { G(x => y); });"; var src2 = "F(() => { G(() => y); });"; var edits = GetMethodEdits(src1, src2); // no changes to the method were made, only within the outer lambda body: edits.VerifyEdits(); } [Fact] public void Lambdas_Update_ParameterRefness_NoBodyChange() { var src1 = @"F((ref int a) => a = 1);"; var src2 = @"F((out int a) => a = 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int a]@5 -> [out int a]@5"); } [Fact] public void Lambdas_Insert_Static_Top() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Insert_Static_Nested1() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => G(b => b) + a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Insert_ThisOnly_Top1() { var src1 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { } } "; var src2 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { G(a => x); } } "; var edits = GetTopEdits(src1, src2); // TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291")] public void Lambdas_Insert_ThisOnly_Top2() { var src1 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; var f1 = new Func<int, int>(a => y); } } } "; var src2 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; var f2 = from a in new[] { 1 } select a + y; var f3 = from a in new[] { 1 } where x > 0 select a; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "x", "x")); } [Fact] public void Lambdas_Insert_ThisOnly_Nested1() { var src1 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var src2 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { G(a => G(b => x)); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact] public void Lambdas_Insert_ThisOnly_Nested2() { var src1 = @" using System; class C { int x = 0; void F() { var f1 = new Func<int, int>(a => { var f2 = new Func<int, int>(b => { return b; }); return a; }); } } "; var src2 = @" using System; class C { int x = 0; void F() { var f1 = new Func<int, int>(a => { var f2 = new Func<int, int>(b => { return b; }); var f3 = new Func<int, int>(c => { return c + x; }); return a; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact] public void Lambdas_InsertAndDelete_Scopes1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 G(a => x3 + x1); G(a => x0 + y0 + x2); G(a => x); } } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 G(a => x3 + x1); G(a => x0 + y0 + x2); G(a => x); G(a => x); // OK G(a => x0 + y0); // OK G(a => x1 + y0); // error - connecting Group #1 and Group #2 G(a => x3 + x1); // error - multi-scope (conservative) G(a => x + y0); // error - connecting Group #0 and Group #1 G(a => x + x3); // error - connecting Group #0 and Group #2 } } } } } "; var insert = GetTopEdits(src1, src2); insert.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "y0", "x1"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "x1", "x3"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.lambda, "this", "y0"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "this", "x3")); var delete = GetTopEdits(src2, src1); delete.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "y0", "x1"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "x1", "x3"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.lambda, "this", "y0"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "this", "x3")); } [Fact] public void Lambdas_Insert_ForEach1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); G(a => x0 + x1); // error: connecting previously disconnected closures } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_Insert_ForEach2() { var src1 = @" using System; class C { void G(Func<int, int> f1, Func<int, int> f2, Func<int, int> f3) {} void F() { int x0 = 0; // Group #0 foreach (int x1 in new[] { 1 }) // Group #1 G(a => x0, a => x1, null); } } "; var src2 = @" using System; class C { void G(Func<int, int> f1, Func<int, int> f2, Func<int, int> f3) {} void F() { int x0 = 0; // Group #0 foreach (int x1 in new[] { 1 }) // Group #1 G(a => x0, a => x1, a => x0 + x1); // error: connecting previously disconnected closures } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_Insert_For1() { var src1 = @" using System; class C { bool G(Func<int, int> f) => true; void F() { for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) { int x2 = 0; G(a => x2); } } } "; var src2 = @" using System; class C { bool G(Func<int, int> f) => true; void F() { for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) { int x2 = 0; G(a => x2); G(a => x0 + x1); // ok G(a => x0 + x2); // error: connecting previously disconnected closures } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x2", CSharpFeaturesResources.lambda, "x0", "x2")); } [Fact] public void Lambdas_Insert_Switch1() { var src1 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; G(() => x2); switch (a) { case 1: int x0 = 1; G(() => x0); break; case 2: int x1 = 1; G(() => x1); break; } } } "; var src2 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; G(() => x2); switch (a) { case 1: int x0 = 1; G(() => x0); goto case 2; case 2: int x1 = 1; G(() => x1); goto default; default: x0 = 1; x1 = 2; G(() => x0 + x1); // ok G(() => x0 + x2); // error break; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.lambda, "x2", "x0")); } [Fact] public void Lambdas_Insert_Using1() { var src1 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static IDisposable D() => null; static void F() { using (IDisposable x0 = D(), y0 = D()) { int x1 = 1; G(() => x0); G(() => y0); G(() => x1); } } } "; var src2 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static IDisposable D() => null; static void F() { using (IDisposable x0 = D(), y0 = D()) { int x1 = 1; G(() => x0); G(() => y0); G(() => x1); G(() => F(x0, y0)); // ok G(() => F(x0, x1)); // error } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_Insert_Catch1() { var src1 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static void F() { try { } catch (Exception x0) { int x1 = 1; G(() => x0); G(() => x1); } } } "; var src2 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static void F() { try { } catch (Exception x0) { int x1 = 1; G(() => x0); G(() => x1); G(() => x0); //ok G(() => F(x0, x1)); //error } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact, WorkItem(1504, "https://github.com/dotnet/roslyn/issues/1504")] public void Lambdas_Insert_CatchFilter1() { var src1 = @" using System; class C { static bool G<T>(Func<T> f) => true; static void F() { Exception x1 = null; try { G(() => x1); } catch (Exception x0) when (G(() => x0)) { } } } "; var src2 = @" using System; class C { static bool G<T>(Func<T> f) => true; static void F() { Exception x1 = null; try { G(() => x1); } catch (Exception x0) when (G(() => x0) && G(() => x0) && // ok G(() => x0 != x1)) // error { G(() => x0); // ok } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.lambda, "x1", "x0") ); } [Fact] public void Lambdas_Insert_NotSupported() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Insert_Second_NotSupported() { var src1 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); } } "; var src2 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); var g = new Func<int, int>(b => b); } } "; var capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.NewTypeDefinition; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "b", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Insert_FirstInClass_NotSupported() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { var g = new Func<int, int>(b => b); } } "; var capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.NewTypeDefinition; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities, // TODO: https://github.com/dotnet/roslyn/issues/52759 // This is incorrect, there should be no rude edit reported Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "b", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_CeaseCapture_This() { var src1 = @" using System; class C { int x = 1; void F() { var f = new Func<int, int>(a => a + x); } } "; var src2 = @" using System; class C { int x; void F() { var f = new Func<int, int>(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "F", "this")); } [Fact] public void Lambdas_Update_Signature1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<long, long> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<long, long> f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature2() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int, int> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int, int> f) {} void F() { G2((a, b) => a + b); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(a, b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature3() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, long> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, long> f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_Nullable() { var src1 = @" using System; class C { void G1(Func<string, string> f) {} void G2(Func<string?, string?> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<string, string> f) {} void G2(Func<string?, string?> f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_SyntaxOnly1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G2((a) => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_ReturnType1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Action<int> f) {} void F() { G1(a => { return 1; }); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Action<int> f) {} void F() { G2(a => { }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_BodySyntaxOnly() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G1(a => { return 1; }); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G2(a => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_ParameterName1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G1(a => 1); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G2(b => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_ParameterRefness1() { var src1 = @" using System; delegate int D1(ref int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1((ref int a) => 1); } } "; var src2 = @" using System; delegate int D1(ref int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2((int a) => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(int a)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_ParameterRefness2() { var src1 = @" using System; delegate int D1(ref int a); delegate int D2(out int a); class C { void G(D1 f) {} void G(D2 f) {} void F() { G((ref int a) => a = 1); } } "; var src2 = @" using System; delegate int D1(ref int a); delegate int D2(out int a); class C { void G(D1 f) {} void G(D2 f) {} void F() { G((out int a) => a = 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(out int a)", CSharpFeaturesResources.lambda)); } // Add corresponding test to VB [Fact(Skip = "TODO")] public void Lambdas_Update_Signature_CustomModifiers1() { var delegateSource = @" .class public auto ansi sealed D1 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public newslot virtual instance int32 [] modopt([mscorlib]System.Int64) Invoke( int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed { } } .class public auto ansi sealed D2 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke( int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed { } } .class public auto ansi sealed D3 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke( int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed { } }"; var src1 = @" using System; class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; MetadataReference delegateDefs; using (var tempAssembly = IlasmUtilities.CreateTempAssembly(delegateSource)) { delegateDefs = MetadataReference.CreateFromImage(File.ReadAllBytes(tempAssembly.Path)); } var edits = GetTopEdits(src1, src2); // TODO edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Signature_MatchingErrorType() { var src1 = @" using System; class C { void G(Func<Unknown, Unknown> f) {} void F() { G(a => 1); } } "; var src2 = @" using System; class C { void G(Func<Unknown, Unknown> f) {} void F() { G(a => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("F").Single(), preserveLocalVariables: true) }); } [Fact] public void Lambdas_Signature_NonMatchingErrorType() { var src1 = @" using System; class C { void G1(Func<Unknown1, Unknown1> f) {} void G2(Func<Unknown2, Unknown2> f) {} void F() { G1(a => 1); } } "; var src2 = @" using System; class C { void G1(Func<Unknown1, Unknown1> f) {} void G2(Func<Unknown2, Unknown2> f) {} void F() { G2(a => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", "lambda")); } [Fact] public void Lambdas_Update_DelegateType1() { var src1 = @" using System; delegate int D1(int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; delegate int D1(int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_SourceType1() { var src1 = @" using System; delegate C D1(C a); delegate C D2(C a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; delegate C D1(C a); delegate C D2(C a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_SourceType2() { var src1 = @" using System; delegate C D1(C a); delegate B D2(B a); class B { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; delegate C D1(C a); delegate B D2(B a); class B { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_SourceTypeAndMetadataType1() { var src1 = @" namespace System { delegate string D1(string a); delegate String D2(String a); class String { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } } "; var src2 = @" namespace System { delegate string D1(string a); delegate String D2(String a); class String { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Generic1() { var src1 = @" delegate T D1<S, T>(S a, T b); delegate T D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, int> f) {} void F() { G1((a, b) => a + b); } } "; var src2 = @" delegate T D1<S, T>(S a, T b); delegate T D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, int> f) {} void F() { G2((a, b) => a + b); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Generic2() { var src1 = @" delegate int D1<S, T>(S a, T b); delegate int D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, string> f) {} void F() { G1((a, b) => 1); } } "; var src2 = @" delegate int D1<S, T>(S a, T b); delegate int D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, string> f) {} void F() { G2((a, b) => 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(a, b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_CapturedParameters1() { var src1 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2); return a1; }); } } "; var src2 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2 + 1); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(2223, "https://github.com/dotnet/roslyn/issues/2223")] public void Lambdas_Update_CapturedParameters2() { var src1 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2); return a1; }); var f3 = new Func<int, int, int>((a1, a2) => { var f4 = new Func<int, int>(a3 => x1 + a2); return a1; }); } } "; var src2 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2 + 1); return a1; }); var f3 = new Func<int, int, int>((a1, a2) => { var f4 = new Func<int, int>(a3 => x1 + a2 + 1); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_CeaseCapture_Closure1() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => y + a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2); return a1 + y; }); } } "; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a2", "y", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_CeaseCapture_IndexerParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a1 + a2); } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a2); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_CeaseCapture_IndexerParameter2() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a1 + a2); } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a2); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_CeaseCapture_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1 + a2); } } "; var src2 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_CeaseCapture_MethodParameter2() { var src1 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1 + a2); } "; var src2 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_CeaseCapture_LambdaParameter1() { var src1 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a1 + a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_SetterValueParameter1() { var src1 = @" using System; class C { int D { get { return 0; } set { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var src2 = @" using System; class C { int D { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { new Action(() => { Console.Write(value); }).Invoke(); } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "add", "value")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "remove", "value")); } [Fact] public void Lambdas_Update_DeleteCapture1() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => y + a2); return y; }); } } "; var src2 = @" using System; class C { void F() { // error var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeletingCapturedVariable, "{", "y").WithFirstLine("{ // error")); } [Fact] public void Lambdas_Update_Capturing_IndexerGetterParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a2); } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a1 + a2); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_Capturing_IndexerGetterParameter2() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a2); } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a1 + a2); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_Capturing_IndexerSetterParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { var f = new Func<int, int>(a3 => a2); } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { var f = new Func<int, int>(a3 => a1 + a2); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_Capturing_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "set", "value")); } [Fact] public void Lambdas_Update_Capturing_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact] public void Lambdas_Update_Capturing_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact] public void Lambdas_Update_Capturing_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1); } } "; var src2 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1 + a2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_Capturing_MethodParameter2() { var src1 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1); } "; var src2 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1 + a2); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_Capturing_LambdaParameter1() { var src1 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a1 + a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_StaticToThisOnly1() { var src1 = @" using System; class C { int x = 1; void F() { var f = new Func<int, int>(a => a); } } "; var src2 = @" using System; class C { int x = 1; void F() { var f = new Func<int, int>(a => a + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact] public void Lambdas_Update_StaticToThisOnly_Partial() { var src1 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { var f = new Func<int, int>(a => a); } } "; var src2 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { var f = new Func<int, int>(a => a + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this").WithFirstLine("partial void F() // impl")); } [Fact] public void Lambdas_Update_StaticToThisOnly3() { var src1 = @" using System; class C { int x = 1; void F() { var f1 = new Func<int, int>(a1 => a1); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var src2 = @" using System; class C { int x = 1; void F() { var f1 = new Func<int, int>(a1 => a1 + x); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a1", "this", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_StaticToClosure1() { var src1 = @" using System; class C { void F() { int x = 1; var f1 = new Func<int, int>(a1 => a1); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var src2 = @" using System; class C { void F() { int x = 1; var f1 = new Func<int, int>(a1 => { return a1 + x+ // 1 x; // 2 }); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.lambda).WithFirstLine("x+ // 1"), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.lambda).WithFirstLine("x; // 2")); } [Fact] public void Lambdas_Update_ThisOnlyToClosure1() { var src1 = @" using System; class C { int x = 1; void F() { int y = 1; var f1 = new Func<int, int>(a1 => a1 + x); var f2 = new Func<int, int>(a2 => a2 + x + y); } } "; var src2 = @" using System; class C { int x = 1; void F() { int y = 1; var f1 = new Func<int, int>(a1 => a1 + x + y); var f2 = new Func<int, int>(a2 => a2 + x + y); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y", "y", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Nested1() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2 + y); return a1; }); } } "; var src2 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2 + y); return a1 + y; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Nested2() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a1 + a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); // TODO: better diagnostics - identify a1 that causes the capture vs. a1 that doesn't edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1").WithFirstLine("var f1 = new Func<int, int>(a1 =>")); } [Fact] public void Lambdas_Update_Accessing_Closure1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} void F() { int x0 = 0, y0 = 0; G(a => x0); G(a => y0); } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} void F() { int x0 = 0, y0 = 0; G(a => x0); G(a => y0 + x0); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x0", "x0", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Accessing_Closure2() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x + x0); G(a => x0); G(a => y0); G(a => x1); } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); // error: disconnecting previously connected closures G(a => x0); G(a => y0); G(a => x1); } } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "x0", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Accessing_Closure3() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); G(a => x0); G(a => y0); G(a => x1); G(a => y1); } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); G(a => x0); G(a => y0); G(a => x1); G(a => y1 + x0); // error: connecting previously disconnected closures } } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x0", "x0", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Accessing_Closure4() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x + x0); G(a => x0); G(a => y0); G(a => x1); G(a => y1); } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); // error: disconnecting previously connected closures G(a => x0); G(a => y0); G(a => x1); G(a => y1 + x0); // error: connecting previously disconnected closures } } } } "; var edits = GetTopEdits(src1, src2); // TODO: "a => x + x0" is matched with "a => y1 + x0", hence we report more errors. // Including statement distance when matching would help. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "this", CSharpFeaturesResources.lambda).WithFirstLine("G(a => y1 + x0); // error: connecting previously disconnected closures"), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y1", "y1", CSharpFeaturesResources.lambda).WithFirstLine("G(a => y1 + x0); // error: connecting previously disconnected closures"), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "this", CSharpFeaturesResources.lambda).WithFirstLine("G(a => x); // error: disconnecting previously connected closures"), Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "y1", CSharpFeaturesResources.lambda).WithFirstLine("G(a => x); // error: disconnecting previously connected closures")); } [Fact] public void Lambdas_Update_Accessing_Closure_NestedLambdas() { var src1 = @" using System; class C { void G(Func<int, Func<int, int>> f) {} void F() { { int x0 = 0; // Group #0 { int x1 = 0; // Group #1 G(a => b => x0); G(a => b => x1); } } } } "; var src2 = @" using System; class C { void G(Func<int, Func<int, int>> f) {} void F() { { int x0 = 0; // Group #0 { int x1 = 0; // Group #1 G(a => b => x0); G(a => b => x1); G(a => b => x0); // ok G(a => b => x1); // ok G(a => b => x0 + x1); // error } } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_RenameCapturedLocal() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main() { int x = 1; Func<int> f = () => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main() { int X = 1; Func<int> f = () => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.RenamingCapturedVariable, "X", "x", "X")); } [Fact] public void Lambdas_RenameCapturedParameter() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main(int x) { Func<int> f = () => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main(int X) { Func<int> f = () => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.Main"), preserveLocalVariables: true) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Lambdas_Parameter_To_Discard1() { var src1 = "var x = new System.Func<int, int, int>((a, b) => 1);"; var src2 = "var x = new System.Func<int, int, int>((a, _) => 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [b]@45 -> [_]@45"); GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); } [Fact] public void Lambdas_Parameter_To_Discard2() { var src1 = "var x = new System.Func<int, int, int>((int a, int b) => 1);"; var src2 = "var x = new System.Func<int, int, int>((_, _) => 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int a]@42 -> [_]@42", "Update [int b]@49 -> [_]@45"); GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); } [Fact] public void Lambdas_Parameter_To_Discard3() { var src1 = "var x = new System.Func<int, int, int>((a, b) => 1);"; var src2 = "var x = new System.Func<int, int, int>((_, _) => 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [a]@42 -> [_]@42", "Update [b]@45 -> [_]@45"); GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); } #endregion #region Local Functions [Fact] public void LocalFunctions_InExpressionStatement() { var src1 = "F(a => a, b => b);"; var src2 = "int x(int a) => a + 1; F(b => b, x);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [a => a]@4 -> [int x(int a) => a + 1;]@2", "Move [a => a]@4 -> @2", "Update [F(a => a, b => b);]@2 -> [F(b => b, x);]@25", "Insert [(int a)]@7", "Insert [int a]@8", "Delete [a]@4"); } [Fact] public void LocalFunctions_ReorderAndUpdate() { var src1 = "int x(int a) => a; int y(int b) => b;"; var src2 = "int y(int b) => b; int x(int a) => a + 1;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [int y(int b) => b;]@21 -> @2", "Update [int x(int a) => a;]@2 -> [int x(int a) => a + 1;]@21"); } [Fact] public void LocalFunctions_InWhile() { var src1 = "do { /*1*/ } while (F(x));int x(int a) => a + 1;"; var src2 = "while (F(a => a)) { /*1*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [while (F(a => a)) { /*1*/ }]@2", "Update [int x(int a) => a + 1;]@28 -> [a => a]@11", "Move [int x(int a) => a + 1;]@28 -> @11", "Move [{ /*1*/ }]@5 -> @20", "Insert [a]@11", "Delete [do { /*1*/ } while (F(x));]@2", "Delete [(int a)]@33", "Delete [int a]@34"); } [Fact] public void LocalFunctions_InLocalFunction_NoChangeInSignature() { var src1 = "int x() { int y(int a) => a; return y(b); }"; var src2 = "int x() { int y() => c; return y(); }"; var edits = GetMethodEdits(src1, src2); // no changes to the method were made, only within the outer local function body: edits.VerifyEdits(); } [Fact] public void LocalFunctions_InLocalFunction_ChangeInSignature() { var src1 = "int x() { int y(int a) => a; return y(b); }"; var src2 = "int x(int z) { int y() => c; return y(); }"; var edits = GetMethodEdits(src1, src2); // changes were made to the outer local function signature: edits.VerifyEdits("Insert [int z]@8"); } [Fact] public void LocalFunctions_InLambda() { var src1 = "F(() => { int y(int a) => a; G(y); });"; var src2 = "F(q => { G(() => y); });"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [() => { int y(int a) => a; G(y); }]@4 -> [q => { G(() => y); }]@4", "Insert [q]@4", "Delete [()]@4"); } [Fact] public void LocalFunctions_Update_ParameterRefness_NoBodyChange() { var src1 = @"void f(ref int a) => a = 1;"; var src2 = @"void f(out int a) => a = 1;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int a]@9 -> [out int a]@9"); } [Fact] public void LocalFunctions_Insert_Static_Top() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { int f(int a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Insert_Static_Nested_ExpressionBodies() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) => a; G(localF); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) => a; int localG(int a) => G(localF) + a; G(localG); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Insert_Static_Nested_BlockBodies() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } G(localF); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } int localG(int a) { return G(localF) + a; } G(localG); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_LocalFunction_Replace_Lambda() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } G(localF); } } "; var edits = GetTopEdits(src1, src2); // To be removed when we will enable EnC for local functions edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, "localF", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Lambda_Replace_LocalFunction() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } G(localF); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, "a", CSharpFeaturesResources.lambda)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Top1() { var src1 = @" using System; class C { int x = 0; void F() { } } "; var src2 = @" using System; class C { int x = 0; void F() { int G(int a) => x; } } "; var edits = GetTopEdits(src1, src2); // TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291"), WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Top2() { var src1 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; int f1(int a) => y; } } } "; var src2 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; var f2 = from a in new[] { 1 } select a + y; var f3 = from a in new[] { 1 } where x > 0 select a; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "x", "x")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Nested1() { var src1 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { int f(int a) => a; G(f); } } "; var src2 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { int f(int a) => x; int g(int a) => G(f); G(g); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Nested2() { var src1 = @" using System; class C { int x = 0; void F() { int f1(int a) { int f2(int b) { return b; }; return a; }; } } "; var src2 = @" using System; class C { int x = 0; void F() { int f1(int a) { int f2(int b) { return b; }; int f3(int c) { return c + x; }; return a; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_InsertAndDelete_Scopes1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 int f1(int a) => x3 + x1; int f2(int a) => x0 + y0 + x2; int f3(int a) => x; } } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 int f1(int a) => x3 + x1; int f2(int a) => x0 + y0 + x2; int f3(int a) => x; int f4(int a) => x; // OK int f5(int a) => x0 + y0; // OK int f6(int a) => x1 + y0; // error - connecting Group #1 and Group #2 int f7(int a) => x3 + x1; // error - multi-scope (conservative) int f8(int a) => x + y0; // error - connecting Group #0 and Group #1 int f9(int a) => x + x3; // error - connecting Group #0 and Group #2 } } } } } "; var insert = GetTopEdits(src1, src2); insert.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "y0", "x1"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "x1", "x3"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.local_function, "this", "y0"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "this", "x3")); var delete = GetTopEdits(src2, src1); delete.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "y0", "x1"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "x1", "x3"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.local_function, "this", "y0"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "this", "x3")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ForEach1() { var src1 = @" using System; class C { void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; int f2(int a) => x0 + x1; // error: connecting previously disconnected closures } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_Switch1() { var src1 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; int f2() => x2; switch (a) { case 1: int x0 = 1; int f0() => x0; break; case 2: int x1 = 1; int f1() => x1; break; } } } "; var src2 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; int f2() => x2; switch (a) { case 1: int x0 = 1; int f0() => x0; goto case 2; case 2: int x1 = 1; int f1() => x1; goto default; default: x0 = 1; x1 = 2; int f01() => x0 + x1; // ok int f02() => x0 + x2; // error break; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.local_function, "x2", "x0")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_Catch1() { var src1 = @" using System; class C { static void F() { try { } catch (Exception x0) { int x1 = 1; int f0() => x0; int f1() => x1; } } } "; var src2 = @" using System; class C { static void F() { try { } catch (Exception x0) { int x1 = 1; int f0() => x0; int f1() => x1; int f00() => x0; //ok int f01() => F(x0, x1); //error } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1")); } [Fact] public void LocalFunctions_Insert_NotSupported() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { void M() { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "M", FeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_This() { var src1 = @" using System; class C { int x = 1; void F() { int f(int a) => a + x; } } "; var src2 = @" using System; class C { int x; void F() { int f(int a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "F", "this")); } [Fact] public void LocalFunctions_Update_Signature1() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void F() { long f(long a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature2() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void F() { int f(int a, int b) => a + b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature3() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void F() { long f(int a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_ReturnType1() { var src1 = @" using System; class C { void F() { int f(int a) { return 1; } } } "; var src2 = @" using System; class C { void F() { void f(int a) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_BodySyntaxOnly() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { int f(int a) { return a; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Update_Signature_ParameterName1() { var src1 = @" using System; class C { void F() { int f(int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(int b) => 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Update_Signature_ParameterRefness1() { var src1 = @" using System; class C { void F() { int f(ref int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(int a) => 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_ParameterRefness2() { var src1 = @" using System; class C { void F() { int f(out int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(ref int a) => 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_ParameterRefness3() { var src1 = @" using System; class C { void F() { int f(ref int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(out int a) => 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Signature_SemanticErrors() { var src1 = @" using System; class C { void F() { Unknown f(Unknown a) => 1; } } "; var src2 = @" using System; class C { void F() { Unknown f(Unknown a) => 2; } } "; var edits = GetTopEdits(src1, src2); // There are semantics errors in the case. The errors are captured during the emit execution. edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Update_CapturedParameters1() { var src1 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2; return a1; }; } } "; var src2 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2 + 1; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(2223, "https://github.com/dotnet/roslyn/issues/2223")] public void LocalFunctions_Update_CapturedParameters2() { var src1 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2; return a1; }; int f3(int a1, int a2) { int f4(int a3) => x1 + a2; return a1; }; } } "; var src2 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2 + 1; return a1; }; int f3(int a1, int a2) { int f4(int a3) => x1 + a2 + 1; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_Closure1() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => y + a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2; return a1 + y; }; } } "; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "f2", "y", CSharpFeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_IndexerParameter() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a2; return f; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1 + a2; } } "; var src2 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_LambdaParameter1() { var src1 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a1 + a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "int f1(int a1, int a2)\r\n {\r\n int f2(int a3) => a2;\r\n return a1;\r\n };\r\n ", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_SetterValueParameter1() { var src1 = @" using System; class C { int D { get { return 0; } set { void f() { Console.Write(value); } f(); } } } "; var src2 = @" using System; class C { int D { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { void f() { Console.Write(value); } f(); } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { void f() { Console.Write(value); } f(); } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "add", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { void f() { Console.Write(value); } f(); } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "remove", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_DeleteCapture1() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => y + a2; return y; }; } } "; var src2 = @" using System; class C { void F() { // error int f1(int a1) { int f2(int a2) => a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeletingCapturedVariable, "{", "y")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerGetterParameter2() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a2; return f; } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerSetterParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { int f(int a3) => a2; } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { int f(int a3) => a1 + a2; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { void f() { Console.Write(value); } f(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "set", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { void f() { Console.Write(value); } f(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { void f() { Console.Write(value); } f(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1; } } "; var src2 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1 + a2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_LambdaParameter1() { var src1 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a1 + a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly1() { var src1 = @" using System; class C { int x = 1; void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { int x = 1; void F() { int f(int a) => a + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly_Partial() { var src1 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { int f(int a) => a; } } "; var src2 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { int f(int a) => a + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly3() { var src1 = @" using System; class C { int x = 1; void F() { int f1(int a1) => a1; int f2(int a2) => a2 + x; } } "; var src2 = @" using System; class C { int x = 1; void F() { int f1(int a1) => a1 + x; int f2(int a2) => a2 + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "f1", "this", CSharpFeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToClosure1() { var src1 = @" using System; class C { void F() { int x = 1; int f1(int a1) => a1; int f2(int a2) => a2 + x; } } "; var src2 = @" using System; class C { void F() { int x = 1; int f1(int a1) { return a1 + x+ // 1 x; // 2 }; int f2(int a2) => a2 + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.local_function), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_ThisOnlyToClosure1() { var src1 = @" using System; class C { int x = 1; void F() { int y = 1; int f1(int a1) => a1 + x; int f2(int a2) => a2 + x + y; } } "; var src2 = @" using System; class C { int x = 1; void F() { int y = 1; int f1(int a1) => a1 + x + y; int f2(int a2) => a2 + x + y; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y", "y", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Nested1() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2 + y; return a1; }; } } "; var src2 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2 + y; return a1 + y; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Nested2() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a1 + a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_RenameCapturedLocal() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main() { int x = 1; int f() => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main() { int X = 1; int f() => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.RenamingCapturedVariable, "X", "x", "X")); } [Fact] public void LocalFunctions_RenameCapturedParameter() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main(int x) { int f() => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main(int X) { int f() => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.Main"), preserveLocalVariables: true) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void LocalFunction_In_Parameter_InsertWhole() { var src1 = @"class Test { void M() { } }"; var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { }]@13 -> [void M() { void local(in int b) { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_In_Parameter_InsertParameter() { var src1 = @"class Test { void M() { void local() { throw null; } } }"; var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { void local() { throw null; } }]@13 -> [void M() { void local(in int b) { throw null; } }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "local", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunction_In_Parameter_Update() { var src1 = @"class Test { void M() { void local(int b) { throw null; } } }"; var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { void local(int b) { throw null; } }]@13 -> [void M() { void local(in int b) { throw null; } }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "local", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunction_ReadOnlyRef_ReturnType_Insert() { var src1 = @"class Test { void M() { } }"; var src2 = @"class Test { void M() { ref readonly int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { }]@13 -> [void M() { ref readonly int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_ReadOnlyRef_ReturnType_Update() { var src1 = @"class Test { void M() { int local() { throw null; } } }"; var src2 = @"class Test { void M() { ref readonly int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { int local() { throw null; } }]@13 -> [void M() { ref readonly int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "local", CSharpFeaturesResources.local_function)); } [WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")] [Fact] public void LocalFunction_AddToInterfaceMethod() { var src1 = @" using System; interface I { static int X = M(() => 1); static int M() => 1; static void F() { void g() { } } } "; var src2 = @" using System; interface I { static int X = M(() => { void f3() {} return 2; }); static int M() => 1; static void F() { int f1() => 1; f1(); void g() { void f2() {} f2(); } var l = new Func<int>(() => 1); l(); } } "; var edits = GetTopEdits(src1, src2); // lambdas are ok as they are emitted to a nested type edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.NetCoreApp }, expectedDiagnostics: new[] { Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f1"), Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f2"), Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f3") }); } [Fact] public void LocalFunction_AddStatic() { var src1 = @"class Test { void M() { int local() { throw null; } } }"; var src2 = @"class Test { void M() { static int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { int local() { throw null; } }]@13 -> [void M() { static int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_RemoveStatic() { var src1 = @"class Test { void M() { static int local() { throw null; } } }"; var src2 = @"class Test { void M() { int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { static int local() { throw null; } }]@13 -> [void M() { int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_AddUnsafe() { var src1 = @"class Test { void M() { int local() { throw null; } } }"; var src2 = @"class Test { void M() { unsafe int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { int local() { throw null; } }]@13 -> [void M() { unsafe int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_RemoveUnsafe() { var src1 = @"class Test { void M() { unsafe int local() { throw null; } } }"; var src2 = @"class Test { void M() { int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { unsafe int local() { throw null; } }]@13 -> [void M() { int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunction_AddAsync() { var src1 = @"class Test { void M() { Task<int> local() => throw null; } }"; var src2 = @"class Test { void M() { async Task<int> local() => throw null; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunction_RemoveAsync() { var src1 = @"class Test { void M() { async int local() { throw null; } } }"; var src2 = @"class Test { void M() { int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "local", FeaturesResources.local_function)); } [Fact] public void LocalFunction_AddAttribute() { var src1 = "void L() { }"; var src2 = "[A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [void L() { }]@2 -> [[A]void L() { }]@2"); // Get top edits so we can validate rude edits GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_RemoveAttribute() { var src1 = "[A]void L() { }"; var src2 = "void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A]void L() { }]@2 -> [void L() { }]@2"); // Get top edits so we can validate rude edits GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReorderAttribute() { var src1 = "[A, B]void L() { }"; var src2 = "[B, A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A, B]void L() { }]@2 -> [[B, A]void L() { }]@2"); // Get top edits so we can validate rude edits GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_CombineAttributeLists() { var src1 = "[A][B]void L() { }"; var src2 = "[A, B]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A][B]void L() { }]@2 -> [[A, B]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_SplitAttributeLists() { var src1 = "[A, B]void L() { }"; var src2 = "[A][B]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A, B]void L() { }]@2 -> [[A][B]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_ChangeAttributeListTarget1() { var src1 = "[return: A]void L() { }"; var src2 = "[A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[return: A]void L() { }]@2 -> [[A]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ChangeAttributeListTarget2() { var src1 = "[A]void L() { }"; var src2 = "[return: A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A]void L() { }]@2 -> [[return: A]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReturnType_AddAttribute() { var src1 = "int L() { return 1; }"; var src2 = "[return: A]int L() { return 1; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int L() { return 1; }]@2 -> [[return: A]int L() { return 1; }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReturnType_RemoveAttribute() { var src1 = "[return: A]int L() { return 1; }"; var src2 = "int L() { return 1; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[return: A]int L() { return 1; }]@2 -> [int L() { return 1; }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReturnType_ReorderAttribute() { var src1 = "[return: A, B]int L() { return 1; }"; var src2 = "[return: B, A]int L() { return 1; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[return: A, B]int L() { return 1; }]@2 -> [[return: B, A]int L() { return 1; }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_Parameter_AddAttribute() { var src1 = "void L(int i) { }"; var src2 = "void L([A]int i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int i]@9 -> [[A]int i]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.parameter)); } [Fact] public void LocalFunction_Parameter_RemoveAttribute() { var src1 = "void L([A]int i) { }"; var src2 = "void L(int i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A]int i]@9 -> [int i]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.parameter)); } [Fact] public void LocalFunction_Parameter_ReorderAttribute() { var src1 = "void L([A, B]int i) { }"; var src2 = "void L([B, A]int i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A, B]int i]@9 -> [[B, A]int i]@9"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_TypeParameter_AddAttribute() { var src1 = "void L<T>(T i) { }"; var src2 = "void L<[A] T>(T i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [T]@9 -> [[A] T]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.type_parameter)); } [Fact] public void LocalFunction_TypeParameter_RemoveAttribute() { var src1 = "void L<[A] T>(T i) { }"; var src2 = "void L<T>(T i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A] T]@9 -> [T]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.type_parameter)); } [Fact] public void LocalFunction_TypeParameter_ReorderAttribute() { var src1 = "void L<[A, B] T>(T i) { }"; var src2 = "void L<[B, A] T>(T i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A, B] T]@9 -> [[B, A] T]@9"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunctions_TypeParameter_Insert1() { var src1 = @"void L() {}"; var src2 = @"void L<A>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@8", "Insert [A]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Insert2() { var src1 = @"void L<A>() {}"; var src2 = @"void L<A,B>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@8 -> [<A,B>]@8", "Insert [B]@11"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Delete1() { var src1 = @"void L<A>() {}"; var src2 = @"void L() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@8", "Delete [A]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Delete2() { var src1 = @"void L<A,B>() {}"; var src2 = @"void L<B>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@8 -> [<B>]@8", "Delete [A]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Update() { var src1 = @"void L<A>() {}"; var src2 = @"void L<B>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [A]@9 -> [B]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Theory] [InlineData("Enum", "Delegate")] [InlineData("IDisposable", "IDisposable, new()")] public void LocalFunctions_TypeParameter_Constraint_Clause_Update(string oldConstraint, string newConstraint) { var src1 = "void L<A>() where A : " + oldConstraint + " {}"; var src2 = "void L<A>() where A : " + newConstraint + " {}"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [where A : " + oldConstraint + "]@14 -> [where A : " + newConstraint + "]@14"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void LocalFunctions_TypeParameter_Constraint_Clause_Delete(string oldConstraint) { var src1 = "void L<A>() where A : " + oldConstraint + " {}"; var src2 = "void L<A>() {}"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [where A : " + oldConstraint + "]@14"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Constraint_Clause_Add() { var src1 = "void L<A,B>() where A : new() {}"; var src2 = "void L<A,B>() where A : new() where B : System.IDisposable {}"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [where B : System.IDisposable]@32"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Reorder() { var src1 = @"void L<A,B>() {}"; var src2 = @"void L<B,A>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@11 -> @9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_ReorderAndUpdate() { var src1 = @"void L<A,B>() {}"; var src2 = @"void L<B,C>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@11 -> @9", "Update [A]@9 -> [C]@11"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } #endregion #region Queries [Fact] public void Queries_Update_Signature_Select1() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} select a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1.0} select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Update_Signature_Select2() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} select a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} select a.ToString(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Update_Signature_From1() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} from b in new[] {2} select b; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from long a in new[] {1} from b in new[] {2} select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "from", CSharpFeaturesResources.from_clause)); } [Fact] public void Queries_Update_Signature_From2() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from System.Int64 a in new[] {1} from b in new[] {2} select b; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from long a in new[] {1} from b in new[] {2} select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Update_Signature_From3() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} from b in new[] {2} select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new List<int>() from b in new List<int>() select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Update_Signature_Let1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} let b = 1 select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} let b = 1.0 select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "let", CSharpFeaturesResources.let_clause)); } [Fact] public void Queries_Update_Signature_OrderBy1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1.0 descending, a + 2 ascending select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "a + 1.0 descending", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Update_Signature_OrderBy2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1 descending, a + 2.0 ascending select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "a + 2.0 ascending", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Update_Signature_Join1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1.0} on a equals b select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_Join2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join byte b in new[] {1} on a equals b select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_Join3() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a + 1 equals b select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a + 1.0 equals b select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_Join4() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b + 1 select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b + 1.0 select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_GroupBy1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a + 1 by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a + 1.0 by a into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_Update_Signature_GroupBy2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a by a + 1.0 into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_Update_Signature_GroupBy_MatchingErrorTypes() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown G1(int a) => null; Unknown G2(int a) => null; void F() { var result = from a in new[] {1} group G1(a) by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown G1(int a) => null; Unknown G2(int a) => null; void F() { var result = from a in new[] {1} group G2(a) by a into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Update_Signature_GroupBy_NonMatchingErrorTypes() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown1 G1(int a) => null; Unknown2 G2(int a) => null; void F() { var result = from a in new[] {1} group G1(a) by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown1 G1(int a) => null; Unknown2 G2(int a) => null; void F() { var result = from a in new[] {1} group G2(a) by a into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_FromSelect_Update1() { var src1 = "F(from a in b from x in y select c);"; var src2 = "F(from a in c from x in z select c + 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [from a in b]@4 -> [from a in c]@4", "Update [from x in y]@16 -> [from x in z]@16", "Update [select c]@28 -> [select c + 1]@28"); } [Fact] public void Queries_FromSelect_Update2() { var src1 = "F(from a in b from x in y select c);"; var src2 = "F(from a in b from x in z select c);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [from x in y]@16 -> [from x in z]@16"); } [Fact] public void Queries_FromSelect_Update3() { var src1 = "F(from a in await b from x in y select c);"; var src2 = "F(from a in await c from x in y select c);"; var edits = GetMethodEdits(src1, src2, MethodKind.Async); edits.VerifyEdits( "Update [await b]@34 -> [await c]@34"); } [Fact] public void Queries_Select_Reduced1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a + 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Select_Reduced2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a + 1; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_FromSelect_Delete() { var src1 = "F(from a in b from c in d select a + c);"; var src2 = "F(from a in b select c + 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [select a + c]@28 -> [select c + 1]@16", "Delete [from c in d]@16"); } [Fact] public void Queries_JoinInto_Update() { var src1 = "F(from a in b join b in c on a equals b into g1 select g1);"; var src2 = "F(from a in b join b in c on a equals b into g2 select g2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [select g1]@50 -> [select g2]@50", "Update [into g1]@42 -> [into g2]@42"); } [Fact] public void Queries_JoinIn_Update() { var src1 = "F(from a in b join b in await A(1) on a equals b select g);"; var src2 = "F(from a in b join b in await A(2) on a equals b select g);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [await A(1)]@26 -> [await A(2)]@26"); } [Fact] public void Queries_GroupBy_Update() { var src1 = "F(from a in b group a by a.x into g select g);"; var src2 = "F(from a in b group z by z.y into h select h);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [group a by a.x]@17 -> [group z by z.y]@17", "Update [into g select g]@32 -> [into h select h]@32", "Update [select g]@40 -> [select h]@40"); } [Fact] public void Queries_OrderBy_Reorder() { var src1 = "F(from a in b orderby a.x, a.b descending, a.c ascending select a.d);"; var src2 = "F(from a in b orderby a.x, a.c ascending, a.b descending select a.d);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [a.c ascending]@46 -> @30"); } [Fact] public void Queries_GroupBy_Reduced1() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1.0 by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced2() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1 by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_GroupBy_Reduced3() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1.0 by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced4() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1 by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_OrderBy_Continuation_Update() { var src1 = "F(from a in b orderby a.x, a.b descending select a.d into z orderby a.c ascending select z);"; var src2 = "F(from a in b orderby a.x, a.c ascending select a.d into z orderby a.b descending select z);"; var edits = GetMethodEdits(src1, src2); var actual = ToMatchingPairs(edits.Match); var expected = new MatchingPairs { { "F(from a in b orderby a.x, a.b descending select a.d into z orderby a.c ascending select z);", "F(from a in b orderby a.x, a.c ascending select a.d into z orderby a.b descending select z);" }, { "from a in b", "from a in b" }, { "orderby a.x, a.b descending select a.d into z orderby a.c ascending select z", "orderby a.x, a.c ascending select a.d into z orderby a.b descending select z" }, { "orderby a.x, a.b descending", "orderby a.x, a.c ascending" }, { "a.x", "a.x" }, { "a.b descending", "a.c ascending" }, { "select a.d", "select a.d" }, { "into z orderby a.c ascending select z", "into z orderby a.b descending select z" }, { "orderby a.c ascending select z", "orderby a.b descending select z" }, { "orderby a.c ascending", "orderby a.b descending" }, { "a.c ascending", "a.b descending" }, { "select z", "select z" } }; expected.AssertEqual(actual); edits.VerifyEdits( "Update [a.b descending]@30 -> [a.c ascending]@30", "Update [a.c ascending]@74 -> [a.b descending]@73"); } [Fact] public void Queries_CapturedTransparentIdentifiers_FromClause1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a) > 0 where Z(() => b) > 0 where Z(() => a) > 0 where Z(() => b) > 0 select a; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a) > 1 // update where Z(() => b) > 2 // update where Z(() => a) > 3 // update where Z(() => b) > 4 // update select a; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_CapturedTransparentIdentifiers_LetClause1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } let b = Z(() => a) select a + b; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } let b = Z(() => a + 1) select a - b; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_CapturedTransparentIdentifiers_JoinClause1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g select Z(() => g.First()); } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g select Z(() => g.Last()); } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_CeaseCapturingTransparentIdentifiers1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + b) > 0 select a; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + 1) > 0 select a; } }"; var edits = GetTopEdits(src1, src2); // TODO: better location (the variable, not the from clause) edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "from b in new[] { 2 }", "b")); } [Fact] public void Queries_CapturingTransparentIdentifiers1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + 1) > 0 select a; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + b) > 0 select a; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "b", "b")); } [Fact] public void Queries_AccessingCapturedTransparentIdentifier1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select 1; } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_AccessingCapturedTransparentIdentifier2() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select b; } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select a + b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_AccessingCapturedTransparentIdentifier3() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => 1); } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_NotAccessingCapturedTransparentIdentifier1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select a + b; } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "select", "a", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_NotAccessingCapturedTransparentIdentifier2() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => 1); } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_Insert1() { var src1 = @" using System; using System.Linq; class C { void F() { } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] { 1 } select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } #endregion #region Yield [Fact] public void Yield_Update1() { var src1 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 2; yield break; } } "; var src2 = @" class C { static IEnumerable<int> F() { yield return 3; yield break; yield return 4; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield break;", CSharpFeaturesResources.yield_return_statement, CSharpFeaturesResources.yield_break_statement), Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield return 4;", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.yield_return_statement)); } [Fact] public void Yield_Delete1() { var src1 = @" yield return 1; yield return 2; yield return 3; "; var src2 = @" yield return 1; yield return 3; "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator); bodyEdits.VerifyEdits( "Delete [yield return 2;]@42"); } [Fact] public void Yield_Delete2() { var src1 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 2; yield return 3; } } "; var src2 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 3; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void Yield_Insert1() { var src1 = @" yield return 1; yield return 3; "; var src2 = @" yield return 1; yield return 2; yield return 3; yield return 4; "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator); bodyEdits.VerifyEdits( "Insert [yield return 2;]@42", "Insert [yield return 4;]@76"); } [Fact] public void Yield_Insert2() { var src1 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 3; } } "; var src2 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 2; yield return 3; yield return 4; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "yield return 4;", CSharpFeaturesResources.yield_return_statement), Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MissingIteratorStateMachineAttribute() { var src1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 1; } } "; var src2 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.Mscorlib40AndSystemCore }, Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static IEnumerable<int> F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute")); } [Fact] public void MissingIteratorStateMachineAttribute2() { var src1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { return null; } } "; var src2 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.Mscorlib40AndSystemCore }); } #endregion #region Await /// <summary> /// Tests spilling detection logic of <see cref="CSharpEditAndContinueAnalyzer.ReportStateMachineSuspensionPointRudeEdits"/>. /// </summary> [Fact] public void AwaitSpilling_OK() { var src1 = @" class C { static async Task<int> F() { await F(1); if (await F(1)) { Console.WriteLine(1); } if (await F(1)) { Console.WriteLine(1); } if (F(1, await F(1))) { Console.WriteLine(1); } if (await F(1)) { Console.WriteLine(1); } do { Console.WriteLine(1); } while (await F(1)); for (var x = await F(1); await G(1); await H(1)) { Console.WriteLine(1); } foreach (var x in await F(1)) { Console.WriteLine(1); } using (var x = await F(1)) { Console.WriteLine(1); } lock (await F(1)) { Console.WriteLine(1); } lock (a = await F(1)) { Console.WriteLine(1); } var a = await F(1), b = await G(1); a = await F(1); switch (await F(2)) { case 1: return b = await F(1); } return await F(1); } static async Task<int> G() => await F(1); } "; var src2 = @" class C { static async Task<int> F() { await F(2); if (await F(1)) { Console.WriteLine(2); } if (await F(2)) { Console.WriteLine(1); } if (F(1, await F(1))) { Console.WriteLine(2); } while (await F(1)) { Console.WriteLine(1); } do { Console.WriteLine(2); } while (await F(2)); for (var x = await F(2); await G(2); await H(2)) { Console.WriteLine(2); } foreach (var x in await F(2)) { Console.WriteLine(2); } using (var x = await F(2)) { Console.WriteLine(1); } lock (await F(2)) { Console.WriteLine(2); } lock (a = await F(2)) { Console.WriteLine(2); } var a = await F(2), b = await G(2); b = await F(2); switch (await F(2)) { case 1: return b = await F(2); } return await F(2); } static async Task<int> G() => await F(2); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } /// <summary> /// Tests spilling detection logic of <see cref="CSharpEditAndContinueAnalyzer.ReportStateMachineSuspensionPointRudeEdits"/>. /// </summary> [Fact] public void AwaitSpilling_Errors() { var src1 = @" class C { static async Task<int> F() { F(1, await F(1)); F(1, await F(1)); F(await F(1)); await F(await F(1)); if (F(1, await F(1))) { Console.WriteLine(1); } var a = F(1, await F(1)), b = F(1, await G(1)); b = F(1, await F(1)); b += await F(1); } } "; var src2 = @" class C { static async Task<int> F() { F(2, await F(1)); F(1, await F(2)); F(await F(2)); await F(await F(2)); if (F(2, await F(1))) { Console.WriteLine(1); } var a = F(1, await F(2)), b = F(1, await G(2)); b = F(1, await F(2)); b += await F(2); } } "; var edits = GetTopEdits(src1, src2); // consider: these edits can be allowed if we get more sophisticated edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(2, await F(1));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(1, await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "await F(await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(2, await F(1))"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "var a = F(1, await F(2)), b = F(1, await G(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "var a = F(1, await F(2)), b = F(1, await G(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "b = F(1, await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "b += await F(2);")); } [Fact] public void Await_Delete1() { var src1 = @" await F(1); await F(2); await F(3); "; var src2 = @" await F(1); await F(3); "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async); bodyEdits.VerifyEdits( "Delete [await F(2);]@37", "Delete [await F(2)]@37"); } [Fact] public void Await_Delete2() { var src1 = @" class C { static async Task<int> F() { await F(1); { await F(2); } await F(3); } } "; var src2 = @" class C { static async Task<int> F() { await F(1); { F(2); } await F(3); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "F(2);", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Delete3() { var src1 = @" class C { static async Task<int> F() { await F(await F(1)); } } "; var src2 = @" class C { static async Task<int> F() { await F(1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "await F(1);", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Delete4() { var src1 = @" class C { static async Task<int> F() => await F(await F(1)); } "; var src2 = @" class C { static async Task<int> F() => await F(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "static async Task<int> F()", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Delete5() { var src1 = @" class C { static async Task<int> F() => await F(1); } "; var src2 = @" class C { static async Task<int> F() => F(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "static async Task<int> F()", CSharpFeaturesResources.await_expression)); } [Fact] public void AwaitForEach_Delete1() { var src1 = @" class C { static async Task<int> F() { await foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { foreach (var x in G()) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "foreach (var x in G())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void AwaitForEach_Delete2() { var src1 = @" class C { static async Task<int> F() { await foreach (var (x, y) in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { foreach (var (x, y) in G()) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "foreach (var (x, y) in G())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void AwaitForEach_Delete3() { var src1 = @" class C { static async Task<int> F() { await foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_foreach_statement)); } [Fact] public void AwaitUsing_Delete1() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await using D x = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "await using", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Delete2() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await using D y = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "await using", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Delete3() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Delete4() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { using D x = new D(), y = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "using", CSharpFeaturesResources.using_declaration), Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "using", CSharpFeaturesResources.using_declaration)); } [Fact] public void Await_Insert1() { var src1 = @" await F(1); await F(3); "; var src2 = @" await F(1); await F(2); await F(3); await F(4); "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async); bodyEdits.VerifyEdits( "Insert [await F(2);]@37", "Insert [await F(4);]@63", "Insert [await F(2)]@37", "Insert [await F(4)]@63"); } [Fact] public void Await_Insert2() { var src1 = @" class C { static async IEnumerable<int> F() { await F(1); await F(3); } } "; var src2 = @" class C { static async IEnumerable<int> F() { await F(1); await F(2); await F(3); await F(4); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Insert3() { var src1 = @" class C { static async IEnumerable<int> F() { await F(1); await F(3); } } "; var src2 = @" class C { static async IEnumerable<int> F() { await F(await F(1)); await F(await F(2)); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Insert4() { var src1 = @" class C { static async Task<int> F() => await F(1); } "; var src2 = @" class C { static async Task<int> F() => await F(await F(1)); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Insert5() { var src1 = @" class C { static Task<int> F() => F(1); } "; var src2 = @" class C { static async Task<int> F() => await F(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void AwaitForEach_Insert_Ok() { var src1 = @" class C { static async Task<int> F() { foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { await foreach (var x in G()) { } } } "; var edits = GetTopEdits(src1, src2); // ok to add awaits if there were none before and no active statements edits.VerifyRudeDiagnostics(); } [Fact] public void AwaitForEach_Insert() { var src1 = @" class C { static async Task<int> F() { await Task.FromResult(1); foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { await Task.FromResult(1); await foreach (var x in G()) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", "await")); } [Fact] public void AwaitUsing_Insert1() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "y = new D()", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Insert2() { var src1 = @" class C { static async Task<int> F() { await G(); using D x = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await G(); await using D x = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", "await")); } [Fact] public void Await_Update() { var src1 = @" class C { static async IAsyncEnumerable<int> F() { await foreach (var x in G()) { } await Task.FromResult(1); await Task.FromResult(1); await Task.FromResult(1); yield return 1; yield break; yield break; } } "; var src2 = @" class C { static async IAsyncEnumerable<int> F() { await foreach (var (x,y) in G()) { } await foreach (var x in G()) { } await using D x = new D(), y = new D(); await Task.FromResult(1); await Task.FromResult(1); yield return 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingStateMachineShape, "await foreach (var x in G()) { }", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_foreach_statement), Diagnostic(RudeEditKind.ChangingStateMachineShape, "x = new D()", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.ChangingStateMachineShape, "y = new D()", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.ChangingStateMachineShape, "await Task.FromResult(1)", CSharpFeaturesResources.yield_return_statement, CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.ChangingStateMachineShape, "await Task.FromResult(1)", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield return 1;", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MissingAsyncStateMachineAttribute1() { var src1 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await new Task(); return 1; } } "; var src2 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await new Task(); return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.MinimalAsync }, expectedDiagnostics: new[] { Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static async Task<int> F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute") }); } [Fact] public void MissingAsyncStateMachineAttribute2() { var src1 = @" using System.Threading.Tasks; class C { static Task<int> F() { return null; } } "; var src2 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await new Task(); return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.MinimalAsync }); } [Fact] public void SemanticError_AwaitInPropertyAccessor() { var src1 = @" using System.Threading.Tasks; class C { public Task<int> P { get { await Task.Delay(1); return 1; } } } "; var src2 = @" using System.Threading.Tasks; class C { public Task<int> P { get { await Task.Delay(2); return 1; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } #endregion #region Out Var [Fact] public void OutVarType_Update() { var src1 = @" M(out var y); "; var src2 = @" M(out int y); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M(out var y);]@4 -> [M(out int y);]@4"); } [Fact] public void OutVarNameAndType_Update() { var src1 = @" M(out var y); "; var src2 = @" M(out int z); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M(out var y);]@4 -> [M(out int z);]@4", "Update [y]@14 -> [z]@14"); } [Fact] public void OutVar_Insert() { var src1 = @" M(); "; var src2 = @" M(out int y); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M();]@4 -> [M(out int y);]@4", "Insert [y]@14"); } [Fact] public void OutVar_Delete() { var src1 = @" M(out int y); "; var src2 = @" M(); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M(out int y);]@4 -> [M();]@4", "Delete [y]@14"); } #endregion #region Pattern [Fact] public void ConstantPattern_Update() { var src1 = @" if ((o is null) && (y == 7)) return 3; if (a is 7) return 5; "; var src2 = @" if ((o1 is null) && (y == 7)) return 3; if (a is 77) return 5; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if ((o is null) && (y == 7)) return 3;]@4 -> [if ((o1 is null) && (y == 7)) return 3;]@4", "Update [if (a is 7) return 5;]@44 -> [if (a is 77) return 5;]@45"); } [Fact] public void DeclarationPattern_Update() { var src1 = @" if (!(o is int i) && (y == 7)) return; if (!(a is string s)) return; if (!(b is string t)) return; if (!(c is int j)) return; "; var src2 = @" if (!(o1 is int i) && (y == 7)) return; if (!(a is int s)) return; if (!(b is string t1)) return; if (!(c is int)) return; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (!(o is int i) && (y == 7)) return;]@4 -> [if (!(o1 is int i) && (y == 7)) return;]@4", "Update [if (!(a is string s)) return;]@44 -> [if (!(a is int s)) return;]@45", "Update [if (!(c is int j)) return;]@106 -> [if (!(c is int)) return;]@105", "Update [t]@93 -> [t1]@91", "Delete [j]@121"); } [Fact] public void DeclarationPattern_Reorder() { var src1 = @"if ((a is int i) && (b is int j)) { A(); }"; var src2 = @"if ((b is int j) && (a is int i)) { A(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if ((a is int i) && (b is int j)) { A(); }]@2 -> [if ((b is int j) && (a is int i)) { A(); }]@2", "Reorder [j]@32 -> @16"); } [Fact] public void VarPattern_Update() { var src1 = @" if (o is (var x, var y)) return; if (o4 is (string a, var (b, c))) return; if (o2 is var (e, f, g)) return; if (o3 is var (k, l, m)) return; "; var src2 = @" if (o is (int x, int y1)) return; if (o1 is (var a, (var b, string c1))) return; if (o7 is var (g, e, f)) return; if (o3 is (string k, int l2, int m)) return; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (o is (var x, var y)) return;]@4 -> [if (o is (int x, int y1)) return;]@4", "Update [if (o4 is (string a, var (b, c))) return;]@38 -> [if (o1 is (var a, (var b, string c1))) return;]@39", "Update [if (o2 is var (e, f, g)) return;]@81 -> [if (o7 is var (g, e, f)) return;]@87", "Reorder [g]@102 -> @102", "Update [if (o3 is var (k, l, m)) return;]@115 -> [if (o3 is (string k, int l2, int m)) return;]@121", "Update [y]@25 -> [y1]@25", "Update [c]@67 -> [c1]@72", "Update [l]@133 -> [l2]@146"); } [Fact] public void PositionalPattern_Update1() { var src1 = @"var r = (x, y, z) switch { (0, var b, int c) when c > 1 => 2, _ => 4 };"; var src2 = @"var r = ((x, y, z)) switch { (_, int b1, double c1) when c1 > 2 => c1, _ => 4 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(x, y, z) switch { (0, var b, int c) when c > 1 => 2, _ => 4 }]@10 -> [((x, y, z)) switch { (_, int b1, double c1) when c1 > 2 => c1, _ => 4 }]@10", "Update [(0, var b, int c) when c > 1 => 2]@29 -> [(_, int b1, double c1) when c1 > 2 => c1]@31", "Reorder [c]@44 -> @39", "Update [c]@44 -> [b1]@39", "Update [b]@37 -> [c1]@50", "Update [when c > 1]@47 -> [when c1 > 2]@54"); } [Fact] public void PositionalPattern_Update2() { var src1 = @"var r = (x, y, z) switch { (var a, 3, 4) => a, (1, 1, Point { X: 0 } p) => 3, _ => 4 };"; var src2 = @"var r = ((x, y, z)) switch { (var a1, 3, 4) => a1 * 2, (1, 1, Point { Y: 0 } p1) => 3, _ => 4 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(x, y, z) switch { (var a, 3, 4) => a, (1, 1, Point { X: 0 } p) => 3, _ => 4 }]@10 -> [((x, y, z)) switch { (var a1, 3, 4) => a1 * 2, (1, 1, Point { Y: 0 } p1) => 3, _ => 4 }]@10", "Update [(var a, 3, 4) => a]@29 -> [(var a1, 3, 4) => a1 * 2]@31", "Update [(1, 1, Point { X: 0 } p) => 3]@49 -> [(1, 1, Point { Y: 0 } p1) => 3]@57", "Update [a]@34 -> [a1]@36", "Update [p]@71 -> [p1]@79"); } [Fact] public void PositionalPattern_Reorder() { var src1 = @"var r = (x, y, z) switch { (1, 2, 3) => 0, (var a, 3, 4) => a, (0, var b, int c) when c > 1 => 2, (1, 1, Point { X: 0 } p) => 3, _ => 4 }; "; var src2 = @"var r = ((x, y, z)) switch { (1, 1, Point { X: 0 } p) => 3, (0, var b, int c) when c > 1 => 2, (var a, 3, 4) => a, (1, 2, 3) => 0, _ => 4 }; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( @"Update [(x, y, z) switch { (1, 2, 3) => 0, (var a, 3, 4) => a, (0, var b, int c) when c > 1 => 2, (1, 1, Point { X: 0 } p) => 3, _ => 4 }]@10 -> [((x, y, z)) switch { (1, 1, Point { X: 0 } p) => 3, (0, var b, int c) when c > 1 => 2, (var a, 3, 4) => a, (1, 2, 3) => 0, _ => 4 }]@10", "Reorder [(var a, 3, 4) => a]@47 -> @100", "Reorder [(0, var b, int c) when c > 1 => 2]@68 -> @64", "Reorder [(1, 1, Point { X: 0 } p) => 3]@104 -> @32"); } [Fact] public void PropertyPattern_Update() { var src1 = @" if (address is { State: ""WA"" }) return 1; if (obj is { Color: Color.Purple }) return 2; if (o is string { Length: 5 } s) return 3; "; var src2 = @" if (address is { ZipCode: 98052 }) return 4; if (obj is { Size: Size.M }) return 2; if (o is string { Length: 7 } s7) return 5; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (address is { State: \"WA\" }) return 1;]@4 -> [if (address is { ZipCode: 98052 }) return 4;]@4", "Update [if (obj is { Color: Color.Purple }) return 2;]@47 -> [if (obj is { Size: Size.M }) return 2;]@50", "Update [if (o is string { Length: 5 } s) return 3;]@94 -> [if (o is string { Length: 7 } s7) return 5;]@90", "Update [return 1;]@36 -> [return 4;]@39", "Update [s]@124 -> [s7]@120", "Update [return 3;]@127 -> [return 5;]@124"); } [Fact] public void RecursivePatterns_Reorder() { var src1 = @"var r = obj switch { string s when s.Length > 0 => (s, obj1) switch { (""a"", int i) => i, _ => 0 }, int i => i * i, _ => -1 }; "; var src2 = @"var r = obj switch { int i => i * i, string s when s.Length > 0 => (s, obj1) switch { (""a"", int i) => i, _ => 0 }, _ => -1 }; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [int i => i * i]@140 -> @29", "Move [i]@102 -> @33", "Move [i]@144 -> @123"); } [Fact] public void CasePattern_UpdateInsert() { var src1 = @" switch(shape) { case Circle c: return 1; default: return 4; } "; var src2 = @" switch(shape) { case Circle c1: return 1; case Point p: return 0; default: return 4; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c: return 1;]@26 -> [case Circle c1: return 1;]@26", "Insert [case Point p: return 0;]@57", "Insert [case Point p:]@57", "Insert [return 0;]@71", "Update [c]@38 -> [c1]@38", "Insert [p]@68"); } [Fact] public void CasePattern_UpdateDelete() { var src1 = @" switch(shape) { case Point p: return 0; case Circle c: A(c); break; default: return 4; } "; var src2 = @" switch(shape) { case Circle c1: A(c1); break; default: return 4; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c: A(c); break;]@55 -> [case Circle c1: A(c1); break;]@26", "Update [A(c);]@70 -> [A(c1);]@42", "Update [c]@67 -> [c1]@38", "Delete [case Point p: return 0;]@26", "Delete [case Point p:]@26", "Delete [p]@37", "Delete [return 0;]@40"); } [Fact] public void WhenCondition_Update() { var src1 = @" switch(shape) { case Circle c when (c < 10): return 1; case Circle c when (c > 100): return 2; } "; var src2 = @" switch(shape) { case Circle c when (c < 5): return 1; case Circle c2 when (c2 > 100): return 2; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c when (c < 10): return 1;]@26 -> [case Circle c when (c < 5): return 1;]@26", "Update [case Circle c when (c > 100): return 2;]@70 -> [case Circle c2 when (c2 > 100): return 2;]@69", "Update [when (c < 10)]@40 -> [when (c < 5)]@40", "Update [c]@82 -> [c2]@81", "Update [when (c > 100)]@84 -> [when (c2 > 100)]@84"); } [Fact] public void CasePatternWithWhenCondition_UpdateReorder() { var src1 = @" switch(shape) { case Rectangle r: return 0; case Circle c when (c.Radius < 10): return 1; case Circle c when (c.Radius > 100): return 2; } "; var src2 = @" switch(shape) { case Circle c when (c.Radius > 99): return 2; case Circle c when (c.Radius < 10): return 1; case Rectangle r: return 0; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [case Circle c when (c.Radius < 10): return 1;]@59 -> @77", "Reorder [case Circle c when (c.Radius > 100): return 2;]@110 -> @26", "Update [case Circle c when (c.Radius > 100): return 2;]@110 -> [case Circle c when (c.Radius > 99): return 2;]@26", "Move [c]@71 -> @38", "Update [when (c.Radius > 100)]@124 -> [when (c.Radius > 99)]@40", "Move [c]@122 -> @89"); } #endregion #region Ref [Fact] public void Ref_Update() { var src1 = @" ref int a = ref G(new int[] { 1, 2 }); ref int G(int[] p) { return ref p[1]; } "; var src2 = @" ref int32 a = ref G1(new int[] { 1, 2 }); ref int G1(int[] p) { return ref p[2]; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int G(int[] p) { return ref p[1]; }]@44 -> [ref int G1(int[] p) { return ref p[2]; }]@47", "Update [ref int a = ref G(new int[] { 1, 2 })]@4 -> [ref int32 a = ref G1(new int[] { 1, 2 })]@4", "Update [a = ref G(new int[] { 1, 2 })]@12 -> [a = ref G1(new int[] { 1, 2 })]@14"); } [Fact] public void Ref_Insert() { var src1 = @" int a = G(new int[] { 1, 2 }); int G(int[] p) { return p[1]; } "; var src2 = @" ref int32 a = ref G1(new int[] { 1, 2 }); ref int G1(int[] p) { return ref p[2]; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int G(int[] p) { return p[1]; }]@36 -> [ref int G1(int[] p) { return ref p[2]; }]@47", "Update [int a = G(new int[] { 1, 2 })]@4 -> [ref int32 a = ref G1(new int[] { 1, 2 })]@4", "Update [a = G(new int[] { 1, 2 })]@8 -> [a = ref G1(new int[] { 1, 2 })]@14"); } [Fact] public void Ref_Delete() { var src1 = @" ref int a = ref G(new int[] { 1, 2 }); ref int G(int[] p) { return ref p[1]; } "; var src2 = @" int32 a = G1(new int[] { 1, 2 }); int G1(int[] p) { return p[2]; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int G(int[] p) { return ref p[1]; }]@44 -> [int G1(int[] p) { return p[2]; }]@39", "Update [ref int a = ref G(new int[] { 1, 2 })]@4 -> [int32 a = G1(new int[] { 1, 2 })]@4", "Update [a = ref G(new int[] { 1, 2 })]@12 -> [a = G1(new int[] { 1, 2 })]@10"); } #endregion #region Tuples [Fact] public void TupleType_LocalVariables() { var src1 = @" (int a, string c) x = (a, string2); (int a, int b) y = (3, 4); (int a, int b, int c) z = (5, 6, 7); "; var src2 = @" (int a, int b) x = (a, string2); (int a, int b, string c) z1 = (5, 6, 7); (int a, int b) y2 = (3, 4); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [(int a, int b, int c) z = (5, 6, 7);]@69 -> @39", "Update [(int a, string c) x = (a, string2)]@4 -> [(int a, int b) x = (a, string2)]@4", "Update [(int a, int b, int c) z = (5, 6, 7)]@69 -> [(int a, int b, string c) z1 = (5, 6, 7)]@39", "Update [z = (5, 6, 7)]@91 -> [z1 = (5, 6, 7)]@64", "Update [y = (3, 4)]@56 -> [y2 = (3, 4)]@96"); } [Fact] public void TupleElementName() { var src1 = @"class C { (int a, int b) F(); }"; var src2 = @"class C { (int x, int b) F(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a, int b) F();]@10 -> [(int x, int b) F();]@10"); } [Fact] public void TupleInField() { var src1 = @"class C { private (int, int) _x = (1, 2); }"; var src2 = @"class C { private (int, string) _y = (1, 2); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) _x = (1, 2)]@18 -> [(int, string) _y = (1, 2)]@18", "Update [_x = (1, 2)]@29 -> [_y = (1, 2)]@32"); } [Fact] public void TupleInProperty() { var src1 = @"class C { public (int, int) Property1 { get { return (1, 2); } } }"; var src2 = @"class C { public (int, string) Property2 { get { return (1, string.Empty); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public (int, int) Property1 { get { return (1, 2); } }]@10 -> [public (int, string) Property2 { get { return (1, string.Empty); } }]@10", "Update [get { return (1, 2); }]@40 -> [get { return (1, string.Empty); }]@43"); } [Fact] public void TupleInDelegate() { var src1 = @"public delegate void EventHandler1((int, int) x);"; var src2 = @"public delegate void EventHandler2((int, int) y);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void EventHandler1((int, int) x);]@0 -> [public delegate void EventHandler2((int, int) y);]@0", "Update [(int, int) x]@35 -> [(int, int) y]@35"); } #endregion #region With Expressions [Fact] public void WithExpression_PropertyAdd() { var src1 = @"var x = y with { X = 1 };"; var src2 = @"var x = y with { X = 1, Y = 2 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1 }]@6 -> [x = y with { X = 1, Y = 2 }]@6"); } [Fact] public void WithExpression_PropertyDelete() { var src1 = @"var x = y with { X = 1, Y = 2 };"; var src2 = @"var x = y with { X = 1 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 2 }]@6 -> [x = y with { X = 1 }]@6"); } [Fact] public void WithExpression_PropertyChange() { var src1 = @"var x = y with { X = 1 };"; var src2 = @"var x = y with { Y = 1 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1 }]@6 -> [x = y with { Y = 1 }]@6"); } [Fact] public void WithExpression_PropertyValueChange() { var src1 = @"var x = y with { X = 1, Y = 1 };"; var src2 = @"var x = y with { X = 1, Y = 2 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 1 }]@6 -> [x = y with { X = 1, Y = 2 }]@6"); } [Fact] public void WithExpression_PropertyValueReorder() { var src1 = @"var x = y with { X = 1, Y = 1 };"; var src2 = @"var x = y with { Y = 1, X = 1 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 1 }]@6 -> [x = y with { Y = 1, X = 1 }]@6"); } #endregion #region Top Level Statements [Fact] public void TopLevelStatement_CaptureArgs() { var src1 = @" using System; var x = new Func<string>(() => ""Hello""); Console.WriteLine(x()); "; var src2 = @" using System; var x = new Func<string>(() => ""Hello"" + args[0]); Console.WriteLine(x()); "; var edits = GetTopEdits(src1, src2); // TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "using System;\r\n\r\nvar x = new Func<string>(() => \"Hello\" + args[0]);\r\n\r\nConsole.WriteLine(x());\r\n", "args")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void TopLevelStatement_InsertMultiScopeCapture() { var src1 = @" using System; foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; } "; var src2 = @" using System; foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; int f2(int a) => x0 + x1; // error: connecting previously disconnected closures } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1")); } #endregion } }
// 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. #nullable disable using System.IO; using System.Linq; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EditAndContinue; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class StatementEditingTests : EditingTestBase { #region Strings [Fact] public void StringLiteral_update() { var src1 = @" var x = ""Hello1""; "; var src2 = @" var x = ""Hello2""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = \"Hello1\"]@8 -> [x = \"Hello2\"]@8"); } [Fact] public void InterpolatedStringText_update() { var src1 = @" var x = $""Hello1""; "; var src2 = @" var x = $""Hello2""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello1\"]@8 -> [x = $\"Hello2\"]@8"); } [Fact] public void Interpolation_update() { var src1 = @" var x = $""Hello{123}""; "; var src2 = @" var x = $""Hello{124}""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello{123}\"]@8 -> [x = $\"Hello{124}\"]@8"); } [Fact] public void InterpolationFormatClause_update() { var src1 = @" var x = $""Hello{123:N1}""; "; var src2 = @" var x = $""Hello{123:N2}""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello{123:N1}\"]@8 -> [x = $\"Hello{123:N2}\"]@8"); } #endregion #region Variable Declaration [Fact] public void VariableDeclaration_Insert() { var src1 = "if (x == 1) { x++; }"; var src2 = "var x = 1; if (x == 1) { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [var x = 1;]@2", "Insert [var x = 1]@2", "Insert [x = 1]@6"); } [Fact] public void VariableDeclaration_Update() { var src1 = "int x = F(1), y = G(2);"; var src2 = "int x = F(3), y = G(4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x = F(1)]@6 -> [x = F(3)]@6", "Update [y = G(2)]@16 -> [y = G(4)]@16"); } [Fact] public void ParenthesizedVariableDeclaration_Update() { var src1 = @" var (x1, (x2, x3)) = (1, (2, true)); var (a1, a2) = (1, () => { return 7; }); "; var src2 = @" var (x1, (x2, x4)) = (1, (2, true)); var (a1, a3) = (1, () => { return 8; }); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x3]@18 -> [x4]@18", "Update [a2]@51 -> [a3]@51"); } [Fact] public void ParenthesizedVariableDeclaration_Insert() { var src1 = @"var (z1, z2) = (1, 2);"; var src2 = @"var (z1, z2, z3) = (1, 2, 5);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (z1, z2) = (1, 2);]@2 -> [var (z1, z2, z3) = (1, 2, 5);]@2", "Insert [z3]@15"); } [Fact] public void ParenthesizedVariableDeclaration_Delete() { var src1 = @"var (y1, y2, y3) = (1, 2, 7);"; var src2 = @"var (y1, y2) = (1, 4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (y1, y2, y3) = (1, 2, 7);]@2 -> [var (y1, y2) = (1, 4);]@2", "Delete [y3]@15"); } [Fact] public void ParenthesizedVariableDeclaration_Insert_Mixed1() { var src1 = @"int a; (var z1, a) = (1, 2);"; var src2 = @"int a; (var z1, a, var z3) = (1, 2, 5);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var z1, a) = (1, 2);]@9 -> [(var z1, a, var z3) = (1, 2, 5);]@9", "Insert [z3]@25"); } [Fact] public void ParenthesizedVariableDeclaration_Insert_Mixed2() { var src1 = @"int a; (var z1, var z2) = (1, 2);"; var src2 = @"int a; (var z1, var z2, a) = (1, 2, 5);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var z1, var z2) = (1, 2);]@9 -> [(var z1, var z2, a) = (1, 2, 5);]@9"); } [Fact] public void ParenthesizedVariableDeclaration_Delete_Mixed1() { var src1 = @"int a; (var y1, var y2, a) = (1, 2, 7);"; var src2 = @"int a; (var y1, var y2) = (1, 4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var y1, var y2, a) = (1, 2, 7);]@9 -> [(var y1, var y2) = (1, 4);]@9"); } [Fact] public void ParenthesizedVariableDeclaration_Delete_Mixed2() { var src1 = @"int a; (var y1, a, var y3) = (1, 2, 7);"; var src2 = @"int a; (var y1, a) = (1, 4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var y1, a, var y3) = (1, 2, 7);]@9 -> [(var y1, a) = (1, 4);]@9", "Delete [y3]@25"); } [Fact] public void VariableDeclaraions_Reorder() { var src1 = @"var (a, b) = (1, 2); var (c, d) = (3, 4);"; var src2 = @"var (c, d) = (3, 4); var (a, b) = (1, 2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [var (c, d) = (3, 4);]@23 -> @2"); } [Fact] public void VariableDeclaraions_Reorder_Mixed() { var src1 = @"int a; (a, int b) = (1, 2); (int c, int d) = (3, 4);"; var src2 = @"int a; (int c, int d) = (3, 4); (a, int b) = (1, 2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [(int c, int d) = (3, 4);]@30 -> @9"); } [Fact] public void VariableNames_Reorder() { var src1 = @"var (a, b) = (1, 2);"; var src2 = @"var (b, a) = (2, 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (a, b) = (1, 2);]@2 -> [var (b, a) = (2, 1);]@2", "Reorder [b]@10 -> @7"); } [Fact] public void VariableNames_Reorder_Mixed() { var src1 = @"int a; (a, int b) = (1, 2);"; var src2 = @"int a; (int b, a) = (2, 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(a, int b) = (1, 2);]@9 -> [(int b, a) = (2, 1);]@9"); } [Fact] public void VariableNamesAndDeclaraions_Reorder() { var src1 = @"var (a, b) = (1, 2); var (c, d) = (3, 4);"; var src2 = @"var (d, c) = (3, 4); var (a, b) = (1, 2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [var (c, d) = (3, 4);]@23 -> @2", "Reorder [d]@31 -> @7"); } [Fact] public void ParenthesizedVariableDeclaration_Reorder() { var src1 = @"var (a, (b, c)) = (1, (2, 3));"; var src2 = @"var ((b, c), a) = ((2, 3), 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((b, c), a) = ((2, 3), 1);]@2", "Reorder [a]@7 -> @15"); } [Fact] public void ParenthesizedVariableDeclaration_DoubleReorder() { var src1 = @"var (a, (b, c)) = (1, (2, 3));"; var src2 = @"var ((c, b), a) = ((2, 3), 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((c, b), a) = ((2, 3), 1);]@2", "Reorder [b]@11 -> @11", "Reorder [c]@14 -> @8"); } [Fact] public void ParenthesizedVariableDeclaration_ComplexReorder() { var src1 = @"var (a, (b, c)) = (1, (2, 3)); var (x, (y, z)) = (4, (5, 6));"; var src2 = @"var (x, (y, z)) = (4, (5, 6)); var ((c, b), a) = (1, (2, 3)); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [var (x, (y, z)) = (4, (5, 6));]@33 -> @2", "Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((c, b), a) = (1, (2, 3));]@33", "Reorder [b]@11 -> @42", "Reorder [c]@14 -> @39"); } #endregion #region Switch Statement [Fact] public void Switch1() { var src1 = "switch (a) { case 1: f(); break; } switch (b) { case 2: g(); break; }"; var src2 = "switch (b) { case 2: f(); break; } switch (a) { case 1: g(); break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [switch (b) { case 2: g(); break; }]@37 -> @2", "Update [case 1: f(); break;]@15 -> [case 2: f(); break;]@15", "Move [case 1: f(); break;]@15 -> @15", "Update [case 2: g(); break;]@50 -> [case 1: g(); break;]@50", "Move [case 2: g(); break;]@50 -> @50"); } [Fact] public void Switch_Case_Reorder() { var src1 = "switch (expr) { case 1: f(); break; case 2: case 3: case 4: g(); break; }"; var src2 = "switch (expr) { case 2: case 3: case 4: g(); break; case 1: f(); break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [case 2: case 3: case 4: g(); break;]@40 -> @18"); } [Fact] public void Switch_Case_Update() { var src1 = "switch (expr) { case 1: f(); break; }"; var src2 = "switch (expr) { case 2: f(); break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: f(); break;]@18 -> [case 2: f(); break;]@18"); } [Fact] public void CasePatternLabel_UpdateDelete() { var src1 = @" switch(shape) { case Point p: return 0; case Circle c: return 1; } "; var src2 = @" switch(shape) { case Circle circle: return 1; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c: return 1;]@55 -> [case Circle circle: return 1;]@26", "Update [c]@67 -> [circle]@38", "Delete [case Point p: return 0;]@26", "Delete [case Point p:]@26", "Delete [p]@37", "Delete [return 0;]@40"); } #endregion #region Switch Expression [Fact] public void MethodUpdate_UpdateSwitchExpression1() { var src1 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 1 }; }"; var src2 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 2 }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, _ => 2 };]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateSwitchExpression2() { var src1 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 1 }; }"; var src2 = @" class C { static int F(int a) => a switch { 1 => 0, _ => 2 }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 1 => 0, _ => 2 };]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateSwitchExpression3() { var src1 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 1 }; }"; var src2 = @" class C { static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 };]@18"); edits.VerifyRudeDiagnostics(); } #endregion #region Try Catch Finally [Fact] public void TryInsert1() { var src1 = "x++;"; var src2 = "try { x++; } catch { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { x++; } catch { }]@2", "Insert [{ x++; }]@6", "Insert [catch { }]@15", "Move [x++;]@2 -> @8", "Insert [{ }]@21"); } [Fact] public void TryInsert2() { var src1 = "{ x++; }"; var src2 = "try { x++; } catch { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { x++; } catch { }]@2", "Move [{ x++; }]@2 -> @6", "Insert [catch { }]@15", "Insert [{ }]@21"); } [Fact] public void TryDelete1() { var src1 = "try { x++; } catch { }"; var src2 = "x++;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [x++;]@8 -> @2", "Delete [try { x++; } catch { }]@2", "Delete [{ x++; }]@6", "Delete [catch { }]@15", "Delete [{ }]@21"); } [Fact] public void TryDelete2() { var src1 = "try { x++; } catch { }"; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ x++; }]@6 -> @2", "Delete [try { x++; } catch { }]@2", "Delete [catch { }]@15", "Delete [{ }]@21"); } [Fact] public void TryReorder() { var src1 = "try { x++; } catch { /*1*/ } try { y++; } catch { /*2*/ }"; var src2 = "try { y++; } catch { /*2*/ } try { x++; } catch { /*1*/ } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [try { y++; } catch { /*2*/ }]@31 -> @2"); } [Fact] public void Finally_DeleteHeader() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } finally { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*3*/ }]@47 -> @39", "Delete [finally { /*3*/ }]@39"); } [Fact] public void Finally_InsertHeader() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [finally { /*3*/ }]@39", "Move [{ /*3*/ }]@39 -> @47"); } [Fact] public void CatchUpdate() { var src1 = "try { } catch (Exception e) { }"; var src2 = "try { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(Exception e)]@16 -> [(IOException e)]@16"); } [Fact] public void CatchInsert() { var src1 = "try { /*1*/ } catch (Exception e) { /*2*/ } "; var src2 = "try { /*1*/ } catch (IOException e) { /*3*/ } catch (Exception e) { /*2*/ } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch (IOException e) { /*3*/ }]@16", "Insert [(IOException e)]@22", "Insert [{ /*3*/ }]@38"); } [Fact] public void CatchBodyUpdate() { var src1 = "try { } catch (E e) { x++; }"; var src2 = "try { } catch (E e) { y++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x++;]@24 -> [y++;]@24"); } [Fact] public void CatchDelete() { var src1 = "try { } catch (IOException e) { } catch (Exception e) { } "; var src2 = "try { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [catch (Exception e) { }]@36", "Delete [(Exception e)]@42", "Delete [{ }]@56"); } [Fact] public void CatchReorder1() { var src1 = "try { } catch (IOException e) { } catch (Exception e) { } "; var src2 = "try { } catch (Exception e) { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [catch (Exception e) { }]@36 -> @10"); } [Fact] public void CatchReorder2() { var src1 = "try { } catch (IOException e) { } catch (Exception e) { } catch { }"; var src2 = "try { } catch (A e) { } catch (Exception e) { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [catch (Exception e) { }]@36 -> @26", "Reorder [catch { }]@60 -> @10", "Insert [(A e)]@16"); } [Fact] public void CatchFilterReorder2() { var src1 = "try { } catch (Exception e) when (e != null) { } catch (Exception e) { } catch { }"; var src2 = "try { } catch when (s == 1) { } catch (Exception e) { } catch (Exception e) when (e != null) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [catch (Exception e) { }]@51 -> @34", "Reorder [catch { }]@75 -> @10", "Insert [when (s == 1)]@16"); } [Fact] public void CatchInsertDelete() { var src1 = @" try { x++; } catch (E e) { /*1*/ } catch (Exception e) { /*2*/ } try { Console.WriteLine(); } finally { /*3*/ }"; var src2 = @" try { x++; } catch (Exception e) { /*2*/ } try { Console.WriteLine(); } catch (E e) { /*1*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch (E e) { /*1*/ }]@79", "Insert [(E e)]@85", "Move [{ /*1*/ }]@29 -> @91", "Delete [catch (E e) { /*1*/ }]@17", "Delete [(E e)]@23"); } [Fact] public void Catch_DeleteHeader1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch (E2 e) { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*3*/ }]@52 -> @39", "Delete [catch (E2 e) { /*3*/ }]@39", "Delete [(E2 e)]@45"); } [Fact] public void Catch_InsertHeader1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch (E2 e) { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch (E2 e) { /*3*/ }]@39", "Insert [(E2 e)]@45", "Move [{ /*3*/ }]@39 -> @52"); } [Fact] public void Catch_DeleteHeader2() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*3*/ }]@45 -> @39", "Delete [catch { /*3*/ }]@39"); } [Fact] public void Catch_InsertHeader2() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch { /*3*/ }]@39", "Move [{ /*3*/ }]@39 -> @45"); } [Fact] public void Catch_InsertFilter1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [when (e == null)]@29"); } [Fact] public void Catch_InsertFilter2() { var src1 = "try { /*1*/ } catch when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [(E1 e)]@22"); } [Fact] public void Catch_InsertFilter3() { var src1 = "try { /*1*/ } catch { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [(E1 e)]@22", "Insert [when (e == null)]@29"); } [Fact] public void Catch_DeleteDeclaration1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ }"; var src2 = "try { /*1*/ } catch { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [(E1 e)]@22"); } [Fact] public void Catch_DeleteFilter1() { var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [when (e == null)]@29"); } [Fact] public void Catch_DeleteFilter2() { var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [(E1 e)]@22"); } [Fact] public void Catch_DeleteFilter3() { var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [(E1 e)]@22", "Delete [when (e == null)]@29"); } [Fact] public void TryCatchFinally_DeleteHeader() { var src1 = "try { /*1*/ } catch { /*2*/ } finally { /*3*/ }"; var src2 = "{ /*1*/ } { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*1*/ }]@6 -> @2", "Move [{ /*2*/ }]@22 -> @12", "Move [{ /*3*/ }]@40 -> @22", "Delete [try { /*1*/ } catch { /*2*/ } finally { /*3*/ }]@2", "Delete [catch { /*2*/ }]@16", "Delete [finally { /*3*/ }]@32"); } [Fact] public void TryCatchFinally_InsertHeader() { var src1 = "{ /*1*/ } { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch { /*2*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { /*1*/ } catch { /*2*/ } finally { /*3*/ }]@2", "Move [{ /*1*/ }]@2 -> @6", "Insert [catch { /*2*/ }]@16", "Insert [finally { /*3*/ }]@32", "Move [{ /*2*/ }]@12 -> @22", "Move [{ /*3*/ }]@22 -> @40"); } [Fact] public void TryFilterFinally_InsertHeader() { var src1 = "{ /*1*/ } if (a == 1) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch when (a == 1) { /*2*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { /*1*/ } catch when (a == 1) { /*2*/ } finally { /*3*/ }]@2", "Move [{ /*1*/ }]@2 -> @6", "Insert [catch when (a == 1) { /*2*/ }]@16", "Insert [finally { /*3*/ }]@46", "Insert [when (a == 1)]@22", "Move [{ /*2*/ }]@24 -> @36", "Move [{ /*3*/ }]@34 -> @54", "Delete [if (a == 1) { /*2*/ }]@12"); } #endregion #region Blocks [Fact] public void Block_Insert() { var src1 = ""; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [{ x++; }]@2", "Insert [x++;]@4"); } [Fact] public void Block_Delete() { var src1 = "{ x++; }"; var src2 = ""; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [{ x++; }]@2", "Delete [x++;]@4"); } [Fact] public void Block_Reorder() { var src1 = "{ x++; } { y++; }"; var src2 = "{ y++; } { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [{ y++; }]@11 -> @2"); } [Fact] public void Block_AddLine() { var src1 = "{ x++; }"; var src2 = @"{ // x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(); } #endregion #region Checked/Unchecked [Fact] public void Checked_Insert() { var src1 = ""; var src2 = "checked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [checked { x++; }]@2", "Insert [{ x++; }]@10", "Insert [x++;]@12"); } [Fact] public void Checked_Delete() { var src1 = "checked { x++; }"; var src2 = ""; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [checked { x++; }]@2", "Delete [{ x++; }]@10", "Delete [x++;]@12"); } [Fact] public void Checked_Update() { var src1 = "checked { x++; }"; var src2 = "unchecked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [checked { x++; }]@2 -> [unchecked { x++; }]@2"); } [Fact] public void Checked_DeleteHeader() { var src1 = "checked { x++; }"; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ x++; }]@10 -> @2", "Delete [checked { x++; }]@2"); } [Fact] public void Checked_InsertHeader() { var src1 = "{ x++; }"; var src2 = "checked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [checked { x++; }]@2", "Move [{ x++; }]@2 -> @10"); } [Fact] public void Unchecked_InsertHeader() { var src1 = "{ x++; }"; var src2 = "unchecked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [unchecked { x++; }]@2", "Move [{ x++; }]@2 -> @12"); } #endregion #region Unsafe [Fact] public void Unsafe_Insert() { var src1 = ""; var src2 = "unsafe { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [unsafe { x++; }]@2", "Insert [{ x++; }]@9", "Insert [x++;]@11"); } [Fact] public void Unsafe_Delete() { var src1 = "unsafe { x++; }"; var src2 = ""; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [unsafe { x++; }]@2", "Delete [{ x++; }]@9", "Delete [x++;]@11"); } [Fact] public void Unsafe_DeleteHeader() { var src1 = "unsafe { x++; }"; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ x++; }]@9 -> @2", "Delete [unsafe { x++; }]@2"); } [Fact] public void Unsafe_InsertHeader() { var src1 = "{ x++; }"; var src2 = "unsafe { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [unsafe { x++; }]@2", "Move [{ x++; }]@2 -> @9"); } #endregion #region Using Statement [Fact] public void Using1() { var src1 = @"using (a) { using (b) { Goo(); } }"; var src2 = @"using (a) { using (c) { using (b) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [using (c) { using (b) { Goo(); } }]@14", "Insert [{ using (b) { Goo(); } }]@24", "Move [using (b) { Goo(); }]@14 -> @26"); } [Fact] public void Using_DeleteHeader() { var src1 = @"using (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@12 -> @2", "Delete [using (a) { Goo(); }]@2"); } [Fact] public void Using_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"using (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [using (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @12"); } #endregion #region Lock Statement [Fact] public void Lock1() { var src1 = @"lock (a) { lock (b) { Goo(); } }"; var src2 = @"lock (a) { lock (c) { lock (b) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [lock (c) { lock (b) { Goo(); } }]@13", "Insert [{ lock (b) { Goo(); } }]@22", "Move [lock (b) { Goo(); }]@13 -> @24"); } [Fact] public void Lock_DeleteHeader() { var src1 = @"lock (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@11 -> @2", "Delete [lock (a) { Goo(); }]@2"); } [Fact] public void Lock_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"lock (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [lock (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @11"); } #endregion #region ForEach Statement [Fact] public void ForEach1() { var src1 = @"foreach (var a in e) { foreach (var b in f) { Goo(); } }"; var src2 = @"foreach (var a in e) { foreach (var c in g) { foreach (var b in f) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [foreach (var c in g) { foreach (var b in f) { Goo(); } }]@25", "Insert [{ foreach (var b in f) { Goo(); } }]@46", "Move [foreach (var b in f) { Goo(); }]@25 -> @48"); var actual = ToMatchingPairs(edits.Match); var expected = new MatchingPairs { { "foreach (var a in e) { foreach (var b in f) { Goo(); } }", "foreach (var a in e) { foreach (var c in g) { foreach (var b in f) { Goo(); } } }" }, { "{ foreach (var b in f) { Goo(); } }", "{ foreach (var c in g) { foreach (var b in f) { Goo(); } } }" }, { "foreach (var b in f) { Goo(); }", "foreach (var b in f) { Goo(); }" }, { "{ Goo(); }", "{ Goo(); }" }, { "Goo();", "Goo();" } }; expected.AssertEqual(actual); } [Fact] public void ForEach_Swap1() { var src1 = @"foreach (var a in e) { foreach (var b in f) { Goo(); } }"; var src2 = @"foreach (var b in f) { foreach (var a in e) { Goo(); } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [foreach (var b in f) { Goo(); }]@25 -> @2", "Move [foreach (var a in e) { foreach (var b in f) { Goo(); } }]@2 -> @25", "Move [Goo();]@48 -> @48"); var actual = ToMatchingPairs(edits.Match); var expected = new MatchingPairs { { "foreach (var a in e) { foreach (var b in f) { Goo(); } }", "foreach (var a in e) { Goo(); }" }, { "{ foreach (var b in f) { Goo(); } }", "{ Goo(); }" }, { "foreach (var b in f) { Goo(); }", "foreach (var b in f) { foreach (var a in e) { Goo(); } }" }, { "{ Goo(); }", "{ foreach (var a in e) { Goo(); } }" }, { "Goo();", "Goo();" } }; expected.AssertEqual(actual); } [Fact] public void Foreach_DeleteHeader() { var src1 = @"foreach (var a in b) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@23 -> @2", "Delete [foreach (var a in b) { Goo(); }]@2"); } [Fact] public void Foreach_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"foreach (var a in b) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [foreach (var a in b) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @23"); } [Fact] public void ForeachVariable_Update1() { var src1 = @" foreach (var (a1, a2) in e) { } foreach ((var b1, var b2) in e) { } foreach (var a in e1) { } "; var src2 = @" foreach (var (a1, a3) in e) { } foreach ((var b3, int b2) in e) { } foreach (_ in e1) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach ((var b1, var b2) in e) { }]@37 -> [foreach ((var b3, int b2) in e) { }]@37", "Update [foreach (var a in e1) { }]@74 -> [foreach (_ in e1) { }]@74", "Update [a2]@22 -> [a3]@22", "Update [b1]@51 -> [b3]@51"); } [Fact] public void ForeachVariable_Update2() { var src1 = @" foreach (_ in e2) { } foreach (_ in e3) { A(); } "; var src2 = @" foreach (var b in e2) { } foreach (_ in e4) { A(); } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach (_ in e2) { }]@4 -> [foreach (var b in e2) { }]@4", "Update [foreach (_ in e3) { A(); }]@27 -> [foreach (_ in e4) { A(); }]@31"); } [Fact] public void ForeachVariable_Insert() { var src1 = @" foreach (var (a3, a4) in e) { } foreach ((var b4, var b5) in e) { } "; var src2 = @" foreach (var (a3, a5, a4) in e) { } foreach ((var b6, var b4, var b5) in e) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach (var (a3, a4) in e) { }]@4 -> [foreach (var (a3, a5, a4) in e) { }]@4", "Update [foreach ((var b4, var b5) in e) { }]@37 -> [foreach ((var b6, var b4, var b5) in e) { }]@41", "Insert [a5]@22", "Insert [b6]@55"); } [Fact] public void ForeachVariable_Delete() { var src1 = @" foreach (var (a11, a12, a13) in e) { F(); } foreach ((var b7, var b8, var b9) in e) { G(); } "; var src2 = @" foreach (var (a12, a13) in e1) { F(); } foreach ((var b7, var b9) in e) { G(); } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach (var (a11, a12, a13) in e) { F(); }]@4 -> [foreach (var (a12, a13) in e1) { F(); }]@4", "Update [foreach ((var b7, var b8, var b9) in e) { G(); }]@49 -> [foreach ((var b7, var b9) in e) { G(); }]@45", "Delete [a11]@18", "Delete [b8]@71"); } [Fact] public void ForeachVariable_Reorder() { var src1 = @" foreach (var (a, b) in e1) { } foreach ((var x, var y) in e2) { } "; var src2 = @" foreach ((var x, var y) in e2) { } foreach (var (a, b) in e1) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [foreach ((var x, var y) in e2) { }]@36 -> @4"); } [Fact] public void ForeachVariableEmbedded_Reorder() { var src1 = @" foreach (var (a, b) in e1) { foreach ((var x, var y) in e2) { } } "; var src2 = @" foreach ((var x, var y) in e2) { } foreach (var (a, b) in e1) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [foreach ((var x, var y) in e2) { }]@39 -> @4"); } #endregion #region For Statement [Fact] public void For1() { var src1 = @"for (int a = 0; a < 10; a++) { for (int a = 0; a < 20; a++) { Goo(); } }"; var src2 = @"for (int a = 0; a < 10; a++) { for (int b = 0; b < 10; b++) { for (int a = 0; a < 20; a++) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [for (int b = 0; b < 10; b++) { for (int a = 0; a < 20; a++) { Goo(); } }]@33", "Insert [int b = 0]@38", "Insert [b < 10]@49", "Insert [b++]@57", "Insert [{ for (int a = 0; a < 20; a++) { Goo(); } }]@62", "Insert [b = 0]@42", "Move [for (int a = 0; a < 20; a++) { Goo(); }]@33 -> @64"); } [Fact] public void For_DeleteHeader() { var src1 = @"for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@43 -> @2", "Delete [for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }]@2", "Delete [int i = 10, j = 0]@7", "Delete [i = 10]@11", "Delete [j = 0]@19", "Delete [i > j]@26", "Delete [i--]@33", "Delete [j++]@38"); } [Fact] public void For_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }]@2", "Insert [int i = 10, j = 0]@7", "Insert [i > j]@26", "Insert [i--]@33", "Insert [j++]@38", "Move [{ Goo(); }]@2 -> @43", "Insert [i = 10]@11", "Insert [j = 0]@19"); } [Fact] public void For_DeclaratorsToInitializers() { var src1 = @"for (var i = 10; i < 10; i++) { }"; var src2 = @"for (i = 10; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [i = 10]@7", "Delete [var i = 10]@7", "Delete [i = 10]@11"); } [Fact] public void For_InitializersToDeclarators() { var src1 = @"for (i = 10, j = 0; i < 10; i++) { }"; var src2 = @"for (var i = 10, j = 0; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [var i = 10, j = 0]@7", "Insert [i = 10]@11", "Insert [j = 0]@19", "Delete [i = 10]@7", "Delete [j = 0]@15"); } [Fact] public void For_Declarations_Reorder() { var src1 = @"for (var i = 10, j = 0; i > j; i++, j++) { }"; var src2 = @"for (var j = 0, i = 10; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Reorder [j = 0]@19 -> @11"); } [Fact] public void For_Declarations_Insert() { var src1 = @"for (var i = 0, j = 1; i > j; i++, j++) { }"; var src2 = @"for (var i = 0, j = 1, k = 2; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var i = 0, j = 1]@7 -> [var i = 0, j = 1, k = 2]@7", "Insert [k = 2]@25"); } [Fact] public void For_Declarations_Delete() { var src1 = @"for (var i = 0, j = 1, k = 2; i > j; i++, j++) { }"; var src2 = @"for (var i = 0, j = 1; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var i = 0, j = 1, k = 2]@7 -> [var i = 0, j = 1]@7", "Delete [k = 2]@25"); } [Fact] public void For_Initializers_Reorder() { var src1 = @"for (i = 10, j = 0; i > j; i++, j++) { }"; var src2 = @"for (j = 0, i = 10; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Reorder [j = 0]@15 -> @7"); } [Fact] public void For_Initializers_Insert() { var src1 = @"for (i = 10; i < 10; i++) { }"; var src2 = @"for (i = 10, j = 0; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Insert [j = 0]@15"); } [Fact] public void For_Initializers_Delete() { var src1 = @"for (i = 10, j = 0; i < 10; i++) { }"; var src2 = @"for (i = 10; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Delete [j = 0]@15"); } [Fact] public void For_Initializers_Update() { var src1 = @"for (i = 1; i < 10; i++) { }"; var src2 = @"for (i = 2; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [i = 1]@7 -> [i = 2]@7"); } [Fact] public void For_Initializers_Update_Lambda() { var src1 = @"for (int i = 10, j = F(() => 1); i > j; i++) { }"; var src2 = @"for (int i = 10, j = F(() => 2); i > j; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [() => 1]@25 -> [() => 2]@25"); } [Fact] public void For_Condition_Update() { var src1 = @"for (int i = 0; i < 10; i++) { }"; var src2 = @"for (int i = 0; i < 20; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [i < 10]@18 -> [i < 20]@18"); } [Fact] public void For_Condition_Lambda() { var src1 = @"for (int i = 0; F(() => 1); i++) { }"; var src2 = @"for (int i = 0; F(() => 2); i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [() => 1]@20 -> [() => 2]@20"); } [Fact] public void For_Incrementors_Reorder() { var src1 = @"for (int i = 10, j = 0; i > j; i--, j++) { }"; var src2 = @"for (int i = 10, j = 0; i > j; j++, i--) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Reorder [j++]@38 -> @33"); } [Fact] public void For_Incrementors_Insert() { var src1 = @"for (int i = 10, j = 0; i > j; i--) { }"; var src2 = @"for (int i = 10, j = 0; i > j; j++, i--) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Insert [j++]@33"); } [Fact] public void For_Incrementors_Delete() { var src1 = @"for (int i = 10, j = 0; i > j; j++, i--) { }"; var src2 = @"for (int i = 10, j = 0; i > j; j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Delete [i--]@38"); } [Fact] public void For_Incrementors_Update() { var src1 = @"for (int i = 10, j = 0; i > j; j++) { }"; var src2 = @"for (int i = 10, j = 0; i > j; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [j++]@33 -> [i++]@33"); } [Fact] public void For_Incrementors_Update_Lambda() { var src1 = @"for (int i = 10, j = 0; i > j; F(() => 1)) { }"; var src2 = @"for (int i = 10, j = 0; i > j; F(() => 2)) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [() => 1]@35 -> [() => 2]@35"); } #endregion #region While Statement [Fact] public void While1() { var src1 = @"while (a) { while (b) { Goo(); } }"; var src2 = @"while (a) { while (c) { while (b) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [while (c) { while (b) { Goo(); } }]@14", "Insert [{ while (b) { Goo(); } }]@24", "Move [while (b) { Goo(); }]@14 -> @26"); } [Fact] public void While_DeleteHeader() { var src1 = @"while (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@12 -> @2", "Delete [while (a) { Goo(); }]@2"); } [Fact] public void While_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"while (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [while (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @12"); } #endregion #region Do Statement [Fact] public void Do1() { var src1 = @"do { do { Goo(); } while (b); } while (a);"; var src2 = @"do { do { do { Goo(); } while(b); } while(c); } while(a);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [do { do { Goo(); } while(b); } while(c);]@7", "Insert [{ do { Goo(); } while(b); }]@10", "Move [do { Goo(); } while (b);]@7 -> @12"); } [Fact] public void Do_DeleteHeader() { var src1 = @"do { Goo(); } while (a);"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@5 -> @2", "Delete [do { Goo(); } while (a);]@2"); } [Fact] public void Do_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"do { Goo(); } while (a);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [do { Goo(); } while (a);]@2", "Move [{ Goo(); }]@2 -> @5"); } #endregion #region If Statement [Fact] public void IfStatement_TestExpression_Update() { var src1 = "var x = 1; if (x == 1) { x++; }"; var src2 = "var x = 1; if (x == 2) { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (x == 1) { x++; }]@13 -> [if (x == 2) { x++; }]@13"); } [Fact] public void ElseClause_Insert() { var src1 = "if (x == 1) x++; "; var src2 = "if (x == 1) x++; else y++;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [else y++;]@19", "Insert [y++;]@24"); } [Fact] public void ElseClause_InsertMove() { var src1 = "if (x == 1) x++; else y++;"; var src2 = "if (x == 1) x++; else if (x == 2) y++;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (x == 2) y++;]@24", "Move [y++;]@24 -> @36"); } [Fact] public void If1() { var src1 = @"if (a) if (b) Goo();"; var src2 = @"if (a) if (c) if (b) Goo();"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (c) if (b) Goo();]@9", "Move [if (b) Goo();]@9 -> @16"); } [Fact] public void If_DeleteHeader() { var src1 = @"if (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@9 -> @2", "Delete [if (a) { Goo(); }]@2"); } [Fact] public void If_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"if (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @9"); } [Fact] public void Else_DeleteHeader() { var src1 = @"if (a) { Goo(/*1*/); } else { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(/*2*/); }]@30 -> @25", "Delete [else { Goo(/*2*/); }]@25"); } [Fact] public void Else_InsertHeader() { var src1 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } else { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [else { Goo(/*2*/); }]@25", "Move [{ Goo(/*2*/); }]@25 -> @30"); } [Fact] public void ElseIf_DeleteHeader() { var src1 = @"if (a) { Goo(/*1*/); } else if (b) { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(/*2*/); }]@37 -> @25", "Delete [else if (b) { Goo(/*2*/); }]@25", "Delete [if (b) { Goo(/*2*/); }]@30"); } [Fact] public void ElseIf_InsertHeader() { var src1 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } else if (b) { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [else if (b) { Goo(/*2*/); }]@25", "Insert [if (b) { Goo(/*2*/); }]@30", "Move [{ Goo(/*2*/); }]@25 -> @37"); } [Fact] public void IfElseElseIf_InsertHeader() { var src1 = @"{ /*1*/ } { /*2*/ } { /*3*/ }"; var src2 = @"if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }]@2", "Move [{ /*1*/ }]@2 -> @9", "Insert [else if (b) { /*2*/ } else { /*3*/ }]@19", "Insert [if (b) { /*2*/ } else { /*3*/ }]@24", "Move [{ /*2*/ }]@12 -> @31", "Insert [else { /*3*/ }]@41", "Move [{ /*3*/ }]@22 -> @46"); } [Fact] public void IfElseElseIf_DeleteHeader() { var src1 = @"if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }"; var src2 = @"{ /*1*/ } { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*1*/ }]@9 -> @2", "Move [{ /*2*/ }]@31 -> @12", "Move [{ /*3*/ }]@46 -> @22", "Delete [if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }]@2", "Delete [else if (b) { /*2*/ } else { /*3*/ }]@19", "Delete [if (b) { /*2*/ } else { /*3*/ }]@24", "Delete [else { /*3*/ }]@41"); } #endregion #region Switch Statement [Fact] public void SwitchStatement_Update_Expression() { var src1 = "var x = 1; switch (x + 1) { case 1: break; }"; var src2 = "var x = 1; switch (x + 2) { case 1: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [switch (x + 1) { case 1: break; }]@13 -> [switch (x + 2) { case 1: break; }]@13"); } [Fact] public void SwitchStatement_Update_SectionLabel() { var src1 = "var x = 1; switch (x) { case 1: break; }"; var src2 = "var x = 1; switch (x) { case 2: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: break;]@26 -> [case 2: break;]@26"); } [Fact] public void SwitchStatement_Update_AddSectionLabel() { var src1 = "var x = 1; switch (x) { case 1: break; }"; var src2 = "var x = 1; switch (x) { case 1: case 2: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: break;]@26 -> [case 1: case 2: break;]@26"); } [Fact] public void SwitchStatement_Update_DeleteSectionLabel() { var src1 = "var x = 1; switch (x) { case 1: case 2: break; }"; var src2 = "var x = 1; switch (x) { case 1: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: case 2: break;]@26 -> [case 1: break;]@26"); } [Fact] public void SwitchStatement_Update_BlockInSection() { var src1 = "var x = 1; switch (x) { case 1: { x++; break; } }"; var src2 = "var x = 1; switch (x) { case 1: { x--; break; } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x++;]@36 -> [x--;]@36"); } [Fact] public void SwitchStatement_Update_BlockInDefaultSection() { var src1 = "var x = 1; switch (x) { default: { x++; break; } }"; var src2 = "var x = 1; switch (x) { default: { x--; break; } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x++;]@37 -> [x--;]@37"); } [Fact] public void SwitchStatement_Insert_Section() { var src1 = "var x = 1; switch (x) { case 1: break; }"; var src2 = "var x = 1; switch (x) { case 1: break; case 2: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [case 2: break;]@41", "Insert [break;]@49"); } [Fact] public void SwitchStatement_Delete_Section() { var src1 = "var x = 1; switch (x) { case 1: break; case 2: break; }"; var src2 = "var x = 1; switch (x) { case 1: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [case 2: break;]@41", "Delete [break;]@49"); } #endregion #region Lambdas [Fact] public void Lambdas_AddAttribute() { var src1 = "Func<int, int> x = (a) => a;"; var src2 = "Func<int, int> x = [A][return:A]([A]a) => a;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(a) => a]@21 -> [[A][return:A]([A]a) => a]@21", "Update [a]@22 -> [[A]a]@35"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.method), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.method), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.parameter)); GetTopEdits(edits).VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Lambdas_InVariableDeclarator() { var src1 = "Action x = a => a, y = b => b;"; var src2 = "Action x = (a) => a, y = b => b + 1;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [a => a]@13 -> [(a) => a]@13", "Update [b => b]@25 -> [b => b + 1]@27", "Insert [(a)]@13", "Insert [a]@14", "Delete [a]@13"); } [Fact] public void Lambdas_InExpressionStatement() { var src1 = "F(a => a, b => b);"; var src2 = "F(b => b, a => a+1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [b => b]@12 -> @4", "Update [a => a]@4 -> [a => a+1]@12"); } [Fact] public void Lambdas_ReorderArguments() { var src1 = "F(G(a => {}), G(b => {}));"; var src2 = "F(G(b => {}), G(a => {}));"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [b => {}]@18 -> @6"); } [Fact] public void Lambdas_InWhile() { var src1 = "while (F(a => a)) { /*1*/ }"; var src2 = "do { /*1*/ } while (F(a => a));"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [do { /*1*/ } while (F(a => a));]@2", "Move [{ /*1*/ }]@20 -> @5", "Move [a => a]@11 -> @24", "Delete [while (F(a => a)) { /*1*/ }]@2"); } [Fact] public void Lambdas_InLambda_ChangeInLambdaSignature() { var src1 = "F(() => { G(x => y); });"; var src2 = "F(q => { G(() => y); });"; var edits = GetMethodEdits(src1, src2); // changes were made to the outer lambda signature: edits.VerifyEdits( "Update [() => { G(x => y); }]@4 -> [q => { G(() => y); }]@4", "Insert [q]@4", "Delete [()]@4"); } [Fact] public void Lambdas_InLambda_ChangeOnlyInLambdaBody() { var src1 = "F(() => { G(x => y); });"; var src2 = "F(() => { G(() => y); });"; var edits = GetMethodEdits(src1, src2); // no changes to the method were made, only within the outer lambda body: edits.VerifyEdits(); } [Fact] public void Lambdas_Update_ParameterRefness_NoBodyChange() { var src1 = @"F((ref int a) => a = 1);"; var src2 = @"F((out int a) => a = 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int a]@5 -> [out int a]@5"); } [Fact] public void Lambdas_Insert_Static_Top() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Insert_Static_Nested1() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => G(b => b) + a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Insert_ThisOnly_Top1() { var src1 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { } } "; var src2 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { G(a => x); } } "; var edits = GetTopEdits(src1, src2); // TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291")] public void Lambdas_Insert_ThisOnly_Top2() { var src1 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; var f1 = new Func<int, int>(a => y); } } } "; var src2 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; var f2 = from a in new[] { 1 } select a + y; var f3 = from a in new[] { 1 } where x > 0 select a; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "x", "x")); } [Fact] public void Lambdas_Insert_ThisOnly_Nested1() { var src1 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var src2 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { G(a => G(b => x)); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact] public void Lambdas_Insert_ThisOnly_Nested2() { var src1 = @" using System; class C { int x = 0; void F() { var f1 = new Func<int, int>(a => { var f2 = new Func<int, int>(b => { return b; }); return a; }); } } "; var src2 = @" using System; class C { int x = 0; void F() { var f1 = new Func<int, int>(a => { var f2 = new Func<int, int>(b => { return b; }); var f3 = new Func<int, int>(c => { return c + x; }); return a; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact] public void Lambdas_InsertAndDelete_Scopes1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 G(a => x3 + x1); G(a => x0 + y0 + x2); G(a => x); } } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 G(a => x3 + x1); G(a => x0 + y0 + x2); G(a => x); G(a => x); // OK G(a => x0 + y0); // OK G(a => x1 + y0); // error - connecting Group #1 and Group #2 G(a => x3 + x1); // error - multi-scope (conservative) G(a => x + y0); // error - connecting Group #0 and Group #1 G(a => x + x3); // error - connecting Group #0 and Group #2 } } } } } "; var insert = GetTopEdits(src1, src2); insert.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "y0", "x1"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "x1", "x3"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.lambda, "this", "y0"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "this", "x3")); var delete = GetTopEdits(src2, src1); delete.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "y0", "x1"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "x1", "x3"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.lambda, "this", "y0"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "this", "x3")); } [Fact] public void Lambdas_Insert_ForEach1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); G(a => x0 + x1); // error: connecting previously disconnected closures } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_Insert_ForEach2() { var src1 = @" using System; class C { void G(Func<int, int> f1, Func<int, int> f2, Func<int, int> f3) {} void F() { int x0 = 0; // Group #0 foreach (int x1 in new[] { 1 }) // Group #1 G(a => x0, a => x1, null); } } "; var src2 = @" using System; class C { void G(Func<int, int> f1, Func<int, int> f2, Func<int, int> f3) {} void F() { int x0 = 0; // Group #0 foreach (int x1 in new[] { 1 }) // Group #1 G(a => x0, a => x1, a => x0 + x1); // error: connecting previously disconnected closures } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_Insert_For1() { var src1 = @" using System; class C { bool G(Func<int, int> f) => true; void F() { for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) { int x2 = 0; G(a => x2); } } } "; var src2 = @" using System; class C { bool G(Func<int, int> f) => true; void F() { for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) { int x2 = 0; G(a => x2); G(a => x0 + x1); // ok G(a => x0 + x2); // error: connecting previously disconnected closures } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x2", CSharpFeaturesResources.lambda, "x0", "x2")); } [Fact] public void Lambdas_Insert_Switch1() { var src1 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; G(() => x2); switch (a) { case 1: int x0 = 1; G(() => x0); break; case 2: int x1 = 1; G(() => x1); break; } } } "; var src2 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; G(() => x2); switch (a) { case 1: int x0 = 1; G(() => x0); goto case 2; case 2: int x1 = 1; G(() => x1); goto default; default: x0 = 1; x1 = 2; G(() => x0 + x1); // ok G(() => x0 + x2); // error break; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.lambda, "x2", "x0")); } [Fact] public void Lambdas_Insert_Using1() { var src1 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static IDisposable D() => null; static void F() { using (IDisposable x0 = D(), y0 = D()) { int x1 = 1; G(() => x0); G(() => y0); G(() => x1); } } } "; var src2 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static IDisposable D() => null; static void F() { using (IDisposable x0 = D(), y0 = D()) { int x1 = 1; G(() => x0); G(() => y0); G(() => x1); G(() => F(x0, y0)); // ok G(() => F(x0, x1)); // error } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_Insert_Catch1() { var src1 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static void F() { try { } catch (Exception x0) { int x1 = 1; G(() => x0); G(() => x1); } } } "; var src2 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static void F() { try { } catch (Exception x0) { int x1 = 1; G(() => x0); G(() => x1); G(() => x0); //ok G(() => F(x0, x1)); //error } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact, WorkItem(1504, "https://github.com/dotnet/roslyn/issues/1504")] public void Lambdas_Insert_CatchFilter1() { var src1 = @" using System; class C { static bool G<T>(Func<T> f) => true; static void F() { Exception x1 = null; try { G(() => x1); } catch (Exception x0) when (G(() => x0)) { } } } "; var src2 = @" using System; class C { static bool G<T>(Func<T> f) => true; static void F() { Exception x1 = null; try { G(() => x1); } catch (Exception x0) when (G(() => x0) && G(() => x0) && // ok G(() => x0 != x1)) // error { G(() => x0); // ok } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.lambda, "x1", "x0") ); } [Fact] public void Lambdas_Insert_NotSupported() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Insert_Second_NotSupported() { var src1 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); } } "; var src2 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); var g = new Func<int, int>(b => b); } } "; var capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.NewTypeDefinition; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "b", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Insert_FirstInClass_NotSupported() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { var g = new Func<int, int>(b => b); } } "; var capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.NewTypeDefinition; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities, // TODO: https://github.com/dotnet/roslyn/issues/52759 // This is incorrect, there should be no rude edit reported Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "b", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_CeaseCapture_This() { var src1 = @" using System; class C { int x = 1; void F() { var f = new Func<int, int>(a => a + x); } } "; var src2 = @" using System; class C { int x; void F() { var f = new Func<int, int>(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "F", "this")); } [Fact] public void Lambdas_Update_Signature1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<long, long> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<long, long> f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature2() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int, int> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int, int> f) {} void F() { G2((a, b) => a + b); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(a, b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature3() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, long> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, long> f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_Nullable() { var src1 = @" using System; class C { void G1(Func<string, string> f) {} void G2(Func<string?, string?> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<string, string> f) {} void G2(Func<string?, string?> f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_SyntaxOnly1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G2((a) => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_ReturnType1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Action<int> f) {} void F() { G1(a => { return 1; }); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Action<int> f) {} void F() { G2(a => { }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_ReturnType2() { var src1 = "var x = int (int a) => a;"; var src2 = "var x = long (int a) => a;"; var edits = GetMethodEdits(src1, src2); GetTopEdits(edits).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "(int a)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_BodySyntaxOnly() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G1(a => { return 1; }); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G2(a => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_ParameterName1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G1(a => 1); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G2(b => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_ParameterRefness1() { var src1 = @" using System; delegate int D1(ref int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1((ref int a) => 1); } } "; var src2 = @" using System; delegate int D1(ref int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2((int a) => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(int a)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_ParameterRefness2() { var src1 = @" using System; delegate int D1(ref int a); delegate int D2(out int a); class C { void G(D1 f) {} void G(D2 f) {} void F() { G((ref int a) => a = 1); } } "; var src2 = @" using System; delegate int D1(ref int a); delegate int D2(out int a); class C { void G(D1 f) {} void G(D2 f) {} void F() { G((out int a) => a = 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(out int a)", CSharpFeaturesResources.lambda)); } // Add corresponding test to VB [Fact(Skip = "TODO")] public void Lambdas_Update_Signature_CustomModifiers1() { var delegateSource = @" .class public auto ansi sealed D1 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public newslot virtual instance int32 [] modopt([mscorlib]System.Int64) Invoke( int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed { } } .class public auto ansi sealed D2 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke( int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed { } } .class public auto ansi sealed D3 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke( int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed { } }"; var src1 = @" using System; class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; MetadataReference delegateDefs; using (var tempAssembly = IlasmUtilities.CreateTempAssembly(delegateSource)) { delegateDefs = MetadataReference.CreateFromImage(File.ReadAllBytes(tempAssembly.Path)); } var edits = GetTopEdits(src1, src2); // TODO edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Signature_MatchingErrorType() { var src1 = @" using System; class C { void G(Func<Unknown, Unknown> f) {} void F() { G(a => 1); } } "; var src2 = @" using System; class C { void G(Func<Unknown, Unknown> f) {} void F() { G(a => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("F").Single(), preserveLocalVariables: true) }); } [Fact] public void Lambdas_Signature_NonMatchingErrorType() { var src1 = @" using System; class C { void G1(Func<Unknown1, Unknown1> f) {} void G2(Func<Unknown2, Unknown2> f) {} void F() { G1(a => 1); } } "; var src2 = @" using System; class C { void G1(Func<Unknown1, Unknown1> f) {} void G2(Func<Unknown2, Unknown2> f) {} void F() { G2(a => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", "lambda")); } [Fact] public void Lambdas_Update_DelegateType1() { var src1 = @" using System; delegate int D1(int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; delegate int D1(int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_SourceType1() { var src1 = @" using System; delegate C D1(C a); delegate C D2(C a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; delegate C D1(C a); delegate C D2(C a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_SourceType2() { var src1 = @" using System; delegate C D1(C a); delegate B D2(B a); class B { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; delegate C D1(C a); delegate B D2(B a); class B { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_SourceTypeAndMetadataType1() { var src1 = @" namespace System { delegate string D1(string a); delegate String D2(String a); class String { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } } "; var src2 = @" namespace System { delegate string D1(string a); delegate String D2(String a); class String { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Generic1() { var src1 = @" delegate T D1<S, T>(S a, T b); delegate T D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, int> f) {} void F() { G1((a, b) => a + b); } } "; var src2 = @" delegate T D1<S, T>(S a, T b); delegate T D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, int> f) {} void F() { G2((a, b) => a + b); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Generic2() { var src1 = @" delegate int D1<S, T>(S a, T b); delegate int D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, string> f) {} void F() { G1((a, b) => 1); } } "; var src2 = @" delegate int D1<S, T>(S a, T b); delegate int D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, string> f) {} void F() { G2((a, b) => 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(a, b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_CapturedParameters1() { var src1 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2); return a1; }); } } "; var src2 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2 + 1); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(2223, "https://github.com/dotnet/roslyn/issues/2223")] public void Lambdas_Update_CapturedParameters2() { var src1 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2); return a1; }); var f3 = new Func<int, int, int>((a1, a2) => { var f4 = new Func<int, int>(a3 => x1 + a2); return a1; }); } } "; var src2 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2 + 1); return a1; }); var f3 = new Func<int, int, int>((a1, a2) => { var f4 = new Func<int, int>(a3 => x1 + a2 + 1); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_CeaseCapture_Closure1() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => y + a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2); return a1 + y; }); } } "; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a2", "y", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_CeaseCapture_IndexerParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a1 + a2); } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a2); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_CeaseCapture_IndexerParameter2() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a1 + a2); } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a2); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_CeaseCapture_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1 + a2); } } "; var src2 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_CeaseCapture_MethodParameter2() { var src1 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1 + a2); } "; var src2 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_CeaseCapture_LambdaParameter1() { var src1 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a1 + a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_SetterValueParameter1() { var src1 = @" using System; class C { int D { get { return 0; } set { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var src2 = @" using System; class C { int D { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { new Action(() => { Console.Write(value); }).Invoke(); } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "add", "value")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "remove", "value")); } [Fact] public void Lambdas_Update_DeleteCapture1() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => y + a2); return y; }); } } "; var src2 = @" using System; class C { void F() { // error var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeletingCapturedVariable, "{", "y").WithFirstLine("{ // error")); } [Fact] public void Lambdas_Update_Capturing_IndexerGetterParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a2); } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a1 + a2); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_Capturing_IndexerGetterParameter2() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a2); } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a1 + a2); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_Capturing_IndexerSetterParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { var f = new Func<int, int>(a3 => a2); } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { var f = new Func<int, int>(a3 => a1 + a2); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_Capturing_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "set", "value")); } [Fact] public void Lambdas_Update_Capturing_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact] public void Lambdas_Update_Capturing_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact] public void Lambdas_Update_Capturing_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1); } } "; var src2 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1 + a2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_Capturing_MethodParameter2() { var src1 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1); } "; var src2 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1 + a2); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_Capturing_LambdaParameter1() { var src1 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a1 + a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_StaticToThisOnly1() { var src1 = @" using System; class C { int x = 1; void F() { var f = new Func<int, int>(a => a); } } "; var src2 = @" using System; class C { int x = 1; void F() { var f = new Func<int, int>(a => a + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact] public void Lambdas_Update_StaticToThisOnly_Partial() { var src1 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { var f = new Func<int, int>(a => a); } } "; var src2 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { var f = new Func<int, int>(a => a + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this").WithFirstLine("partial void F() // impl")); } [Fact] public void Lambdas_Update_StaticToThisOnly3() { var src1 = @" using System; class C { int x = 1; void F() { var f1 = new Func<int, int>(a1 => a1); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var src2 = @" using System; class C { int x = 1; void F() { var f1 = new Func<int, int>(a1 => a1 + x); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a1", "this", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_StaticToClosure1() { var src1 = @" using System; class C { void F() { int x = 1; var f1 = new Func<int, int>(a1 => a1); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var src2 = @" using System; class C { void F() { int x = 1; var f1 = new Func<int, int>(a1 => { return a1 + x+ // 1 x; // 2 }); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.lambda).WithFirstLine("x+ // 1"), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.lambda).WithFirstLine("x; // 2")); } [Fact] public void Lambdas_Update_ThisOnlyToClosure1() { var src1 = @" using System; class C { int x = 1; void F() { int y = 1; var f1 = new Func<int, int>(a1 => a1 + x); var f2 = new Func<int, int>(a2 => a2 + x + y); } } "; var src2 = @" using System; class C { int x = 1; void F() { int y = 1; var f1 = new Func<int, int>(a1 => a1 + x + y); var f2 = new Func<int, int>(a2 => a2 + x + y); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y", "y", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Nested1() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2 + y); return a1; }); } } "; var src2 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2 + y); return a1 + y; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Nested2() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a1 + a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); // TODO: better diagnostics - identify a1 that causes the capture vs. a1 that doesn't edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1").WithFirstLine("var f1 = new Func<int, int>(a1 =>")); } [Fact] public void Lambdas_Update_Accessing_Closure1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} void F() { int x0 = 0, y0 = 0; G(a => x0); G(a => y0); } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} void F() { int x0 = 0, y0 = 0; G(a => x0); G(a => y0 + x0); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x0", "x0", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Accessing_Closure2() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x + x0); G(a => x0); G(a => y0); G(a => x1); } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); // error: disconnecting previously connected closures G(a => x0); G(a => y0); G(a => x1); } } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "x0", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Accessing_Closure3() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); G(a => x0); G(a => y0); G(a => x1); G(a => y1); } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); G(a => x0); G(a => y0); G(a => x1); G(a => y1 + x0); // error: connecting previously disconnected closures } } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x0", "x0", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Accessing_Closure4() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x + x0); G(a => x0); G(a => y0); G(a => x1); G(a => y1); } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); // error: disconnecting previously connected closures G(a => x0); G(a => y0); G(a => x1); G(a => y1 + x0); // error: connecting previously disconnected closures } } } } "; var edits = GetTopEdits(src1, src2); // TODO: "a => x + x0" is matched with "a => y1 + x0", hence we report more errors. // Including statement distance when matching would help. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "this", CSharpFeaturesResources.lambda).WithFirstLine("G(a => y1 + x0); // error: connecting previously disconnected closures"), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y1", "y1", CSharpFeaturesResources.lambda).WithFirstLine("G(a => y1 + x0); // error: connecting previously disconnected closures"), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "this", CSharpFeaturesResources.lambda).WithFirstLine("G(a => x); // error: disconnecting previously connected closures"), Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "y1", CSharpFeaturesResources.lambda).WithFirstLine("G(a => x); // error: disconnecting previously connected closures")); } [Fact] public void Lambdas_Update_Accessing_Closure_NestedLambdas() { var src1 = @" using System; class C { void G(Func<int, Func<int, int>> f) {} void F() { { int x0 = 0; // Group #0 { int x1 = 0; // Group #1 G(a => b => x0); G(a => b => x1); } } } } "; var src2 = @" using System; class C { void G(Func<int, Func<int, int>> f) {} void F() { { int x0 = 0; // Group #0 { int x1 = 0; // Group #1 G(a => b => x0); G(a => b => x1); G(a => b => x0); // ok G(a => b => x1); // ok G(a => b => x0 + x1); // error } } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_RenameCapturedLocal() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main() { int x = 1; Func<int> f = () => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main() { int X = 1; Func<int> f = () => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.RenamingCapturedVariable, "X", "x", "X")); } [Fact] public void Lambdas_RenameCapturedParameter() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main(int x) { Func<int> f = () => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main(int X) { Func<int> f = () => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.Main"), preserveLocalVariables: true) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Lambdas_Parameter_To_Discard1() { var src1 = "var x = new System.Func<int, int, int>((a, b) => 1);"; var src2 = "var x = new System.Func<int, int, int>((a, _) => 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [b]@45 -> [_]@45"); GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); } [Fact] public void Lambdas_Parameter_To_Discard2() { var src1 = "var x = new System.Func<int, int, int>((int a, int b) => 1);"; var src2 = "var x = new System.Func<int, int, int>((_, _) => 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int a]@42 -> [_]@42", "Update [int b]@49 -> [_]@45"); GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); } [Fact] public void Lambdas_Parameter_To_Discard3() { var src1 = "var x = new System.Func<int, int, int>((a, b) => 1);"; var src2 = "var x = new System.Func<int, int, int>((_, _) => 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [a]@42 -> [_]@42", "Update [b]@45 -> [_]@45"); GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); } #endregion #region Local Functions [Fact] public void LocalFunctions_InExpressionStatement() { var src1 = "F(a => a, b => b);"; var src2 = "int x(int a) => a + 1; F(b => b, x);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [a => a]@4 -> [int x(int a) => a + 1;]@2", "Move [a => a]@4 -> @2", "Update [F(a => a, b => b);]@2 -> [F(b => b, x);]@25", "Insert [(int a)]@7", "Insert [int a]@8", "Delete [a]@4"); } [Fact] public void LocalFunctions_ReorderAndUpdate() { var src1 = "int x(int a) => a; int y(int b) => b;"; var src2 = "int y(int b) => b; int x(int a) => a + 1;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [int y(int b) => b;]@21 -> @2", "Update [int x(int a) => a;]@2 -> [int x(int a) => a + 1;]@21"); } [Fact] public void LocalFunctions_InWhile() { var src1 = "do { /*1*/ } while (F(x));int x(int a) => a + 1;"; var src2 = "while (F(a => a)) { /*1*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [while (F(a => a)) { /*1*/ }]@2", "Update [int x(int a) => a + 1;]@28 -> [a => a]@11", "Move [int x(int a) => a + 1;]@28 -> @11", "Move [{ /*1*/ }]@5 -> @20", "Insert [a]@11", "Delete [do { /*1*/ } while (F(x));]@2", "Delete [(int a)]@33", "Delete [int a]@34"); } [Fact] public void LocalFunctions_InLocalFunction_NoChangeInSignature() { var src1 = "int x() { int y(int a) => a; return y(b); }"; var src2 = "int x() { int y() => c; return y(); }"; var edits = GetMethodEdits(src1, src2); // no changes to the method were made, only within the outer local function body: edits.VerifyEdits(); } [Fact] public void LocalFunctions_InLocalFunction_ChangeInSignature() { var src1 = "int x() { int y(int a) => a; return y(b); }"; var src2 = "int x(int z) { int y() => c; return y(); }"; var edits = GetMethodEdits(src1, src2); // changes were made to the outer local function signature: edits.VerifyEdits("Insert [int z]@8"); } [Fact] public void LocalFunctions_InLambda() { var src1 = "F(() => { int y(int a) => a; G(y); });"; var src2 = "F(q => { G(() => y); });"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [() => { int y(int a) => a; G(y); }]@4 -> [q => { G(() => y); }]@4", "Insert [q]@4", "Delete [()]@4"); } [Fact] public void LocalFunctions_Update_ParameterRefness_NoBodyChange() { var src1 = @"void f(ref int a) => a = 1;"; var src2 = @"void f(out int a) => a = 1;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int a]@9 -> [out int a]@9"); } [Fact] public void LocalFunctions_Insert_Static_Top() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { int f(int a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Insert_Static_Nested_ExpressionBodies() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) => a; G(localF); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) => a; int localG(int a) => G(localF) + a; G(localG); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Insert_Static_Nested_BlockBodies() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } G(localF); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } int localG(int a) { return G(localF) + a; } G(localG); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_LocalFunction_Replace_Lambda() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } G(localF); } } "; var edits = GetTopEdits(src1, src2); // To be removed when we will enable EnC for local functions edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, "localF", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Lambda_Replace_LocalFunction() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } G(localF); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, "a", CSharpFeaturesResources.lambda)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Top1() { var src1 = @" using System; class C { int x = 0; void F() { } } "; var src2 = @" using System; class C { int x = 0; void F() { int G(int a) => x; } } "; var edits = GetTopEdits(src1, src2); // TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291"), WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Top2() { var src1 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; int f1(int a) => y; } } } "; var src2 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; var f2 = from a in new[] { 1 } select a + y; var f3 = from a in new[] { 1 } where x > 0 select a; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "x", "x")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Nested1() { var src1 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { int f(int a) => a; G(f); } } "; var src2 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { int f(int a) => x; int g(int a) => G(f); G(g); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Nested2() { var src1 = @" using System; class C { int x = 0; void F() { int f1(int a) { int f2(int b) { return b; }; return a; }; } } "; var src2 = @" using System; class C { int x = 0; void F() { int f1(int a) { int f2(int b) { return b; }; int f3(int c) { return c + x; }; return a; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_InsertAndDelete_Scopes1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 int f1(int a) => x3 + x1; int f2(int a) => x0 + y0 + x2; int f3(int a) => x; } } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 int f1(int a) => x3 + x1; int f2(int a) => x0 + y0 + x2; int f3(int a) => x; int f4(int a) => x; // OK int f5(int a) => x0 + y0; // OK int f6(int a) => x1 + y0; // error - connecting Group #1 and Group #2 int f7(int a) => x3 + x1; // error - multi-scope (conservative) int f8(int a) => x + y0; // error - connecting Group #0 and Group #1 int f9(int a) => x + x3; // error - connecting Group #0 and Group #2 } } } } } "; var insert = GetTopEdits(src1, src2); insert.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "y0", "x1"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "x1", "x3"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.local_function, "this", "y0"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "this", "x3")); var delete = GetTopEdits(src2, src1); delete.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "y0", "x1"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "x1", "x3"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.local_function, "this", "y0"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "this", "x3")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ForEach1() { var src1 = @" using System; class C { void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; int f2(int a) => x0 + x1; // error: connecting previously disconnected closures } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_Switch1() { var src1 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; int f2() => x2; switch (a) { case 1: int x0 = 1; int f0() => x0; break; case 2: int x1 = 1; int f1() => x1; break; } } } "; var src2 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; int f2() => x2; switch (a) { case 1: int x0 = 1; int f0() => x0; goto case 2; case 2: int x1 = 1; int f1() => x1; goto default; default: x0 = 1; x1 = 2; int f01() => x0 + x1; // ok int f02() => x0 + x2; // error break; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.local_function, "x2", "x0")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_Catch1() { var src1 = @" using System; class C { static void F() { try { } catch (Exception x0) { int x1 = 1; int f0() => x0; int f1() => x1; } } } "; var src2 = @" using System; class C { static void F() { try { } catch (Exception x0) { int x1 = 1; int f0() => x0; int f1() => x1; int f00() => x0; //ok int f01() => F(x0, x1); //error } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1")); } [Fact] public void LocalFunctions_Insert_NotSupported() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { void M() { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "M", FeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_This() { var src1 = @" using System; class C { int x = 1; void F() { int f(int a) => a + x; } } "; var src2 = @" using System; class C { int x; void F() { int f(int a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "F", "this")); } [Fact] public void LocalFunctions_Update_Signature1() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void F() { long f(long a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature2() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void F() { int f(int a, int b) => a + b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature3() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void F() { long f(int a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_ReturnType1() { var src1 = @" using System; class C { void F() { int f(int a) { return 1; } } } "; var src2 = @" using System; class C { void F() { void f(int a) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_BodySyntaxOnly() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { int f(int a) { return a; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Update_Signature_ParameterName1() { var src1 = @" using System; class C { void F() { int f(int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(int b) => 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Update_Signature_ParameterRefness1() { var src1 = @" using System; class C { void F() { int f(ref int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(int a) => 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_ParameterRefness2() { var src1 = @" using System; class C { void F() { int f(out int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(ref int a) => 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_ParameterRefness3() { var src1 = @" using System; class C { void F() { int f(ref int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(out int a) => 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Signature_SemanticErrors() { var src1 = @" using System; class C { void F() { Unknown f(Unknown a) => 1; } } "; var src2 = @" using System; class C { void F() { Unknown f(Unknown a) => 2; } } "; var edits = GetTopEdits(src1, src2); // There are semantics errors in the case. The errors are captured during the emit execution. edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Update_CapturedParameters1() { var src1 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2; return a1; }; } } "; var src2 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2 + 1; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(2223, "https://github.com/dotnet/roslyn/issues/2223")] public void LocalFunctions_Update_CapturedParameters2() { var src1 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2; return a1; }; int f3(int a1, int a2) { int f4(int a3) => x1 + a2; return a1; }; } } "; var src2 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2 + 1; return a1; }; int f3(int a1, int a2) { int f4(int a3) => x1 + a2 + 1; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_Closure1() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => y + a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2; return a1 + y; }; } } "; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "f2", "y", CSharpFeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_IndexerParameter() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a2; return f; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1 + a2; } } "; var src2 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_LambdaParameter1() { var src1 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a1 + a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "int f1(int a1, int a2)\r\n {\r\n int f2(int a3) => a2;\r\n return a1;\r\n };\r\n ", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_SetterValueParameter1() { var src1 = @" using System; class C { int D { get { return 0; } set { void f() { Console.Write(value); } f(); } } } "; var src2 = @" using System; class C { int D { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { void f() { Console.Write(value); } f(); } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { void f() { Console.Write(value); } f(); } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "add", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { void f() { Console.Write(value); } f(); } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "remove", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_DeleteCapture1() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => y + a2; return y; }; } } "; var src2 = @" using System; class C { void F() { // error int f1(int a1) { int f2(int a2) => a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeletingCapturedVariable, "{", "y")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerGetterParameter2() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a2; return f; } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerSetterParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { int f(int a3) => a2; } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { int f(int a3) => a1 + a2; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { void f() { Console.Write(value); } f(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "set", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { void f() { Console.Write(value); } f(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { void f() { Console.Write(value); } f(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1; } } "; var src2 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1 + a2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_LambdaParameter1() { var src1 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a1 + a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly1() { var src1 = @" using System; class C { int x = 1; void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { int x = 1; void F() { int f(int a) => a + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly_Partial() { var src1 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { int f(int a) => a; } } "; var src2 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { int f(int a) => a + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly3() { var src1 = @" using System; class C { int x = 1; void F() { int f1(int a1) => a1; int f2(int a2) => a2 + x; } } "; var src2 = @" using System; class C { int x = 1; void F() { int f1(int a1) => a1 + x; int f2(int a2) => a2 + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "f1", "this", CSharpFeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToClosure1() { var src1 = @" using System; class C { void F() { int x = 1; int f1(int a1) => a1; int f2(int a2) => a2 + x; } } "; var src2 = @" using System; class C { void F() { int x = 1; int f1(int a1) { return a1 + x+ // 1 x; // 2 }; int f2(int a2) => a2 + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.local_function), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_ThisOnlyToClosure1() { var src1 = @" using System; class C { int x = 1; void F() { int y = 1; int f1(int a1) => a1 + x; int f2(int a2) => a2 + x + y; } } "; var src2 = @" using System; class C { int x = 1; void F() { int y = 1; int f1(int a1) => a1 + x + y; int f2(int a2) => a2 + x + y; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y", "y", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Nested1() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2 + y; return a1; }; } } "; var src2 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2 + y; return a1 + y; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Nested2() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a1 + a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_RenameCapturedLocal() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main() { int x = 1; int f() => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main() { int X = 1; int f() => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.RenamingCapturedVariable, "X", "x", "X")); } [Fact] public void LocalFunctions_RenameCapturedParameter() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main(int x) { int f() => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main(int X) { int f() => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.Main"), preserveLocalVariables: true) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void LocalFunction_In_Parameter_InsertWhole() { var src1 = @"class Test { void M() { } }"; var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { }]@13 -> [void M() { void local(in int b) { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_In_Parameter_InsertParameter() { var src1 = @"class Test { void M() { void local() { throw null; } } }"; var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { void local() { throw null; } }]@13 -> [void M() { void local(in int b) { throw null; } }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "local", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunction_In_Parameter_Update() { var src1 = @"class Test { void M() { void local(int b) { throw null; } } }"; var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { void local(int b) { throw null; } }]@13 -> [void M() { void local(in int b) { throw null; } }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "local", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunction_ReadOnlyRef_ReturnType_Insert() { var src1 = @"class Test { void M() { } }"; var src2 = @"class Test { void M() { ref readonly int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { }]@13 -> [void M() { ref readonly int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_ReadOnlyRef_ReturnType_Update() { var src1 = @"class Test { void M() { int local() { throw null; } } }"; var src2 = @"class Test { void M() { ref readonly int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { int local() { throw null; } }]@13 -> [void M() { ref readonly int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "local", CSharpFeaturesResources.local_function)); } [WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")] [Fact] public void LocalFunction_AddToInterfaceMethod() { var src1 = @" using System; interface I { static int X = M(() => 1); static int M() => 1; static void F() { void g() { } } } "; var src2 = @" using System; interface I { static int X = M(() => { void f3() {} return 2; }); static int M() => 1; static void F() { int f1() => 1; f1(); void g() { void f2() {} f2(); } var l = new Func<int>(() => 1); l(); } } "; var edits = GetTopEdits(src1, src2); // lambdas are ok as they are emitted to a nested type edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.NetCoreApp }, expectedDiagnostics: new[] { Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f1"), Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f2"), Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f3") }); } [Fact] public void LocalFunction_AddStatic() { var src1 = @"class Test { void M() { int local() { throw null; } } }"; var src2 = @"class Test { void M() { static int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { int local() { throw null; } }]@13 -> [void M() { static int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_RemoveStatic() { var src1 = @"class Test { void M() { static int local() { throw null; } } }"; var src2 = @"class Test { void M() { int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { static int local() { throw null; } }]@13 -> [void M() { int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_AddUnsafe() { var src1 = @"class Test { void M() { int local() { throw null; } } }"; var src2 = @"class Test { void M() { unsafe int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { int local() { throw null; } }]@13 -> [void M() { unsafe int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_RemoveUnsafe() { var src1 = @"class Test { void M() { unsafe int local() { throw null; } } }"; var src2 = @"class Test { void M() { int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { unsafe int local() { throw null; } }]@13 -> [void M() { int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunction_AddAsync() { var src1 = @"class Test { void M() { Task<int> local() => throw null; } }"; var src2 = @"class Test { void M() { async Task<int> local() => throw null; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunction_RemoveAsync() { var src1 = @"class Test { void M() { async int local() { throw null; } } }"; var src2 = @"class Test { void M() { int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "local", FeaturesResources.local_function)); } [Fact] public void LocalFunction_AddAttribute() { var src1 = "void L() { }"; var src2 = "[A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [void L() { }]@2 -> [[A]void L() { }]@2"); // Get top edits so we can validate rude edits GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_RemoveAttribute() { var src1 = "[A]void L() { }"; var src2 = "void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A]void L() { }]@2 -> [void L() { }]@2"); // Get top edits so we can validate rude edits GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReorderAttribute() { var src1 = "[A, B]void L() { }"; var src2 = "[B, A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A, B]void L() { }]@2 -> [[B, A]void L() { }]@2"); // Get top edits so we can validate rude edits GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_CombineAttributeLists() { var src1 = "[A][B]void L() { }"; var src2 = "[A, B]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A][B]void L() { }]@2 -> [[A, B]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_SplitAttributeLists() { var src1 = "[A, B]void L() { }"; var src2 = "[A][B]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A, B]void L() { }]@2 -> [[A][B]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_ChangeAttributeListTarget1() { var src1 = "[return: A]void L() { }"; var src2 = "[A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[return: A]void L() { }]@2 -> [[A]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ChangeAttributeListTarget2() { var src1 = "[A]void L() { }"; var src2 = "[return: A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A]void L() { }]@2 -> [[return: A]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReturnType_AddAttribute() { var src1 = "int L() { return 1; }"; var src2 = "[return: A]int L() { return 1; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int L() { return 1; }]@2 -> [[return: A]int L() { return 1; }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReturnType_RemoveAttribute() { var src1 = "[return: A]int L() { return 1; }"; var src2 = "int L() { return 1; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[return: A]int L() { return 1; }]@2 -> [int L() { return 1; }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReturnType_ReorderAttribute() { var src1 = "[return: A, B]int L() { return 1; }"; var src2 = "[return: B, A]int L() { return 1; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[return: A, B]int L() { return 1; }]@2 -> [[return: B, A]int L() { return 1; }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_Parameter_AddAttribute() { var src1 = "void L(int i) { }"; var src2 = "void L([A]int i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int i]@9 -> [[A]int i]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.parameter)); } [Fact] public void LocalFunction_Parameter_RemoveAttribute() { var src1 = "void L([A]int i) { }"; var src2 = "void L(int i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A]int i]@9 -> [int i]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.parameter)); } [Fact] public void LocalFunction_Parameter_ReorderAttribute() { var src1 = "void L([A, B]int i) { }"; var src2 = "void L([B, A]int i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A, B]int i]@9 -> [[B, A]int i]@9"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_TypeParameter_AddAttribute() { var src1 = "void L<T>(T i) { }"; var src2 = "void L<[A] T>(T i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [T]@9 -> [[A] T]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.type_parameter)); } [Fact] public void LocalFunction_TypeParameter_RemoveAttribute() { var src1 = "void L<[A] T>(T i) { }"; var src2 = "void L<T>(T i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A] T]@9 -> [T]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.type_parameter)); } [Fact] public void LocalFunction_TypeParameter_ReorderAttribute() { var src1 = "void L<[A, B] T>(T i) { }"; var src2 = "void L<[B, A] T>(T i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A, B] T]@9 -> [[B, A] T]@9"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunctions_TypeParameter_Insert1() { var src1 = @"void L() {}"; var src2 = @"void L<A>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@8", "Insert [A]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Insert2() { var src1 = @"void L<A>() {}"; var src2 = @"void L<A,B>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@8 -> [<A,B>]@8", "Insert [B]@11"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Delete1() { var src1 = @"void L<A>() {}"; var src2 = @"void L() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@8", "Delete [A]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Delete2() { var src1 = @"void L<A,B>() {}"; var src2 = @"void L<B>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@8 -> [<B>]@8", "Delete [A]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Update() { var src1 = @"void L<A>() {}"; var src2 = @"void L<B>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [A]@9 -> [B]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Theory] [InlineData("Enum", "Delegate")] [InlineData("IDisposable", "IDisposable, new()")] public void LocalFunctions_TypeParameter_Constraint_Clause_Update(string oldConstraint, string newConstraint) { var src1 = "void L<A>() where A : " + oldConstraint + " {}"; var src2 = "void L<A>() where A : " + newConstraint + " {}"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [where A : " + oldConstraint + "]@14 -> [where A : " + newConstraint + "]@14"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void LocalFunctions_TypeParameter_Constraint_Clause_Delete(string oldConstraint) { var src1 = "void L<A>() where A : " + oldConstraint + " {}"; var src2 = "void L<A>() {}"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [where A : " + oldConstraint + "]@14"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Constraint_Clause_Add() { var src1 = "void L<A,B>() where A : new() {}"; var src2 = "void L<A,B>() where A : new() where B : System.IDisposable {}"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [where B : System.IDisposable]@32"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Reorder() { var src1 = @"void L<A,B>() {}"; var src2 = @"void L<B,A>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@11 -> @9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_ReorderAndUpdate() { var src1 = @"void L<A,B>() {}"; var src2 = @"void L<B,C>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@11 -> @9", "Update [A]@9 -> [C]@11"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } #endregion #region Queries [Fact] public void Queries_Update_Signature_Select1() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} select a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1.0} select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Update_Signature_Select2() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} select a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} select a.ToString(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Update_Signature_From1() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} from b in new[] {2} select b; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from long a in new[] {1} from b in new[] {2} select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "from", CSharpFeaturesResources.from_clause)); } [Fact] public void Queries_Update_Signature_From2() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from System.Int64 a in new[] {1} from b in new[] {2} select b; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from long a in new[] {1} from b in new[] {2} select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Update_Signature_From3() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} from b in new[] {2} select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new List<int>() from b in new List<int>() select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Update_Signature_Let1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} let b = 1 select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} let b = 1.0 select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "let", CSharpFeaturesResources.let_clause)); } [Fact] public void Queries_Update_Signature_OrderBy1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1.0 descending, a + 2 ascending select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "a + 1.0 descending", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Update_Signature_OrderBy2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1 descending, a + 2.0 ascending select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "a + 2.0 ascending", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Update_Signature_Join1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1.0} on a equals b select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_Join2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join byte b in new[] {1} on a equals b select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_Join3() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a + 1 equals b select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a + 1.0 equals b select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_Join4() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b + 1 select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b + 1.0 select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_GroupBy1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a + 1 by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a + 1.0 by a into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_Update_Signature_GroupBy2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a by a + 1.0 into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_Update_Signature_GroupBy_MatchingErrorTypes() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown G1(int a) => null; Unknown G2(int a) => null; void F() { var result = from a in new[] {1} group G1(a) by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown G1(int a) => null; Unknown G2(int a) => null; void F() { var result = from a in new[] {1} group G2(a) by a into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Update_Signature_GroupBy_NonMatchingErrorTypes() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown1 G1(int a) => null; Unknown2 G2(int a) => null; void F() { var result = from a in new[] {1} group G1(a) by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown1 G1(int a) => null; Unknown2 G2(int a) => null; void F() { var result = from a in new[] {1} group G2(a) by a into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_FromSelect_Update1() { var src1 = "F(from a in b from x in y select c);"; var src2 = "F(from a in c from x in z select c + 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [from a in b]@4 -> [from a in c]@4", "Update [from x in y]@16 -> [from x in z]@16", "Update [select c]@28 -> [select c + 1]@28"); } [Fact] public void Queries_FromSelect_Update2() { var src1 = "F(from a in b from x in y select c);"; var src2 = "F(from a in b from x in z select c);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [from x in y]@16 -> [from x in z]@16"); } [Fact] public void Queries_FromSelect_Update3() { var src1 = "F(from a in await b from x in y select c);"; var src2 = "F(from a in await c from x in y select c);"; var edits = GetMethodEdits(src1, src2, MethodKind.Async); edits.VerifyEdits( "Update [await b]@34 -> [await c]@34"); } [Fact] public void Queries_Select_Reduced1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a + 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Select_Reduced2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a + 1; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_FromSelect_Delete() { var src1 = "F(from a in b from c in d select a + c);"; var src2 = "F(from a in b select c + 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [select a + c]@28 -> [select c + 1]@16", "Delete [from c in d]@16"); } [Fact] public void Queries_JoinInto_Update() { var src1 = "F(from a in b join b in c on a equals b into g1 select g1);"; var src2 = "F(from a in b join b in c on a equals b into g2 select g2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [select g1]@50 -> [select g2]@50", "Update [into g1]@42 -> [into g2]@42"); } [Fact] public void Queries_JoinIn_Update() { var src1 = "F(from a in b join b in await A(1) on a equals b select g);"; var src2 = "F(from a in b join b in await A(2) on a equals b select g);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [await A(1)]@26 -> [await A(2)]@26"); } [Fact] public void Queries_GroupBy_Update() { var src1 = "F(from a in b group a by a.x into g select g);"; var src2 = "F(from a in b group z by z.y into h select h);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [group a by a.x]@17 -> [group z by z.y]@17", "Update [into g select g]@32 -> [into h select h]@32", "Update [select g]@40 -> [select h]@40"); } [Fact] public void Queries_OrderBy_Reorder() { var src1 = "F(from a in b orderby a.x, a.b descending, a.c ascending select a.d);"; var src2 = "F(from a in b orderby a.x, a.c ascending, a.b descending select a.d);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [a.c ascending]@46 -> @30"); } [Fact] public void Queries_GroupBy_Reduced1() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1.0 by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced2() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1 by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_GroupBy_Reduced3() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1.0 by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced4() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1 by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_OrderBy_Continuation_Update() { var src1 = "F(from a in b orderby a.x, a.b descending select a.d into z orderby a.c ascending select z);"; var src2 = "F(from a in b orderby a.x, a.c ascending select a.d into z orderby a.b descending select z);"; var edits = GetMethodEdits(src1, src2); var actual = ToMatchingPairs(edits.Match); var expected = new MatchingPairs { { "F(from a in b orderby a.x, a.b descending select a.d into z orderby a.c ascending select z);", "F(from a in b orderby a.x, a.c ascending select a.d into z orderby a.b descending select z);" }, { "from a in b", "from a in b" }, { "orderby a.x, a.b descending select a.d into z orderby a.c ascending select z", "orderby a.x, a.c ascending select a.d into z orderby a.b descending select z" }, { "orderby a.x, a.b descending", "orderby a.x, a.c ascending" }, { "a.x", "a.x" }, { "a.b descending", "a.c ascending" }, { "select a.d", "select a.d" }, { "into z orderby a.c ascending select z", "into z orderby a.b descending select z" }, { "orderby a.c ascending select z", "orderby a.b descending select z" }, { "orderby a.c ascending", "orderby a.b descending" }, { "a.c ascending", "a.b descending" }, { "select z", "select z" } }; expected.AssertEqual(actual); edits.VerifyEdits( "Update [a.b descending]@30 -> [a.c ascending]@30", "Update [a.c ascending]@74 -> [a.b descending]@73"); } [Fact] public void Queries_CapturedTransparentIdentifiers_FromClause1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a) > 0 where Z(() => b) > 0 where Z(() => a) > 0 where Z(() => b) > 0 select a; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a) > 1 // update where Z(() => b) > 2 // update where Z(() => a) > 3 // update where Z(() => b) > 4 // update select a; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_CapturedTransparentIdentifiers_LetClause1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } let b = Z(() => a) select a + b; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } let b = Z(() => a + 1) select a - b; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_CapturedTransparentIdentifiers_JoinClause1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g select Z(() => g.First()); } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g select Z(() => g.Last()); } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_CeaseCapturingTransparentIdentifiers1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + b) > 0 select a; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + 1) > 0 select a; } }"; var edits = GetTopEdits(src1, src2); // TODO: better location (the variable, not the from clause) edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "from b in new[] { 2 }", "b")); } [Fact] public void Queries_CapturingTransparentIdentifiers1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + 1) > 0 select a; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + b) > 0 select a; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "b", "b")); } [Fact] public void Queries_AccessingCapturedTransparentIdentifier1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select 1; } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_AccessingCapturedTransparentIdentifier2() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select b; } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select a + b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_AccessingCapturedTransparentIdentifier3() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => 1); } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_NotAccessingCapturedTransparentIdentifier1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select a + b; } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "select", "a", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_NotAccessingCapturedTransparentIdentifier2() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => 1); } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_Insert1() { var src1 = @" using System; using System.Linq; class C { void F() { } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] { 1 } select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } #endregion #region Yield [Fact] public void Yield_Update1() { var src1 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 2; yield break; } } "; var src2 = @" class C { static IEnumerable<int> F() { yield return 3; yield break; yield return 4; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield break;", CSharpFeaturesResources.yield_return_statement, CSharpFeaturesResources.yield_break_statement), Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield return 4;", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.yield_return_statement)); } [Fact] public void Yield_Delete1() { var src1 = @" yield return 1; yield return 2; yield return 3; "; var src2 = @" yield return 1; yield return 3; "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator); bodyEdits.VerifyEdits( "Delete [yield return 2;]@42"); } [Fact] public void Yield_Delete2() { var src1 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 2; yield return 3; } } "; var src2 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 3; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void Yield_Insert1() { var src1 = @" yield return 1; yield return 3; "; var src2 = @" yield return 1; yield return 2; yield return 3; yield return 4; "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator); bodyEdits.VerifyEdits( "Insert [yield return 2;]@42", "Insert [yield return 4;]@76"); } [Fact] public void Yield_Insert2() { var src1 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 3; } } "; var src2 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 2; yield return 3; yield return 4; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "yield return 4;", CSharpFeaturesResources.yield_return_statement), Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MissingIteratorStateMachineAttribute() { var src1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 1; } } "; var src2 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.Mscorlib40AndSystemCore }, Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static IEnumerable<int> F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute")); } [Fact] public void MissingIteratorStateMachineAttribute2() { var src1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { return null; } } "; var src2 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.Mscorlib40AndSystemCore }); } #endregion #region Await /// <summary> /// Tests spilling detection logic of <see cref="CSharpEditAndContinueAnalyzer.ReportStateMachineSuspensionPointRudeEdits"/>. /// </summary> [Fact] public void AwaitSpilling_OK() { var src1 = @" class C { static async Task<int> F() { await F(1); if (await F(1)) { Console.WriteLine(1); } if (await F(1)) { Console.WriteLine(1); } if (F(1, await F(1))) { Console.WriteLine(1); } if (await F(1)) { Console.WriteLine(1); } do { Console.WriteLine(1); } while (await F(1)); for (var x = await F(1); await G(1); await H(1)) { Console.WriteLine(1); } foreach (var x in await F(1)) { Console.WriteLine(1); } using (var x = await F(1)) { Console.WriteLine(1); } lock (await F(1)) { Console.WriteLine(1); } lock (a = await F(1)) { Console.WriteLine(1); } var a = await F(1), b = await G(1); a = await F(1); switch (await F(2)) { case 1: return b = await F(1); } return await F(1); } static async Task<int> G() => await F(1); } "; var src2 = @" class C { static async Task<int> F() { await F(2); if (await F(1)) { Console.WriteLine(2); } if (await F(2)) { Console.WriteLine(1); } if (F(1, await F(1))) { Console.WriteLine(2); } while (await F(1)) { Console.WriteLine(1); } do { Console.WriteLine(2); } while (await F(2)); for (var x = await F(2); await G(2); await H(2)) { Console.WriteLine(2); } foreach (var x in await F(2)) { Console.WriteLine(2); } using (var x = await F(2)) { Console.WriteLine(1); } lock (await F(2)) { Console.WriteLine(2); } lock (a = await F(2)) { Console.WriteLine(2); } var a = await F(2), b = await G(2); b = await F(2); switch (await F(2)) { case 1: return b = await F(2); } return await F(2); } static async Task<int> G() => await F(2); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } /// <summary> /// Tests spilling detection logic of <see cref="CSharpEditAndContinueAnalyzer.ReportStateMachineSuspensionPointRudeEdits"/>. /// </summary> [Fact] public void AwaitSpilling_Errors() { var src1 = @" class C { static async Task<int> F() { F(1, await F(1)); F(1, await F(1)); F(await F(1)); await F(await F(1)); if (F(1, await F(1))) { Console.WriteLine(1); } var a = F(1, await F(1)), b = F(1, await G(1)); b = F(1, await F(1)); b += await F(1); } } "; var src2 = @" class C { static async Task<int> F() { F(2, await F(1)); F(1, await F(2)); F(await F(2)); await F(await F(2)); if (F(2, await F(1))) { Console.WriteLine(1); } var a = F(1, await F(2)), b = F(1, await G(2)); b = F(1, await F(2)); b += await F(2); } } "; var edits = GetTopEdits(src1, src2); // consider: these edits can be allowed if we get more sophisticated edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(2, await F(1));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(1, await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "await F(await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(2, await F(1))"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "var a = F(1, await F(2)), b = F(1, await G(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "var a = F(1, await F(2)), b = F(1, await G(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "b = F(1, await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "b += await F(2);")); } [Fact] public void Await_Delete1() { var src1 = @" await F(1); await F(2); await F(3); "; var src2 = @" await F(1); await F(3); "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async); bodyEdits.VerifyEdits( "Delete [await F(2);]@37", "Delete [await F(2)]@37"); } [Fact] public void Await_Delete2() { var src1 = @" class C { static async Task<int> F() { await F(1); { await F(2); } await F(3); } } "; var src2 = @" class C { static async Task<int> F() { await F(1); { F(2); } await F(3); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "F(2);", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Delete3() { var src1 = @" class C { static async Task<int> F() { await F(await F(1)); } } "; var src2 = @" class C { static async Task<int> F() { await F(1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "await F(1);", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Delete4() { var src1 = @" class C { static async Task<int> F() => await F(await F(1)); } "; var src2 = @" class C { static async Task<int> F() => await F(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "static async Task<int> F()", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Delete5() { var src1 = @" class C { static async Task<int> F() => await F(1); } "; var src2 = @" class C { static async Task<int> F() => F(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "static async Task<int> F()", CSharpFeaturesResources.await_expression)); } [Fact] public void AwaitForEach_Delete1() { var src1 = @" class C { static async Task<int> F() { await foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { foreach (var x in G()) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "foreach (var x in G())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void AwaitForEach_Delete2() { var src1 = @" class C { static async Task<int> F() { await foreach (var (x, y) in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { foreach (var (x, y) in G()) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "foreach (var (x, y) in G())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void AwaitForEach_Delete3() { var src1 = @" class C { static async Task<int> F() { await foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_foreach_statement)); } [Fact] public void AwaitUsing_Delete1() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await using D x = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "await using", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Delete2() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await using D y = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "await using", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Delete3() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Delete4() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { using D x = new D(), y = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "using", CSharpFeaturesResources.using_declaration), Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "using", CSharpFeaturesResources.using_declaration)); } [Fact] public void Await_Insert1() { var src1 = @" await F(1); await F(3); "; var src2 = @" await F(1); await F(2); await F(3); await F(4); "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async); bodyEdits.VerifyEdits( "Insert [await F(2);]@37", "Insert [await F(4);]@63", "Insert [await F(2)]@37", "Insert [await F(4)]@63"); } [Fact] public void Await_Insert2() { var src1 = @" class C { static async IEnumerable<int> F() { await F(1); await F(3); } } "; var src2 = @" class C { static async IEnumerable<int> F() { await F(1); await F(2); await F(3); await F(4); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Insert3() { var src1 = @" class C { static async IEnumerable<int> F() { await F(1); await F(3); } } "; var src2 = @" class C { static async IEnumerable<int> F() { await F(await F(1)); await F(await F(2)); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Insert4() { var src1 = @" class C { static async Task<int> F() => await F(1); } "; var src2 = @" class C { static async Task<int> F() => await F(await F(1)); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Insert5() { var src1 = @" class C { static Task<int> F() => F(1); } "; var src2 = @" class C { static async Task<int> F() => await F(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void AwaitForEach_Insert_Ok() { var src1 = @" class C { static async Task<int> F() { foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { await foreach (var x in G()) { } } } "; var edits = GetTopEdits(src1, src2); // ok to add awaits if there were none before and no active statements edits.VerifyRudeDiagnostics(); } [Fact] public void AwaitForEach_Insert() { var src1 = @" class C { static async Task<int> F() { await Task.FromResult(1); foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { await Task.FromResult(1); await foreach (var x in G()) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", "await")); } [Fact] public void AwaitUsing_Insert1() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "y = new D()", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Insert2() { var src1 = @" class C { static async Task<int> F() { await G(); using D x = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await G(); await using D x = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", "await")); } [Fact] public void Await_Update() { var src1 = @" class C { static async IAsyncEnumerable<int> F() { await foreach (var x in G()) { } await Task.FromResult(1); await Task.FromResult(1); await Task.FromResult(1); yield return 1; yield break; yield break; } } "; var src2 = @" class C { static async IAsyncEnumerable<int> F() { await foreach (var (x,y) in G()) { } await foreach (var x in G()) { } await using D x = new D(), y = new D(); await Task.FromResult(1); await Task.FromResult(1); yield return 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingStateMachineShape, "await foreach (var x in G()) { }", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_foreach_statement), Diagnostic(RudeEditKind.ChangingStateMachineShape, "x = new D()", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.ChangingStateMachineShape, "y = new D()", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.ChangingStateMachineShape, "await Task.FromResult(1)", CSharpFeaturesResources.yield_return_statement, CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.ChangingStateMachineShape, "await Task.FromResult(1)", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield return 1;", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MissingAsyncStateMachineAttribute1() { var src1 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await new Task(); return 1; } } "; var src2 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await new Task(); return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.MinimalAsync }, expectedDiagnostics: new[] { Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static async Task<int> F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute") }); } [Fact] public void MissingAsyncStateMachineAttribute2() { var src1 = @" using System.Threading.Tasks; class C { static Task<int> F() { return null; } } "; var src2 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await new Task(); return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.MinimalAsync }); } [Fact] public void SemanticError_AwaitInPropertyAccessor() { var src1 = @" using System.Threading.Tasks; class C { public Task<int> P { get { await Task.Delay(1); return 1; } } } "; var src2 = @" using System.Threading.Tasks; class C { public Task<int> P { get { await Task.Delay(2); return 1; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } #endregion #region Out Var [Fact] public void OutVarType_Update() { var src1 = @" M(out var y); "; var src2 = @" M(out int y); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M(out var y);]@4 -> [M(out int y);]@4"); } [Fact] public void OutVarNameAndType_Update() { var src1 = @" M(out var y); "; var src2 = @" M(out int z); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M(out var y);]@4 -> [M(out int z);]@4", "Update [y]@14 -> [z]@14"); } [Fact] public void OutVar_Insert() { var src1 = @" M(); "; var src2 = @" M(out int y); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M();]@4 -> [M(out int y);]@4", "Insert [y]@14"); } [Fact] public void OutVar_Delete() { var src1 = @" M(out int y); "; var src2 = @" M(); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M(out int y);]@4 -> [M();]@4", "Delete [y]@14"); } #endregion #region Pattern [Fact] public void ConstantPattern_Update() { var src1 = @" if ((o is null) && (y == 7)) return 3; if (a is 7) return 5; "; var src2 = @" if ((o1 is null) && (y == 7)) return 3; if (a is 77) return 5; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if ((o is null) && (y == 7)) return 3;]@4 -> [if ((o1 is null) && (y == 7)) return 3;]@4", "Update [if (a is 7) return 5;]@44 -> [if (a is 77) return 5;]@45"); } [Fact] public void DeclarationPattern_Update() { var src1 = @" if (!(o is int i) && (y == 7)) return; if (!(a is string s)) return; if (!(b is string t)) return; if (!(c is int j)) return; "; var src2 = @" if (!(o1 is int i) && (y == 7)) return; if (!(a is int s)) return; if (!(b is string t1)) return; if (!(c is int)) return; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (!(o is int i) && (y == 7)) return;]@4 -> [if (!(o1 is int i) && (y == 7)) return;]@4", "Update [if (!(a is string s)) return;]@44 -> [if (!(a is int s)) return;]@45", "Update [if (!(c is int j)) return;]@106 -> [if (!(c is int)) return;]@105", "Update [t]@93 -> [t1]@91", "Delete [j]@121"); } [Fact] public void DeclarationPattern_Reorder() { var src1 = @"if ((a is int i) && (b is int j)) { A(); }"; var src2 = @"if ((b is int j) && (a is int i)) { A(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if ((a is int i) && (b is int j)) { A(); }]@2 -> [if ((b is int j) && (a is int i)) { A(); }]@2", "Reorder [j]@32 -> @16"); } [Fact] public void VarPattern_Update() { var src1 = @" if (o is (var x, var y)) return; if (o4 is (string a, var (b, c))) return; if (o2 is var (e, f, g)) return; if (o3 is var (k, l, m)) return; "; var src2 = @" if (o is (int x, int y1)) return; if (o1 is (var a, (var b, string c1))) return; if (o7 is var (g, e, f)) return; if (o3 is (string k, int l2, int m)) return; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (o is (var x, var y)) return;]@4 -> [if (o is (int x, int y1)) return;]@4", "Update [if (o4 is (string a, var (b, c))) return;]@38 -> [if (o1 is (var a, (var b, string c1))) return;]@39", "Update [if (o2 is var (e, f, g)) return;]@81 -> [if (o7 is var (g, e, f)) return;]@87", "Reorder [g]@102 -> @102", "Update [if (o3 is var (k, l, m)) return;]@115 -> [if (o3 is (string k, int l2, int m)) return;]@121", "Update [y]@25 -> [y1]@25", "Update [c]@67 -> [c1]@72", "Update [l]@133 -> [l2]@146"); } [Fact] public void PositionalPattern_Update1() { var src1 = @"var r = (x, y, z) switch { (0, var b, int c) when c > 1 => 2, _ => 4 };"; var src2 = @"var r = ((x, y, z)) switch { (_, int b1, double c1) when c1 > 2 => c1, _ => 4 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(x, y, z) switch { (0, var b, int c) when c > 1 => 2, _ => 4 }]@10 -> [((x, y, z)) switch { (_, int b1, double c1) when c1 > 2 => c1, _ => 4 }]@10", "Update [(0, var b, int c) when c > 1 => 2]@29 -> [(_, int b1, double c1) when c1 > 2 => c1]@31", "Reorder [c]@44 -> @39", "Update [c]@44 -> [b1]@39", "Update [b]@37 -> [c1]@50", "Update [when c > 1]@47 -> [when c1 > 2]@54"); } [Fact] public void PositionalPattern_Update2() { var src1 = @"var r = (x, y, z) switch { (var a, 3, 4) => a, (1, 1, Point { X: 0 } p) => 3, _ => 4 };"; var src2 = @"var r = ((x, y, z)) switch { (var a1, 3, 4) => a1 * 2, (1, 1, Point { Y: 0 } p1) => 3, _ => 4 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(x, y, z) switch { (var a, 3, 4) => a, (1, 1, Point { X: 0 } p) => 3, _ => 4 }]@10 -> [((x, y, z)) switch { (var a1, 3, 4) => a1 * 2, (1, 1, Point { Y: 0 } p1) => 3, _ => 4 }]@10", "Update [(var a, 3, 4) => a]@29 -> [(var a1, 3, 4) => a1 * 2]@31", "Update [(1, 1, Point { X: 0 } p) => 3]@49 -> [(1, 1, Point { Y: 0 } p1) => 3]@57", "Update [a]@34 -> [a1]@36", "Update [p]@71 -> [p1]@79"); } [Fact] public void PositionalPattern_Reorder() { var src1 = @"var r = (x, y, z) switch { (1, 2, 3) => 0, (var a, 3, 4) => a, (0, var b, int c) when c > 1 => 2, (1, 1, Point { X: 0 } p) => 3, _ => 4 }; "; var src2 = @"var r = ((x, y, z)) switch { (1, 1, Point { X: 0 } p) => 3, (0, var b, int c) when c > 1 => 2, (var a, 3, 4) => a, (1, 2, 3) => 0, _ => 4 }; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( @"Update [(x, y, z) switch { (1, 2, 3) => 0, (var a, 3, 4) => a, (0, var b, int c) when c > 1 => 2, (1, 1, Point { X: 0 } p) => 3, _ => 4 }]@10 -> [((x, y, z)) switch { (1, 1, Point { X: 0 } p) => 3, (0, var b, int c) when c > 1 => 2, (var a, 3, 4) => a, (1, 2, 3) => 0, _ => 4 }]@10", "Reorder [(var a, 3, 4) => a]@47 -> @100", "Reorder [(0, var b, int c) when c > 1 => 2]@68 -> @64", "Reorder [(1, 1, Point { X: 0 } p) => 3]@104 -> @32"); } [Fact] public void PropertyPattern_Update() { var src1 = @" if (address is { State: ""WA"" }) return 1; if (obj is { Color: Color.Purple }) return 2; if (o is string { Length: 5 } s) return 3; "; var src2 = @" if (address is { ZipCode: 98052 }) return 4; if (obj is { Size: Size.M }) return 2; if (o is string { Length: 7 } s7) return 5; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (address is { State: \"WA\" }) return 1;]@4 -> [if (address is { ZipCode: 98052 }) return 4;]@4", "Update [if (obj is { Color: Color.Purple }) return 2;]@47 -> [if (obj is { Size: Size.M }) return 2;]@50", "Update [if (o is string { Length: 5 } s) return 3;]@94 -> [if (o is string { Length: 7 } s7) return 5;]@90", "Update [return 1;]@36 -> [return 4;]@39", "Update [s]@124 -> [s7]@120", "Update [return 3;]@127 -> [return 5;]@124"); } [Fact] public void RecursivePatterns_Reorder() { var src1 = @"var r = obj switch { string s when s.Length > 0 => (s, obj1) switch { (""a"", int i) => i, _ => 0 }, int i => i * i, _ => -1 }; "; var src2 = @"var r = obj switch { int i => i * i, string s when s.Length > 0 => (s, obj1) switch { (""a"", int i) => i, _ => 0 }, _ => -1 }; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [int i => i * i]@140 -> @29", "Move [i]@102 -> @33", "Move [i]@144 -> @123"); } [Fact] public void CasePattern_UpdateInsert() { var src1 = @" switch(shape) { case Circle c: return 1; default: return 4; } "; var src2 = @" switch(shape) { case Circle c1: return 1; case Point p: return 0; default: return 4; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c: return 1;]@26 -> [case Circle c1: return 1;]@26", "Insert [case Point p: return 0;]@57", "Insert [case Point p:]@57", "Insert [return 0;]@71", "Update [c]@38 -> [c1]@38", "Insert [p]@68"); } [Fact] public void CasePattern_UpdateDelete() { var src1 = @" switch(shape) { case Point p: return 0; case Circle c: A(c); break; default: return 4; } "; var src2 = @" switch(shape) { case Circle c1: A(c1); break; default: return 4; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c: A(c); break;]@55 -> [case Circle c1: A(c1); break;]@26", "Update [A(c);]@70 -> [A(c1);]@42", "Update [c]@67 -> [c1]@38", "Delete [case Point p: return 0;]@26", "Delete [case Point p:]@26", "Delete [p]@37", "Delete [return 0;]@40"); } [Fact] public void WhenCondition_Update() { var src1 = @" switch(shape) { case Circle c when (c < 10): return 1; case Circle c when (c > 100): return 2; } "; var src2 = @" switch(shape) { case Circle c when (c < 5): return 1; case Circle c2 when (c2 > 100): return 2; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c when (c < 10): return 1;]@26 -> [case Circle c when (c < 5): return 1;]@26", "Update [case Circle c when (c > 100): return 2;]@70 -> [case Circle c2 when (c2 > 100): return 2;]@69", "Update [when (c < 10)]@40 -> [when (c < 5)]@40", "Update [c]@82 -> [c2]@81", "Update [when (c > 100)]@84 -> [when (c2 > 100)]@84"); } [Fact] public void CasePatternWithWhenCondition_UpdateReorder() { var src1 = @" switch(shape) { case Rectangle r: return 0; case Circle c when (c.Radius < 10): return 1; case Circle c when (c.Radius > 100): return 2; } "; var src2 = @" switch(shape) { case Circle c when (c.Radius > 99): return 2; case Circle c when (c.Radius < 10): return 1; case Rectangle r: return 0; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [case Circle c when (c.Radius < 10): return 1;]@59 -> @77", "Reorder [case Circle c when (c.Radius > 100): return 2;]@110 -> @26", "Update [case Circle c when (c.Radius > 100): return 2;]@110 -> [case Circle c when (c.Radius > 99): return 2;]@26", "Move [c]@71 -> @38", "Update [when (c.Radius > 100)]@124 -> [when (c.Radius > 99)]@40", "Move [c]@122 -> @89"); } #endregion #region Ref [Fact] public void Ref_Update() { var src1 = @" ref int a = ref G(new int[] { 1, 2 }); ref int G(int[] p) { return ref p[1]; } "; var src2 = @" ref int32 a = ref G1(new int[] { 1, 2 }); ref int G1(int[] p) { return ref p[2]; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int G(int[] p) { return ref p[1]; }]@44 -> [ref int G1(int[] p) { return ref p[2]; }]@47", "Update [ref int a = ref G(new int[] { 1, 2 })]@4 -> [ref int32 a = ref G1(new int[] { 1, 2 })]@4", "Update [a = ref G(new int[] { 1, 2 })]@12 -> [a = ref G1(new int[] { 1, 2 })]@14"); } [Fact] public void Ref_Insert() { var src1 = @" int a = G(new int[] { 1, 2 }); int G(int[] p) { return p[1]; } "; var src2 = @" ref int32 a = ref G1(new int[] { 1, 2 }); ref int G1(int[] p) { return ref p[2]; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int G(int[] p) { return p[1]; }]@36 -> [ref int G1(int[] p) { return ref p[2]; }]@47", "Update [int a = G(new int[] { 1, 2 })]@4 -> [ref int32 a = ref G1(new int[] { 1, 2 })]@4", "Update [a = G(new int[] { 1, 2 })]@8 -> [a = ref G1(new int[] { 1, 2 })]@14"); } [Fact] public void Ref_Delete() { var src1 = @" ref int a = ref G(new int[] { 1, 2 }); ref int G(int[] p) { return ref p[1]; } "; var src2 = @" int32 a = G1(new int[] { 1, 2 }); int G1(int[] p) { return p[2]; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int G(int[] p) { return ref p[1]; }]@44 -> [int G1(int[] p) { return p[2]; }]@39", "Update [ref int a = ref G(new int[] { 1, 2 })]@4 -> [int32 a = G1(new int[] { 1, 2 })]@4", "Update [a = ref G(new int[] { 1, 2 })]@12 -> [a = G1(new int[] { 1, 2 })]@10"); } #endregion #region Tuples [Fact] public void TupleType_LocalVariables() { var src1 = @" (int a, string c) x = (a, string2); (int a, int b) y = (3, 4); (int a, int b, int c) z = (5, 6, 7); "; var src2 = @" (int a, int b) x = (a, string2); (int a, int b, string c) z1 = (5, 6, 7); (int a, int b) y2 = (3, 4); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [(int a, int b, int c) z = (5, 6, 7);]@69 -> @39", "Update [(int a, string c) x = (a, string2)]@4 -> [(int a, int b) x = (a, string2)]@4", "Update [(int a, int b, int c) z = (5, 6, 7)]@69 -> [(int a, int b, string c) z1 = (5, 6, 7)]@39", "Update [z = (5, 6, 7)]@91 -> [z1 = (5, 6, 7)]@64", "Update [y = (3, 4)]@56 -> [y2 = (3, 4)]@96"); } [Fact] public void TupleElementName() { var src1 = @"class C { (int a, int b) F(); }"; var src2 = @"class C { (int x, int b) F(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a, int b) F();]@10 -> [(int x, int b) F();]@10"); } [Fact] public void TupleInField() { var src1 = @"class C { private (int, int) _x = (1, 2); }"; var src2 = @"class C { private (int, string) _y = (1, 2); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) _x = (1, 2)]@18 -> [(int, string) _y = (1, 2)]@18", "Update [_x = (1, 2)]@29 -> [_y = (1, 2)]@32"); } [Fact] public void TupleInProperty() { var src1 = @"class C { public (int, int) Property1 { get { return (1, 2); } } }"; var src2 = @"class C { public (int, string) Property2 { get { return (1, string.Empty); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public (int, int) Property1 { get { return (1, 2); } }]@10 -> [public (int, string) Property2 { get { return (1, string.Empty); } }]@10", "Update [get { return (1, 2); }]@40 -> [get { return (1, string.Empty); }]@43"); } [Fact] public void TupleInDelegate() { var src1 = @"public delegate void EventHandler1((int, int) x);"; var src2 = @"public delegate void EventHandler2((int, int) y);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void EventHandler1((int, int) x);]@0 -> [public delegate void EventHandler2((int, int) y);]@0", "Update [(int, int) x]@35 -> [(int, int) y]@35"); } #endregion #region With Expressions [Fact] public void WithExpression_PropertyAdd() { var src1 = @"var x = y with { X = 1 };"; var src2 = @"var x = y with { X = 1, Y = 2 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1 }]@6 -> [x = y with { X = 1, Y = 2 }]@6"); } [Fact] public void WithExpression_PropertyDelete() { var src1 = @"var x = y with { X = 1, Y = 2 };"; var src2 = @"var x = y with { X = 1 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 2 }]@6 -> [x = y with { X = 1 }]@6"); } [Fact] public void WithExpression_PropertyChange() { var src1 = @"var x = y with { X = 1 };"; var src2 = @"var x = y with { Y = 1 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1 }]@6 -> [x = y with { Y = 1 }]@6"); } [Fact] public void WithExpression_PropertyValueChange() { var src1 = @"var x = y with { X = 1, Y = 1 };"; var src2 = @"var x = y with { X = 1, Y = 2 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 1 }]@6 -> [x = y with { X = 1, Y = 2 }]@6"); } [Fact] public void WithExpression_PropertyValueReorder() { var src1 = @"var x = y with { X = 1, Y = 1 };"; var src2 = @"var x = y with { Y = 1, X = 1 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 1 }]@6 -> [x = y with { Y = 1, X = 1 }]@6"); } #endregion #region Top Level Statements [Fact] public void TopLevelStatement_CaptureArgs() { var src1 = @" using System; var x = new Func<string>(() => ""Hello""); Console.WriteLine(x()); "; var src2 = @" using System; var x = new Func<string>(() => ""Hello"" + args[0]); Console.WriteLine(x()); "; var edits = GetTopEdits(src1, src2); // TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "using System;\r\n\r\nvar x = new Func<string>(() => \"Hello\" + args[0]);\r\n\r\nConsole.WriteLine(x());\r\n", "args")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void TopLevelStatement_InsertMultiScopeCapture() { var src1 = @" using System; foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; } "; var src2 = @" using System; foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; int f2(int a) => x0 + x1; // error: connecting previously disconnected closures } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1")); } #endregion } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/TestUtilities/EditAndContinue/EditAndContinueTestHelpers.cs
// 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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.EditAndContinue.AbstractEditAndContinueAnalyzer; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal abstract class EditAndContinueTestHelpers { public const EditAndContinueCapabilities BaselineCapabilities = EditAndContinueCapabilities.Baseline; public const EditAndContinueCapabilities Net5RuntimeCapabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.AddInstanceFieldToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.NewTypeDefinition; public const EditAndContinueCapabilities Net6RuntimeCapabilities = Net5RuntimeCapabilities | EditAndContinueCapabilities.ChangeCustomAttributes | EditAndContinueCapabilities.UpdateParameters; public abstract AbstractEditAndContinueAnalyzer Analyzer { get; } public abstract SyntaxNode FindNode(SyntaxNode root, TextSpan span); public abstract ImmutableArray<SyntaxNode> GetDeclarators(ISymbol method); public abstract string LanguageName { get; } public abstract TreeComparer<SyntaxNode> TopSyntaxComparer { get; } private void VerifyDocumentActiveStatementsAndExceptionRegions( ActiveStatementsDescription description, SyntaxTree oldTree, SyntaxTree newTree, ImmutableArray<ActiveStatement> actualNewActiveStatements, ImmutableArray<ImmutableArray<SourceFileSpan>> actualNewExceptionRegions) { // check active statements: AssertSpansEqual(description.NewMappedSpans, actualNewActiveStatements.OrderBy(x => x.Ordinal).Select(s => s.FileSpan), newTree); var oldRoot = oldTree.GetRoot(); // check old exception regions: foreach (var oldStatement in description.OldStatements) { var oldRegions = Analyzer.GetExceptionRegions( oldRoot, oldStatement.UnmappedSpan, isNonLeaf: oldStatement.Statement.IsNonLeaf, CancellationToken.None); AssertSpansEqual(oldStatement.ExceptionRegions.Spans, oldRegions.Spans, oldTree); } // check new exception regions: if (!actualNewExceptionRegions.IsDefault) { Assert.Equal(actualNewActiveStatements.Length, actualNewExceptionRegions.Length); Assert.Equal(description.NewMappedRegions.Length, actualNewExceptionRegions.Length); for (var i = 0; i < actualNewActiveStatements.Length; i++) { var activeStatement = actualNewActiveStatements[i]; AssertSpansEqual(description.NewMappedRegions[activeStatement.Ordinal], actualNewExceptionRegions[i], newTree); } } } internal void VerifyLineEdits( EditScript<SyntaxNode> editScript, SequencePointUpdates[] expectedLineEdits, SemanticEditDescription[]? expectedSemanticEdits, RudeEditDiagnosticDescription[]? expectedDiagnostics) { VerifySemantics( new[] { editScript }, TargetFramework.NetStandard20, new[] { new DocumentAnalysisResultsDescription(semanticEdits: expectedSemanticEdits, lineEdits: expectedLineEdits, diagnostics: expectedDiagnostics) }, capabilities: Net5RuntimeCapabilities); } internal void VerifySemantics(EditScript<SyntaxNode>[] editScripts, TargetFramework targetFramework, DocumentAnalysisResultsDescription[] expectedResults, EditAndContinueCapabilities? capabilities = null) { Assert.True(editScripts.Length == expectedResults.Length); var documentCount = expectedResults.Length; using var workspace = new AdhocWorkspace(FeaturesTestCompositions.Features.GetHostServices()); CreateProjects(editScripts, workspace, targetFramework, out var oldProject, out var newProject); var oldDocuments = oldProject.Documents.ToArray(); var newDocuments = newProject.Documents.ToArray(); Debug.Assert(oldDocuments.Length == newDocuments.Length); var oldTrees = oldDocuments.Select(d => d.GetSyntaxTreeSynchronously(default)!).ToArray(); var newTrees = newDocuments.Select(d => d.GetSyntaxTreeSynchronously(default)!).ToArray(); var testAccessor = Analyzer.GetTestAccessor(); var allEdits = new List<SemanticEditInfo>(); var lazyCapabilities = AsyncLazy.Create(capabilities ?? Net5RuntimeCapabilities); for (var documentIndex = 0; documentIndex < documentCount; documentIndex++) { var assertMessagePrefix = (documentCount > 0) ? $"Document #{documentIndex}" : null; var expectedResult = expectedResults[documentIndex]; var includeFirstLineInDiagnostics = expectedResult.Diagnostics.Any(d => d.FirstLine != null) == true; var newActiveStatementSpans = expectedResult.ActiveStatements.OldUnmappedTrackingSpans; // we need to rebuild the edit script, so that it operates on nodes associated with the same syntax trees backing the documents: var oldTree = oldTrees[documentIndex]; var newTree = newTrees[documentIndex]; var oldRoot = oldTree.GetRoot(); var newRoot = newTree.GetRoot(); var oldDocument = oldDocuments[documentIndex]; var newDocument = newDocuments[documentIndex]; var oldModel = oldDocument.GetSemanticModelAsync().Result; var newModel = newDocument.GetSemanticModelAsync().Result; Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); var lazyOldActiveStatementMap = AsyncLazy.Create(expectedResult.ActiveStatements.OldStatementsMap); var result = Analyzer.AnalyzeDocumentAsync(oldProject, lazyOldActiveStatementMap, newDocument, newActiveStatementSpans, lazyCapabilities, CancellationToken.None).Result; var oldText = oldDocument.GetTextSynchronously(default); var newText = newDocument.GetTextSynchronously(default); VerifyDiagnostics(expectedResult.Diagnostics, result.RudeEditErrors.ToDescription(newText, includeFirstLineInDiagnostics), assertMessagePrefix); if (!expectedResult.SemanticEdits.IsDefault) { if (result.HasChanges) { VerifySemanticEdits(expectedResult.SemanticEdits, result.SemanticEdits, oldModel.Compilation, newModel.Compilation, oldRoot, newRoot, assertMessagePrefix); allEdits.AddRange(result.SemanticEdits); } else { Assert.True(expectedResult.SemanticEdits.IsEmpty); Assert.True(result.SemanticEdits.IsDefault); } } if (!result.HasChanges) { Assert.True(result.ExceptionRegions.IsDefault); Assert.True(result.ActiveStatements.IsDefault); } else { // exception regions not available in presence of rude edits: Assert.Equal(!expectedResult.Diagnostics.IsEmpty, result.ExceptionRegions.IsDefault); VerifyDocumentActiveStatementsAndExceptionRegions( expectedResult.ActiveStatements, oldTree, newTree, result.ActiveStatements, result.ExceptionRegions); } if (!result.RudeEditErrors.IsEmpty) { Assert.True(result.LineEdits.IsDefault); Assert.True(expectedResult.LineEdits.IsDefaultOrEmpty); } else if (!expectedResult.LineEdits.IsDefault) { // check files of line edits: AssertEx.Equal( expectedResult.LineEdits.Select(e => e.FileName), result.LineEdits.Select(e => e.FileName), itemSeparator: ",\r\n", message: "File names of line edits differ in " + assertMessagePrefix); // check lines of line edits: _ = expectedResult.LineEdits.Zip(result.LineEdits, (expected, actual) => { AssertEx.Equal( expected.LineUpdates, actual.LineUpdates, itemSeparator: ",\r\n", itemInspector: s => $"new({s.OldLine}, {s.NewLine})", message: "Line deltas differ in " + assertMessagePrefix); return true; }).ToArray(); } } var duplicateNonPartial = allEdits .Where(e => e.PartialType == null) .GroupBy(e => e.Symbol, SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true)) .Where(g => g.Count() > 1) .Select(g => g.Key); AssertEx.Empty(duplicateNonPartial, "Duplicate non-partial symbols"); // check if we can merge edits without throwing: EditSession.MergePartialEdits(oldProject.GetCompilationAsync().Result!, newProject.GetCompilationAsync().Result!, allEdits, out var _, out var _, CancellationToken.None); } public static void VerifyDiagnostics(IEnumerable<RudeEditDiagnosticDescription> expected, IEnumerable<RudeEditDiagnostic> actual, SourceText newSource) => VerifyDiagnostics(expected, actual.ToDescription(newSource, expected.Any(d => d.FirstLine != null))); public static void VerifyDiagnostics(IEnumerable<RudeEditDiagnosticDescription> expected, IEnumerable<RudeEditDiagnosticDescription> actual, string? message = null) => AssertEx.SetEqual(expected, actual, message: message, itemSeparator: ",\r\n"); private void VerifySemanticEdits( ImmutableArray<SemanticEditDescription> expectedSemanticEdits, ImmutableArray<SemanticEditInfo> actualSemanticEdits, Compilation oldCompilation, Compilation newCompilation, SyntaxNode oldRoot, SyntaxNode newRoot, string? message = null) { // string comparison to simplify understanding why a test failed: AssertEx.Equal( expectedSemanticEdits.Select(e => $"{e.Kind}: {e.SymbolProvider(newCompilation)}"), actualSemanticEdits.NullToEmpty().Select(e => $"{e.Kind}: {e.Symbol.Resolve(newCompilation).Symbol}"), message: message); for (var i = 0; i < actualSemanticEdits.Length; i++) { var expectedSemanticEdit = expectedSemanticEdits[i]; var actualSemanticEdit = actualSemanticEdits[i]; var editKind = expectedSemanticEdit.Kind; Assert.Equal(editKind, actualSemanticEdit.Kind); var expectedOldSymbol = (editKind == SemanticEditKind.Update) ? expectedSemanticEdit.SymbolProvider(oldCompilation) : null; var expectedNewSymbol = expectedSemanticEdit.SymbolProvider(newCompilation); var symbolKey = actualSemanticEdit.Symbol; if (editKind == SemanticEditKind.Update) { Assert.Equal(expectedOldSymbol, symbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true).Symbol); Assert.Equal(expectedNewSymbol, symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true).Symbol); } else if (editKind is SemanticEditKind.Insert or SemanticEditKind.Replace) { Assert.Equal(expectedNewSymbol, symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true).Symbol); } else { Assert.False(true, "Only Update, Insert or Replace allowed"); } // Partial types must match: Assert.Equal( expectedSemanticEdit.PartialType?.Invoke(newCompilation), actualSemanticEdit.PartialType?.Resolve(newCompilation, ignoreAssemblyKey: true).Symbol); // Edit is expected to have a syntax map: var actualSyntaxMap = actualSemanticEdit.SyntaxMap; Assert.Equal(expectedSemanticEdit.HasSyntaxMap, actualSyntaxMap != null); // If expected map is specified validate its mappings with the actual one: var expectedSyntaxMap = expectedSemanticEdit.SyntaxMap; if (expectedSyntaxMap != null) { Contract.ThrowIfNull(actualSyntaxMap); VerifySyntaxMap(oldRoot, newRoot, expectedSyntaxMap, actualSyntaxMap); } } } private void VerifySyntaxMap( SyntaxNode oldRoot, SyntaxNode newRoot, IEnumerable<KeyValuePair<TextSpan, TextSpan>> expectedSyntaxMap, Func<SyntaxNode, SyntaxNode?> actualSyntaxMap) { foreach (var expectedSpanMapping in expectedSyntaxMap) { var newNode = FindNode(newRoot, expectedSpanMapping.Value); var expectedOldNode = FindNode(oldRoot, expectedSpanMapping.Key); var actualOldNode = actualSyntaxMap(newNode); Assert.Equal(expectedOldNode, actualOldNode); } } private void CreateProjects(EditScript<SyntaxNode>[] editScripts, AdhocWorkspace workspace, TargetFramework targetFramework, out Project oldProject, out Project newProject) { oldProject = workspace.AddProject("project", LanguageName).WithMetadataReferences(TargetFrameworkUtil.GetReferences(targetFramework)); var documentIndex = 0; foreach (var editScript in editScripts) { oldProject = oldProject.AddDocument(documentIndex.ToString(), editScript.Match.OldRoot).Project; documentIndex++; } var newSolution = oldProject.Solution; documentIndex = 0; foreach (var oldDocument in oldProject.Documents) { newSolution = newSolution.WithDocumentSyntaxRoot(oldDocument.Id, editScripts[documentIndex].Match.NewRoot, PreservationMode.PreserveIdentity); documentIndex++; } newProject = newSolution.Projects.Single(); } private static void AssertSpansEqual(IEnumerable<SourceFileSpan> expected, IEnumerable<SourceFileSpan> actual, SyntaxTree newTree) { AssertEx.Equal( expected, actual, itemSeparator: "\r\n", itemInspector: span => DisplaySpan(newTree, span)); } private static string DisplaySpan(SyntaxTree tree, SourceFileSpan span) { if (tree.FilePath != span.Path) { return span.ToString(); } var text = tree.GetText(); var code = text.GetSubText(text.Lines.GetTextSpan(span.Span)).ToString().Replace("\r\n", " "); return $"{span}: [{code}]"; } internal static IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> GetMethodMatches(AbstractEditAndContinueAnalyzer analyzer, Match<SyntaxNode> bodyMatch) { Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas = null; var map = analyzer.GetTestAccessor().ComputeMap(bodyMatch, new ArrayBuilder<ActiveNode>(), ref lazyActiveOrMatchedLambdas, new ArrayBuilder<RudeEditDiagnostic>()); var result = new Dictionary<SyntaxNode, SyntaxNode>(); foreach (var pair in map.Forward) { if (pair.Value == bodyMatch.NewRoot) { Assert.Same(pair.Key, bodyMatch.OldRoot); continue; } result.Add(pair.Key, pair.Value); } return result; } public static MatchingPairs ToMatchingPairs(Match<SyntaxNode> match) => ToMatchingPairs(match.Matches.Where(partners => partners.Key != match.OldRoot)); public static MatchingPairs ToMatchingPairs(IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> matches) { return new MatchingPairs(matches .OrderBy(partners => partners.Key.GetLocation().SourceSpan.Start) .ThenByDescending(partners => partners.Key.Span.Length) .Select(partners => new MatchingPair { Old = partners.Key.ToString().Replace("\r\n", " ").Replace("\n", " "), New = partners.Value.ToString().Replace("\r\n", " ").Replace("\n", " ") })); } } internal static class EditScriptTestUtils { public static void VerifyEdits<TNode>(this EditScript<TNode> actual, params string[] expected) => AssertEx.Equal(expected, actual.Edits.Select(e => e.GetDebuggerDisplay()), itemSeparator: ",\r\n"); } }
// 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 System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.EditAndContinue.AbstractEditAndContinueAnalyzer; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal abstract class EditAndContinueTestHelpers { public const EditAndContinueCapabilities BaselineCapabilities = EditAndContinueCapabilities.Baseline; public const EditAndContinueCapabilities Net5RuntimeCapabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.AddInstanceFieldToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.NewTypeDefinition; public const EditAndContinueCapabilities Net6RuntimeCapabilities = Net5RuntimeCapabilities | EditAndContinueCapabilities.ChangeCustomAttributes | EditAndContinueCapabilities.UpdateParameters; public abstract AbstractEditAndContinueAnalyzer Analyzer { get; } public abstract SyntaxNode FindNode(SyntaxNode root, TextSpan span); public abstract ImmutableArray<SyntaxNode> GetDeclarators(ISymbol method); public abstract string LanguageName { get; } public abstract TreeComparer<SyntaxNode> TopSyntaxComparer { get; } private void VerifyDocumentActiveStatementsAndExceptionRegions( ActiveStatementsDescription description, SyntaxTree oldTree, SyntaxTree newTree, ImmutableArray<ActiveStatement> actualNewActiveStatements, ImmutableArray<ImmutableArray<SourceFileSpan>> actualNewExceptionRegions) { // check active statements: AssertSpansEqual(description.NewMappedSpans, actualNewActiveStatements.OrderBy(x => x.Ordinal).Select(s => s.FileSpan), newTree); var oldRoot = oldTree.GetRoot(); // check old exception regions: foreach (var oldStatement in description.OldStatements) { var oldRegions = Analyzer.GetExceptionRegions( oldRoot, oldStatement.UnmappedSpan, isNonLeaf: oldStatement.Statement.IsNonLeaf, CancellationToken.None); AssertSpansEqual(oldStatement.ExceptionRegions.Spans, oldRegions.Spans, oldTree); } // check new exception regions: if (!actualNewExceptionRegions.IsDefault) { Assert.Equal(actualNewActiveStatements.Length, actualNewExceptionRegions.Length); Assert.Equal(description.NewMappedRegions.Length, actualNewExceptionRegions.Length); for (var i = 0; i < actualNewActiveStatements.Length; i++) { var activeStatement = actualNewActiveStatements[i]; AssertSpansEqual(description.NewMappedRegions[activeStatement.Ordinal], actualNewExceptionRegions[i], newTree); } } } internal void VerifyLineEdits( EditScript<SyntaxNode> editScript, SequencePointUpdates[] expectedLineEdits, SemanticEditDescription[]? expectedSemanticEdits, RudeEditDiagnosticDescription[]? expectedDiagnostics) { VerifySemantics( new[] { editScript }, TargetFramework.NetStandard20, new[] { new DocumentAnalysisResultsDescription(semanticEdits: expectedSemanticEdits, lineEdits: expectedLineEdits, diagnostics: expectedDiagnostics) }, capabilities: Net5RuntimeCapabilities); } internal void VerifySemantics(EditScript<SyntaxNode>[] editScripts, TargetFramework targetFramework, DocumentAnalysisResultsDescription[] expectedResults, EditAndContinueCapabilities? capabilities = null) { Assert.True(editScripts.Length == expectedResults.Length); var documentCount = expectedResults.Length; using var workspace = new AdhocWorkspace(FeaturesTestCompositions.Features.GetHostServices()); CreateProjects(editScripts, workspace, targetFramework, out var oldProject, out var newProject); var oldDocuments = oldProject.Documents.ToArray(); var newDocuments = newProject.Documents.ToArray(); Debug.Assert(oldDocuments.Length == newDocuments.Length); var oldTrees = oldDocuments.Select(d => d.GetSyntaxTreeSynchronously(default)!).ToArray(); var newTrees = newDocuments.Select(d => d.GetSyntaxTreeSynchronously(default)!).ToArray(); var testAccessor = Analyzer.GetTestAccessor(); var allEdits = new List<SemanticEditInfo>(); var lazyCapabilities = AsyncLazy.Create(capabilities ?? Net5RuntimeCapabilities); for (var documentIndex = 0; documentIndex < documentCount; documentIndex++) { var assertMessagePrefix = (documentCount > 0) ? $"Document #{documentIndex}" : null; var expectedResult = expectedResults[documentIndex]; var includeFirstLineInDiagnostics = expectedResult.Diagnostics.Any(d => d.FirstLine != null) == true; var newActiveStatementSpans = expectedResult.ActiveStatements.OldUnmappedTrackingSpans; // we need to rebuild the edit script, so that it operates on nodes associated with the same syntax trees backing the documents: var oldTree = oldTrees[documentIndex]; var newTree = newTrees[documentIndex]; var oldRoot = oldTree.GetRoot(); var newRoot = newTree.GetRoot(); var oldDocument = oldDocuments[documentIndex]; var newDocument = newDocuments[documentIndex]; var oldModel = oldDocument.GetSemanticModelAsync().Result; var newModel = newDocument.GetSemanticModelAsync().Result; Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); var lazyOldActiveStatementMap = AsyncLazy.Create(expectedResult.ActiveStatements.OldStatementsMap); var result = Analyzer.AnalyzeDocumentAsync(oldProject, lazyOldActiveStatementMap, newDocument, newActiveStatementSpans, lazyCapabilities, CancellationToken.None).Result; var oldText = oldDocument.GetTextSynchronously(default); var newText = newDocument.GetTextSynchronously(default); VerifyDiagnostics(expectedResult.Diagnostics, result.RudeEditErrors.ToDescription(newText, includeFirstLineInDiagnostics), assertMessagePrefix); if (!expectedResult.SemanticEdits.IsDefault) { if (result.HasChanges) { VerifySemanticEdits(expectedResult.SemanticEdits, result.SemanticEdits, oldModel.Compilation, newModel.Compilation, oldRoot, newRoot, assertMessagePrefix); allEdits.AddRange(result.SemanticEdits); } else { Assert.True(expectedResult.SemanticEdits.IsEmpty); Assert.True(result.SemanticEdits.IsDefault); } } if (!result.HasChanges) { Assert.True(result.ExceptionRegions.IsDefault); Assert.True(result.ActiveStatements.IsDefault); } else { // exception regions not available in presence of rude edits: Assert.Equal(!expectedResult.Diagnostics.IsEmpty, result.ExceptionRegions.IsDefault); VerifyDocumentActiveStatementsAndExceptionRegions( expectedResult.ActiveStatements, oldTree, newTree, result.ActiveStatements, result.ExceptionRegions); } if (!result.RudeEditErrors.IsEmpty) { Assert.True(result.LineEdits.IsDefault); Assert.True(expectedResult.LineEdits.IsDefaultOrEmpty); } else if (!expectedResult.LineEdits.IsDefault) { // check files of line edits: AssertEx.Equal( expectedResult.LineEdits.Select(e => e.FileName), result.LineEdits.Select(e => e.FileName), itemSeparator: ",\r\n", message: "File names of line edits differ in " + assertMessagePrefix); // check lines of line edits: _ = expectedResult.LineEdits.Zip(result.LineEdits, (expected, actual) => { AssertEx.Equal( expected.LineUpdates, actual.LineUpdates, itemSeparator: ",\r\n", itemInspector: s => $"new({s.OldLine}, {s.NewLine})", message: "Line deltas differ in " + assertMessagePrefix); return true; }).ToArray(); } } var duplicateNonPartial = allEdits .Where(e => e.PartialType == null) .GroupBy(e => e.Symbol, SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true)) .Where(g => g.Count() > 1) .Select(g => g.Key); AssertEx.Empty(duplicateNonPartial, "Duplicate non-partial symbols"); // check if we can merge edits without throwing: EditSession.MergePartialEdits(oldProject.GetCompilationAsync().Result!, newProject.GetCompilationAsync().Result!, allEdits, out var _, out var _, CancellationToken.None); } public static void VerifyDiagnostics(IEnumerable<RudeEditDiagnosticDescription> expected, IEnumerable<RudeEditDiagnostic> actual, SourceText newSource) => VerifyDiagnostics(expected, actual.ToDescription(newSource, expected.Any(d => d.FirstLine != null))); public static void VerifyDiagnostics(IEnumerable<RudeEditDiagnosticDescription> expected, IEnumerable<RudeEditDiagnosticDescription> actual, string? message = null) => AssertEx.SetEqual(expected, actual, message: message, itemSeparator: ",\r\n"); private void VerifySemanticEdits( ImmutableArray<SemanticEditDescription> expectedSemanticEdits, ImmutableArray<SemanticEditInfo> actualSemanticEdits, Compilation oldCompilation, Compilation newCompilation, SyntaxNode oldRoot, SyntaxNode newRoot, string? message = null) { // string comparison to simplify understanding why a test failed: AssertEx.Equal( expectedSemanticEdits.Select(e => $"{e.Kind}: {e.SymbolProvider(newCompilation)}"), actualSemanticEdits.NullToEmpty().Select(e => $"{e.Kind}: {e.Symbol.Resolve(newCompilation).Symbol}"), message: message); for (var i = 0; i < actualSemanticEdits.Length; i++) { var expectedSemanticEdit = expectedSemanticEdits[i]; var actualSemanticEdit = actualSemanticEdits[i]; var editKind = expectedSemanticEdit.Kind; Assert.Equal(editKind, actualSemanticEdit.Kind); var expectedOldSymbol = (editKind == SemanticEditKind.Update) ? expectedSemanticEdit.SymbolProvider(oldCompilation) : null; var expectedNewSymbol = expectedSemanticEdit.SymbolProvider(newCompilation); var symbolKey = actualSemanticEdit.Symbol; if (editKind == SemanticEditKind.Update) { Assert.Equal(expectedOldSymbol, symbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true).Symbol); Assert.Equal(expectedNewSymbol, symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true).Symbol); } else if (editKind is SemanticEditKind.Insert or SemanticEditKind.Replace) { Assert.Equal(expectedNewSymbol, symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true).Symbol); } else { Assert.False(true, "Only Update, Insert or Replace allowed"); } // Partial types must match: Assert.Equal( expectedSemanticEdit.PartialType?.Invoke(newCompilation), actualSemanticEdit.PartialType?.Resolve(newCompilation, ignoreAssemblyKey: true).Symbol); // Edit is expected to have a syntax map: var actualSyntaxMap = actualSemanticEdit.SyntaxMap; Assert.Equal(expectedSemanticEdit.HasSyntaxMap, actualSyntaxMap != null); // If expected map is specified validate its mappings with the actual one: var expectedSyntaxMap = expectedSemanticEdit.SyntaxMap; if (expectedSyntaxMap != null) { Contract.ThrowIfNull(actualSyntaxMap); VerifySyntaxMap(oldRoot, newRoot, expectedSyntaxMap, actualSyntaxMap); } } } private void VerifySyntaxMap( SyntaxNode oldRoot, SyntaxNode newRoot, IEnumerable<KeyValuePair<TextSpan, TextSpan>> expectedSyntaxMap, Func<SyntaxNode, SyntaxNode?> actualSyntaxMap) { foreach (var expectedSpanMapping in expectedSyntaxMap) { var newNode = FindNode(newRoot, expectedSpanMapping.Value); var expectedOldNode = FindNode(oldRoot, expectedSpanMapping.Key); var actualOldNode = actualSyntaxMap(newNode); Assert.Equal(expectedOldNode, actualOldNode); } } private void CreateProjects(EditScript<SyntaxNode>[] editScripts, AdhocWorkspace workspace, TargetFramework targetFramework, out Project oldProject, out Project newProject) { oldProject = workspace.AddProject("project", LanguageName).WithMetadataReferences(TargetFrameworkUtil.GetReferences(targetFramework)); var documentIndex = 0; foreach (var editScript in editScripts) { oldProject = oldProject.AddDocument(documentIndex.ToString(), editScript.Match.OldRoot).Project; documentIndex++; } var newSolution = oldProject.Solution; documentIndex = 0; foreach (var oldDocument in oldProject.Documents) { newSolution = newSolution.WithDocumentSyntaxRoot(oldDocument.Id, editScripts[documentIndex].Match.NewRoot, PreservationMode.PreserveIdentity); documentIndex++; } newProject = newSolution.Projects.Single(); } private static void AssertSpansEqual(IEnumerable<SourceFileSpan> expected, IEnumerable<SourceFileSpan> actual, SyntaxTree newTree) { AssertEx.Equal( expected, actual, itemSeparator: "\r\n", itemInspector: span => DisplaySpan(newTree, span)); } private static string DisplaySpan(SyntaxTree tree, SourceFileSpan span) { if (tree.FilePath != span.Path) { return span.ToString(); } var text = tree.GetText(); var code = text.GetSubText(text.Lines.GetTextSpan(span.Span)).ToString().Replace("\r\n", " "); return $"{span}: [{code}]"; } internal static IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> GetMethodMatches(AbstractEditAndContinueAnalyzer analyzer, Match<SyntaxNode> bodyMatch) { Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas = null; var map = analyzer.GetTestAccessor().ComputeMap(bodyMatch, new ArrayBuilder<ActiveNode>(), ref lazyActiveOrMatchedLambdas, new ArrayBuilder<RudeEditDiagnostic>()); var result = new Dictionary<SyntaxNode, SyntaxNode>(); foreach (var pair in map.Forward) { if (pair.Value == bodyMatch.NewRoot) { Assert.Same(pair.Key, bodyMatch.OldRoot); continue; } result.Add(pair.Key, pair.Value); } return result; } public static MatchingPairs ToMatchingPairs(Match<SyntaxNode> match) => ToMatchingPairs(match.Matches.Where(partners => partners.Key != match.OldRoot)); public static MatchingPairs ToMatchingPairs(IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> matches) { return new MatchingPairs(matches .OrderBy(partners => partners.Key.GetLocation().SourceSpan.Start) .ThenByDescending(partners => partners.Key.Span.Length) .Select(partners => new MatchingPair { Old = partners.Key.ToString().Replace("\r\n", " ").Replace("\n", " "), New = partners.Value.ToString().Replace("\r\n", " ").Replace("\n", " ") })); } } internal static class EditScriptTestUtils { public static void VerifyEdits<TNode>(this EditScript<TNode> actual, params string[] expected) => AssertEx.Equal(expected, actual.Edits.Select(e => e.GetDebuggerDisplay()), itemSeparator: ",\r\n", itemInspector: s => $"\"{s}\""); } }
1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/Core/Tags/IImageIdService.cs
// 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. #nullable disable using System.Collections.Immutable; using Microsoft.VisualStudio.Core.Imaging; namespace Microsoft.CodeAnalysis.Editor.Tags { /// <summary> /// Extensibility point for hosts to display <see cref="ImageId"/>s for items with Tags. /// </summary> internal interface IImageIdService { bool TryGetImageId(ImmutableArray<string> tags, out ImageId imageId); } }
// 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. #nullable disable using System.Collections.Immutable; using Microsoft.VisualStudio.Core.Imaging; namespace Microsoft.CodeAnalysis.Editor.Tags { /// <summary> /// Extensibility point for hosts to display <see cref="ImageId"/>s for items with Tags. /// </summary> internal interface IImageIdService { bool TryGetImageId(ImmutableArray<string> tags, out ImageId imageId); } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/CSharp/Portable/ReassignedVariable/CSharpReassignedVariableService.cs
// 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 System; using System.Composition; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.ReassignedVariable; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ReassignedVariable { [ExportLanguageService(typeof(IReassignedVariableService), LanguageNames.CSharp), Shared] internal class CSharpReassignedVariableService : AbstractReassignedVariableService< ParameterSyntax, VariableDeclaratorSyntax, SingleVariableDesignationSyntax, IdentifierNameSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpReassignedVariableService() { } protected override SyntaxToken GetIdentifierOfVariable(VariableDeclaratorSyntax variable) => variable.Identifier; protected override SyntaxToken GetIdentifierOfSingleVariableDesignation(SingleVariableDesignationSyntax variable) => variable.Identifier; protected override bool HasInitializer(SyntaxNode variable) => (variable as VariableDeclaratorSyntax)?.Initializer != null; protected override SyntaxNode GetMemberBlock(SyntaxNode methodOrPropertyDeclaration) => methodOrPropertyDeclaration; protected override SyntaxNode GetParentScope(SyntaxNode localDeclaration) { var current = localDeclaration; while (current != null) { if (current is BlockSyntax or SwitchSectionSyntax or ArrowExpressionClauseSyntax or AnonymousMethodExpressionSyntax or MemberDeclarationSyntax) break; current = current.Parent; } Contract.ThrowIfNull(current, "Couldn't find a suitable parent of this local declaration"); return current is GlobalStatementSyntax ? current.GetRequiredParent() : current; } } }
// 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 System; using System.Composition; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.ReassignedVariable; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ReassignedVariable { [ExportLanguageService(typeof(IReassignedVariableService), LanguageNames.CSharp), Shared] internal class CSharpReassignedVariableService : AbstractReassignedVariableService< ParameterSyntax, VariableDeclaratorSyntax, SingleVariableDesignationSyntax, IdentifierNameSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpReassignedVariableService() { } protected override SyntaxToken GetIdentifierOfVariable(VariableDeclaratorSyntax variable) => variable.Identifier; protected override SyntaxToken GetIdentifierOfSingleVariableDesignation(SingleVariableDesignationSyntax variable) => variable.Identifier; protected override bool HasInitializer(SyntaxNode variable) => (variable as VariableDeclaratorSyntax)?.Initializer != null; protected override SyntaxNode GetMemberBlock(SyntaxNode methodOrPropertyDeclaration) => methodOrPropertyDeclaration; protected override SyntaxNode GetParentScope(SyntaxNode localDeclaration) { var current = localDeclaration; while (current != null) { if (current is BlockSyntax or SwitchSectionSyntax or ArrowExpressionClauseSyntax or AnonymousMethodExpressionSyntax or MemberDeclarationSyntax) break; current = current.Parent; } Contract.ThrowIfNull(current, "Couldn't find a suitable parent of this local declaration"); return current is GlobalStatementSyntax ? current.GetRequiredParent() : current; } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/AbstractSyntaxTreeFactoryService.AbstractRecoverableSyntaxRoot.cs
// 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 System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal abstract partial class AbstractSyntaxTreeFactoryService { internal struct SyntaxTreeInfo { public readonly string FilePath; public readonly ParseOptions Options; public readonly ValueSource<TextAndVersion> TextSource; public readonly Encoding Encoding; public readonly int Length; public SyntaxTreeInfo( string filePath, ParseOptions options, ValueSource<TextAndVersion> textSource, Encoding encoding, int length) { FilePath = filePath ?? string.Empty; Options = options; TextSource = textSource; Encoding = encoding; Length = length; } internal bool TryGetText([NotNullWhen(true)] out SourceText? text) { if (TextSource.TryGetValue(out var textAndVersion)) { text = textAndVersion.Text; return true; } text = null; return false; } internal async Task<SourceText> GetTextAsync(CancellationToken cancellationToken) { var textAndVersion = await TextSource.GetValueAsync(cancellationToken).ConfigureAwait(false); return textAndVersion.Text; } internal SyntaxTreeInfo WithFilePath(string path) { return new SyntaxTreeInfo( path, Options, TextSource, Encoding, Length); } internal SyntaxTreeInfo WithOptionsAndLength(ParseOptions options, int length) { return new SyntaxTreeInfo( FilePath, options, TextSource, Encoding, length); } } internal sealed class RecoverableSyntaxRoot<TRoot> : WeaklyCachedRecoverableValueSource<TRoot> where TRoot : SyntaxNode { private ITemporaryStreamStorage? _storage; private readonly IRecoverableSyntaxTree<TRoot> _containingTree; private readonly AbstractSyntaxTreeFactoryService _service; public RecoverableSyntaxRoot( AbstractSyntaxTreeFactoryService service, TRoot root, IRecoverableSyntaxTree<TRoot> containingTree) : base(new ConstantValueSource<TRoot>(containingTree.CloneNodeAsRoot(root))) { _service = service; _containingTree = containingTree; } private RecoverableSyntaxRoot( RecoverableSyntaxRoot<TRoot> originalRoot, IRecoverableSyntaxTree<TRoot> containingTree) : base(originalRoot) { Contract.ThrowIfNull(originalRoot._storage); _service = originalRoot._service; _storage = originalRoot._storage; _containingTree = containingTree; } public RecoverableSyntaxRoot<TRoot> WithSyntaxTree(IRecoverableSyntaxTree<TRoot> containingTree) { // at this point, we should either have strongly held root or _storage should not be null if (TryGetValue(out var root)) { // we have strongly held root return new RecoverableSyntaxRoot<TRoot>(_service, root, containingTree); } else { // we have _storage here. _storage != null is checked inside return new RecoverableSyntaxRoot<TRoot>(this, containingTree); } } protected override async Task SaveAsync(TRoot root, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_storage == null); // Cannot save more than once // tree will be always held alive in memory, but nodes come and go. serialize nodes to storage using var stream = SerializableBytes.CreateWritableStream(); root.SerializeTo(stream, cancellationToken); stream.Position = 0; _storage = _service.LanguageServices.WorkspaceServices.GetRequiredService<ITemporaryStorageService>().CreateTemporaryStreamStorage(cancellationToken); await _storage.WriteStreamAsync(stream, cancellationToken).ConfigureAwait(false); } protected override async Task<TRoot> RecoverAsync(CancellationToken cancellationToken) { Contract.ThrowIfNull(_storage); using (RoslynEventSource.LogInformationalBlock(FunctionId.Workspace_Recoverable_RecoverRootAsync, _containingTree.FilePath, cancellationToken)) { using var stream = await _storage.ReadStreamAsync(cancellationToken).ConfigureAwait(false); return RecoverRoot(stream, cancellationToken); } } protected override TRoot Recover(CancellationToken cancellationToken) { Contract.ThrowIfNull(_storage); using (RoslynEventSource.LogInformationalBlock(FunctionId.Workspace_Recoverable_RecoverRoot, _containingTree.FilePath, cancellationToken)) { using var stream = _storage.ReadStream(cancellationToken); return RecoverRoot(stream, cancellationToken); } } private TRoot RecoverRoot(Stream stream, CancellationToken cancellationToken) => _containingTree.CloneNodeAsRoot((TRoot)_service.DeserializeNodeFrom(stream, cancellationToken)); } } internal interface IRecoverableSyntaxTree<TRoot> where TRoot : SyntaxNode { string FilePath { get; } TRoot CloneNodeAsRoot(TRoot root); } }
// 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 System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal abstract partial class AbstractSyntaxTreeFactoryService { internal struct SyntaxTreeInfo { public readonly string FilePath; public readonly ParseOptions Options; public readonly ValueSource<TextAndVersion> TextSource; public readonly Encoding Encoding; public readonly int Length; public SyntaxTreeInfo( string filePath, ParseOptions options, ValueSource<TextAndVersion> textSource, Encoding encoding, int length) { FilePath = filePath ?? string.Empty; Options = options; TextSource = textSource; Encoding = encoding; Length = length; } internal bool TryGetText([NotNullWhen(true)] out SourceText? text) { if (TextSource.TryGetValue(out var textAndVersion)) { text = textAndVersion.Text; return true; } text = null; return false; } internal async Task<SourceText> GetTextAsync(CancellationToken cancellationToken) { var textAndVersion = await TextSource.GetValueAsync(cancellationToken).ConfigureAwait(false); return textAndVersion.Text; } internal SyntaxTreeInfo WithFilePath(string path) { return new SyntaxTreeInfo( path, Options, TextSource, Encoding, Length); } internal SyntaxTreeInfo WithOptionsAndLength(ParseOptions options, int length) { return new SyntaxTreeInfo( FilePath, options, TextSource, Encoding, length); } } internal sealed class RecoverableSyntaxRoot<TRoot> : WeaklyCachedRecoverableValueSource<TRoot> where TRoot : SyntaxNode { private ITemporaryStreamStorage? _storage; private readonly IRecoverableSyntaxTree<TRoot> _containingTree; private readonly AbstractSyntaxTreeFactoryService _service; public RecoverableSyntaxRoot( AbstractSyntaxTreeFactoryService service, TRoot root, IRecoverableSyntaxTree<TRoot> containingTree) : base(new ConstantValueSource<TRoot>(containingTree.CloneNodeAsRoot(root))) { _service = service; _containingTree = containingTree; } private RecoverableSyntaxRoot( RecoverableSyntaxRoot<TRoot> originalRoot, IRecoverableSyntaxTree<TRoot> containingTree) : base(originalRoot) { Contract.ThrowIfNull(originalRoot._storage); _service = originalRoot._service; _storage = originalRoot._storage; _containingTree = containingTree; } public RecoverableSyntaxRoot<TRoot> WithSyntaxTree(IRecoverableSyntaxTree<TRoot> containingTree) { // at this point, we should either have strongly held root or _storage should not be null if (TryGetValue(out var root)) { // we have strongly held root return new RecoverableSyntaxRoot<TRoot>(_service, root, containingTree); } else { // we have _storage here. _storage != null is checked inside return new RecoverableSyntaxRoot<TRoot>(this, containingTree); } } protected override async Task SaveAsync(TRoot root, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_storage == null); // Cannot save more than once // tree will be always held alive in memory, but nodes come and go. serialize nodes to storage using var stream = SerializableBytes.CreateWritableStream(); root.SerializeTo(stream, cancellationToken); stream.Position = 0; _storage = _service.LanguageServices.WorkspaceServices.GetRequiredService<ITemporaryStorageService>().CreateTemporaryStreamStorage(cancellationToken); await _storage.WriteStreamAsync(stream, cancellationToken).ConfigureAwait(false); } protected override async Task<TRoot> RecoverAsync(CancellationToken cancellationToken) { Contract.ThrowIfNull(_storage); using (RoslynEventSource.LogInformationalBlock(FunctionId.Workspace_Recoverable_RecoverRootAsync, _containingTree.FilePath, cancellationToken)) { using var stream = await _storage.ReadStreamAsync(cancellationToken).ConfigureAwait(false); return RecoverRoot(stream, cancellationToken); } } protected override TRoot Recover(CancellationToken cancellationToken) { Contract.ThrowIfNull(_storage); using (RoslynEventSource.LogInformationalBlock(FunctionId.Workspace_Recoverable_RecoverRoot, _containingTree.FilePath, cancellationToken)) { using var stream = _storage.ReadStream(cancellationToken); return RecoverRoot(stream, cancellationToken); } } private TRoot RecoverRoot(Stream stream, CancellationToken cancellationToken) => _containingTree.CloneNodeAsRoot((TRoot)_service.DeserializeNodeFrom(stream, cancellationToken)); } } internal interface IRecoverableSyntaxTree<TRoot> where TRoot : SyntaxNode { string FilePath { get; } TRoot CloneNodeAsRoot(TRoot root); } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpTypeInferenceService.cs
// 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. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.LanguageServices.TypeInferenceService; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageService(typeof(ITypeInferenceService), LanguageNames.CSharp), Shared] internal partial class CSharpTypeInferenceService : AbstractTypeInferenceService { public static readonly CSharpTypeInferenceService Instance = new(); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")] public CSharpTypeInferenceService() { } protected override AbstractTypeInferrer CreateTypeInferrer(SemanticModel semanticModel, CancellationToken cancellationToken) => new TypeInferrer(semanticModel, cancellationToken); } }
// 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. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.LanguageServices.TypeInferenceService; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageService(typeof(ITypeInferenceService), LanguageNames.CSharp), Shared] internal partial class CSharpTypeInferenceService : AbstractTypeInferenceService { public static readonly CSharpTypeInferenceService Instance = new(); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")] public CSharpTypeInferenceService() { } protected override AbstractTypeInferrer CreateTypeInferrer(SemanticModel semanticModel, CancellationToken cancellationToken) => new TypeInferrer(semanticModel, cancellationToken); } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/VisualBasic/Portable/Classification/SyntaxClassification/OperatorOverloadSyntaxClassifier.vb
' 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. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Classification.Classifiers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers Friend Class OperatorOverloadSyntaxClassifier Inherits AbstractSyntaxClassifier Public Overrides ReadOnly Property SyntaxNodeTypes As ImmutableArray(Of Type) = ImmutableArray.Create( GetType(BinaryExpressionSyntax), GetType(UnaryExpressionSyntax)) Public Overrides Sub AddClassifications( workspace As Workspace, syntax As SyntaxNode, semanticModel As SemanticModel, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) Dim symbolInfo = semanticModel.GetSymbolInfo(syntax, cancellationToken) If TypeOf symbolInfo.Symbol Is IMethodSymbol AndAlso DirectCast(symbolInfo.Symbol, IMethodSymbol).MethodKind = MethodKind.UserDefinedOperator Then If TypeOf syntax Is BinaryExpressionSyntax Then result.Add(New ClassifiedSpan(DirectCast(syntax, BinaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded)) ElseIf TypeOf syntax Is UnaryExpressionSyntax Then result.Add(New ClassifiedSpan(DirectCast(syntax, UnaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded)) End If End If End Sub End Class End Namespace
' 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. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Classification.Classifiers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers Friend Class OperatorOverloadSyntaxClassifier Inherits AbstractSyntaxClassifier Public Overrides ReadOnly Property SyntaxNodeTypes As ImmutableArray(Of Type) = ImmutableArray.Create( GetType(BinaryExpressionSyntax), GetType(UnaryExpressionSyntax)) Public Overrides Sub AddClassifications( workspace As Workspace, syntax As SyntaxNode, semanticModel As SemanticModel, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) Dim symbolInfo = semanticModel.GetSymbolInfo(syntax, cancellationToken) If TypeOf symbolInfo.Symbol Is IMethodSymbol AndAlso DirectCast(symbolInfo.Symbol, IMethodSymbol).MethodKind = MethodKind.UserDefinedOperator Then If TypeOf syntax Is BinaryExpressionSyntax Then result.Add(New ClassifiedSpan(DirectCast(syntax, BinaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded)) ElseIf TypeOf syntax Is UnaryExpressionSyntax Then result.Add(New ClassifiedSpan(DirectCast(syntax, UnaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded)) End If End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/WarningItemLevel.vb
' 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. Imports System.Runtime.InteropServices Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop <StructLayout(LayoutKind.Sequential)> Friend Structure WarningItemLevel Public WarningId As Integer Public WarningLevel As WarningLevel End Structure End Namespace
' 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. Imports System.Runtime.InteropServices Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop <StructLayout(LayoutKind.Sequential)> Friend Structure WarningItemLevel Public WarningId As Integer Public WarningLevel As WarningLevel End Structure End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCommandLineArguments.vb
' 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. Imports System Imports System.Collections.Generic Imports System.Collections.ObjectModel Imports System.Diagnostics Imports System.IO Imports System.Linq Imports System.Runtime.InteropServices Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' The CommandLineArguments class provides members to Set and Get Visual Basic compilation and parse options. ''' </summary> Public NotInheritable Class VisualBasicCommandLineArguments Inherits CommandLineArguments ''' <summary> ''' Set and Get the Visual Basic compilation options. ''' </summary> ''' <returns>The currently set Visual Basic compilation options.</returns> Public Overloads Property CompilationOptions As VisualBasicCompilationOptions ''' <summary> ''' Set and Get the Visual Basic parse options. ''' </summary> ''' <returns>The currently set Visual Basic parse options.</returns> Public Overloads Property ParseOptions As VisualBasicParseOptions Friend OutputLevel As OutputLevel ''' <summary> ''' Gets the core Parse options. ''' </summary> ''' <returns>The currently set core parse options.</returns> Protected Overrides ReadOnly Property ParseOptionsCore As ParseOptions Get Return ParseOptions End Get End Property ''' <summary> ''' Gets the core compilation options. ''' </summary> ''' <returns>The currently set core compilation options.</returns> Protected Overrides ReadOnly Property CompilationOptionsCore As CompilationOptions Get Return CompilationOptions End Get End Property Friend Property DefaultCoreLibraryReference As CommandLineReference? Friend Sub New() End Sub Friend Overrides Function ResolveMetadataReferences( metadataResolver As MetadataReferenceResolver, diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, resolved As List(Of MetadataReference) ) As Boolean Dim result = MyBase.ResolveMetadataReferences(metadataResolver, diagnostics, messageProvider, resolved) ' If there were no references, don't try to add default Cor library reference. If Me.DefaultCoreLibraryReference IsNot Nothing AndAlso resolved.Count > 0 Then ' All references from arguments were resolved successfully. Let's see if we have a reference that can be used as a Cor library. For Each reference In resolved If reference.IsUnresolved Then Continue For End If Dim refProps = reference.Properties ' The logic about deciding what assembly is a candidate for being a Cor library here and in ' CommonReferenceManager<TCompilation, TAssemblySymbol>.IndexOfCorLibrary ' should be equivalent. If Not refProps.EmbedInteropTypes AndAlso refProps.Kind = MetadataImageKind.Assembly Then Try Dim assemblyMetadata = TryCast(DirectCast(reference, PortableExecutableReference).GetMetadataNoCopy(), AssemblyMetadata) If assemblyMetadata Is Nothing OrElse Not assemblyMetadata.IsValidAssembly() Then ' There will be some errors reported later. Return result End If Dim assembly As PEAssembly = assemblyMetadata.GetAssembly() If assembly.AssemblyReferences.Length = 0 AndAlso Not assembly.ContainsNoPiaLocalTypes AndAlso assembly.DeclaresTheObjectClass Then ' This reference looks like a valid Cor library candidate, bail out. Return result End If Catch e As BadImageFormatException ' error reported later Return result Catch e As IOException ' error reported later Return result End Try End If Next ' None of the supplied references could be used as a Cor library. Let's add a default one. Dim defaultCorLibrary = ResolveMetadataReference(Me.DefaultCoreLibraryReference.Value, metadataResolver, diagnostics, messageProvider).FirstOrDefault() If defaultCorLibrary Is Nothing OrElse defaultCorLibrary.IsUnresolved Then Debug.Assert(diagnostics Is Nothing OrElse diagnostics.Any()) Return False Else resolved.Insert(0, defaultCorLibrary) Return result End If End If Return result End Function End Class Friend Enum OutputLevel Quiet Normal Verbose End Enum End Namespace
' 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. Imports System Imports System.Collections.Generic Imports System.Collections.ObjectModel Imports System.Diagnostics Imports System.IO Imports System.Linq Imports System.Runtime.InteropServices Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' The CommandLineArguments class provides members to Set and Get Visual Basic compilation and parse options. ''' </summary> Public NotInheritable Class VisualBasicCommandLineArguments Inherits CommandLineArguments ''' <summary> ''' Set and Get the Visual Basic compilation options. ''' </summary> ''' <returns>The currently set Visual Basic compilation options.</returns> Public Overloads Property CompilationOptions As VisualBasicCompilationOptions ''' <summary> ''' Set and Get the Visual Basic parse options. ''' </summary> ''' <returns>The currently set Visual Basic parse options.</returns> Public Overloads Property ParseOptions As VisualBasicParseOptions Friend OutputLevel As OutputLevel ''' <summary> ''' Gets the core Parse options. ''' </summary> ''' <returns>The currently set core parse options.</returns> Protected Overrides ReadOnly Property ParseOptionsCore As ParseOptions Get Return ParseOptions End Get End Property ''' <summary> ''' Gets the core compilation options. ''' </summary> ''' <returns>The currently set core compilation options.</returns> Protected Overrides ReadOnly Property CompilationOptionsCore As CompilationOptions Get Return CompilationOptions End Get End Property Friend Property DefaultCoreLibraryReference As CommandLineReference? Friend Sub New() End Sub Friend Overrides Function ResolveMetadataReferences( metadataResolver As MetadataReferenceResolver, diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, resolved As List(Of MetadataReference) ) As Boolean Dim result = MyBase.ResolveMetadataReferences(metadataResolver, diagnostics, messageProvider, resolved) ' If there were no references, don't try to add default Cor library reference. If Me.DefaultCoreLibraryReference IsNot Nothing AndAlso resolved.Count > 0 Then ' All references from arguments were resolved successfully. Let's see if we have a reference that can be used as a Cor library. For Each reference In resolved If reference.IsUnresolved Then Continue For End If Dim refProps = reference.Properties ' The logic about deciding what assembly is a candidate for being a Cor library here and in ' CommonReferenceManager<TCompilation, TAssemblySymbol>.IndexOfCorLibrary ' should be equivalent. If Not refProps.EmbedInteropTypes AndAlso refProps.Kind = MetadataImageKind.Assembly Then Try Dim assemblyMetadata = TryCast(DirectCast(reference, PortableExecutableReference).GetMetadataNoCopy(), AssemblyMetadata) If assemblyMetadata Is Nothing OrElse Not assemblyMetadata.IsValidAssembly() Then ' There will be some errors reported later. Return result End If Dim assembly As PEAssembly = assemblyMetadata.GetAssembly() If assembly.AssemblyReferences.Length = 0 AndAlso Not assembly.ContainsNoPiaLocalTypes AndAlso assembly.DeclaresTheObjectClass Then ' This reference looks like a valid Cor library candidate, bail out. Return result End If Catch e As BadImageFormatException ' error reported later Return result Catch e As IOException ' error reported later Return result End Try End If Next ' None of the supplied references could be used as a Cor library. Let's add a default one. Dim defaultCorLibrary = ResolveMetadataReference(Me.DefaultCoreLibraryReference.Value, metadataResolver, diagnostics, messageProvider).FirstOrDefault() If defaultCorLibrary Is Nothing OrElse defaultCorLibrary.IsUnresolved Then Debug.Assert(diagnostics Is Nothing OrElse diagnostics.Any()) Return False Else resolved.Insert(0, defaultCorLibrary) Return result End If End If Return result End Function End Class Friend Enum OutputLevel Quiet Normal Verbose End Enum End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/CSharp/Test/Semantic/Semantics/StackAllocInitializerTests.cs
// 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. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.StackAllocInitializer)] public class StackAllocInitializerTests : CompilingTestBase { [Fact, WorkItem(33945, "https://github.com/dotnet/roslyn/issues/33945")] public void RestrictedTypesAllowedInStackalloc() { var comp = CreateCompilationWithMscorlibAndSpan(@" public ref struct RefS { } public ref struct RefG<T> { public T field; } class C { unsafe void M() { var x1 = stackalloc RefS[10]; var x2 = stackalloc RefG<string>[10]; var x3 = stackalloc RefG<int>[10]; var x4 = stackalloc System.TypedReference[10]; // Note: this should be disallowed by adding a dummy field to the ref assembly for TypedReference var x5 = stackalloc System.ArgIterator[10]; var x6 = stackalloc System.RuntimeArgumentHandle[10]; var y1 = new RefS[10]; var y2 = new RefG<string>[10]; var y3 = new RefG<int>[10]; var y4 = new System.TypedReference[10]; var y5 = new System.ArgIterator[10]; var y6 = new System.RuntimeArgumentHandle[10]; RefS[] z1 = null; RefG<string>[] z2 = null; RefG<int>[] z3 = null; System.TypedReference[] z4 = null; System.ArgIterator[] z5 = null; System.RuntimeArgumentHandle[] z6 = null; _ = z1; _ = z2; _ = z3; _ = z4; _ = z5; _ = z6; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (10,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('RefG<string>') // var x2 = stackalloc RefG<string>[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "RefG<string>").WithArguments("RefG<string>").WithLocation(10, 29), // (16,22): error CS0611: Array elements cannot be of type 'RefS' // var y1 = new RefS[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(16, 22), // (17,22): error CS0611: Array elements cannot be of type 'RefG<string>' // var y2 = new RefG<string>[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(17, 22), // (18,22): error CS0611: Array elements cannot be of type 'RefG<int>' // var y3 = new RefG<int>[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(18, 22), // (19,22): error CS0611: Array elements cannot be of type 'TypedReference' // var y4 = new System.TypedReference[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(19, 22), // (20,22): error CS0611: Array elements cannot be of type 'ArgIterator' // var y5 = new System.ArgIterator[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(20, 22), // (21,22): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle' // var y6 = new System.RuntimeArgumentHandle[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(21, 22), // (23,9): error CS0611: Array elements cannot be of type 'RefS' // RefS[] z1 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(23, 9), // (24,9): error CS0611: Array elements cannot be of type 'RefG<string>' // RefG<string>[] z2 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(24, 9), // (25,9): error CS0611: Array elements cannot be of type 'RefG<int>' // RefG<int>[] z3 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(25, 9), // (26,9): error CS0611: Array elements cannot be of type 'TypedReference' // System.TypedReference[] z4 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(26, 9), // (27,9): error CS0611: Array elements cannot be of type 'ArgIterator' // System.ArgIterator[] z5 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(27, 9), // (28,9): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle' // System.RuntimeArgumentHandle[] z6 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(28, 9) ); } [Fact] public void NoBestType_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { struct A {} struct B {} void Method(dynamic d, RefStruct r) { var p0 = stackalloc[] { new A(), new B() }; var p1 = stackalloc[] { }; var p2 = stackalloc[] { VoidMethod() }; var p3 = stackalloc[] { null }; var p4 = stackalloc[] { (1, null) }; var p5 = stackalloc[] { () => { } }; var p6 = stackalloc[] { new {} , new { i = 0 } }; var p7 = stackalloc[] { d }; var p8 = stackalloc[] { _ }; } public void VoidMethod() {} } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 a, T2 b) => throw null; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,28): error CS0246: The type or namespace name 'RefStruct' could not be found (are you missing a using directive or an assembly reference?) // void Method(dynamic d, RefStruct r) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "RefStruct").WithArguments("RefStruct").WithLocation(7, 28), // (9,18): error CS0826: No best type found for implicitly-typed array // var p0 = stackalloc[] { new A(), new B() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var p1 = stackalloc[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var p2 = stackalloc[] { VoidMethod() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var p3 = stackalloc[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var p4 = stackalloc[] { (1, null) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 18), // (14,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Action') // var p5 = stackalloc[] { () => { } }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { () => { } }").WithArguments("System.Action").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var p6 = stackalloc[] { new {} , new { i = 0 } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 18), // (16,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var p7 = stackalloc[] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 18), // (17,33): error CS0103: The name '_' does not exist in the current context // var p8 = stackalloc[] { _ }; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 33) ); } [Fact] public void NoBestType_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { struct A {} struct B {} void Method(dynamic d, bool c) { var p0 = c ? default : stackalloc[] { new A(), new B() }; var p1 = c ? default : stackalloc[] { }; var p2 = c ? default : stackalloc[] { VoidMethod() }; var p3 = c ? default : stackalloc[] { null }; var p4 = c ? default : stackalloc[] { (1, null) }; var p5 = c ? default : stackalloc[] { () => { } }; var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } }; var p7 = c ? default : stackalloc[] { d }; var p8 = c ? default : stackalloc[] { _ }; } public void VoidMethod() {} } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 a, T2 b) => throw null; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (9,32): error CS0826: No best type found for implicitly-typed array // var p0 = c ? default : stackalloc[] { new A(), new B() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 32), // (10,32): error CS0826: No best type found for implicitly-typed array // var p1 = c ? default : stackalloc[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 32), // (11,32): error CS0826: No best type found for implicitly-typed array // var p2 = c ? default : stackalloc[] { VoidMethod() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 32), // (12,32): error CS0826: No best type found for implicitly-typed array // var p3 = c ? default : stackalloc[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 32), // (13,32): error CS0826: No best type found for implicitly-typed array // var p4 = c ? default : stackalloc[] { (1, null) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 32), // (14,32): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Action') // var p5 = c ? default : stackalloc[] { () => { } }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { () => { } }").WithArguments("System.Action").WithLocation(14, 32), // (15,32): error CS0826: No best type found for implicitly-typed array // var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 32), // (16,32): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var p7 = c ? default : stackalloc[] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 32), // (17,47): error CS0103: The name '_' does not exist in the current context // var p8 = c ? default : stackalloc[] { _ }; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 47) ); } [Fact] public void InitializeWithSelf_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void Method1() { var obj1 = stackalloc int[1] { obj1 }; var obj2 = stackalloc int[ ] { obj2 }; var obj3 = stackalloc [ ] { obj3 }; } void Method2() { var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,40): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[1] { obj1 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 40), // (7,40): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 40), // (8,40): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 40), // (13,40): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 40), // (13,50): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 50), // (14,40): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 40), // (14,50): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 50), // (15,40): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 40), // (15,50): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 50) ); } [Fact] public void InitializeWithSelf_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void Method1(bool c) { var obj1 = c ? default : stackalloc int[1] { obj1 }; var obj2 = c ? default : stackalloc int[ ] { obj2 }; var obj3 = c ? default : stackalloc [ ] { obj3 }; } void Method2(bool c) { var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,54): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[1] { obj1 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 54), // (7,54): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 54), // (8,54): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 54), // (13,54): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 54), // (13,64): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 64), // (14,54): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 54), // (14,64): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 64), // (15,54): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 54), // (15,64): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 64) ); } [Fact] public void BadBestType_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { ref struct S {} void Method1(S s) { var obj1 = stackalloc[] { """" }; var obj2 = stackalloc[] { new {} }; var obj3 = stackalloc[] { s }; // OK } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // var obj1 = stackalloc[] { "" }; Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 20), // (8,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>') // var obj2 = stackalloc[] { new {} }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 20) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.String*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.String*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.String", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("<empty anonymous type>*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("Test.S*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("Test.S*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); } [Fact] public void BadBestType_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { ref struct S {} void Method1(S s, bool c) { var obj1 = c ? default : stackalloc[] { """" }; var obj2 = c ? default : stackalloc[] { new {} }; var obj3 = c ? default : stackalloc[] { s }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // var obj1 = c ? default : stackalloc[] { "" }; Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 34), // (8,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>') // var obj2 = c ? default : stackalloc[] { new {} }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 34), // (9,34): error CS0306: The type 'Test.S' may not be used as a type argument // var obj3 = c ? default : stackalloc[] { s }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "stackalloc[] { s }").WithArguments("Test.S").WithLocation(9, 34) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.String>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.String>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.String", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<Test.S>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<Test.S>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); } [Fact] public void TestFor_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { static void Method1() { int i = 0; for (var p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method2() { int i = 0; for (var p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method3() { int i = 0; for (var p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } public static void Main() { Method1(); Method2(); Method3(); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "123123123", verify: Verification.Fails); } [Fact] public void TestFor_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { static void Method1() { int i = 0; for (Span<int> p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method2() { int i = 0; for (Span<int> p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method3() { int i = 0; for (Span<int> p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } public static void Main() { Method1(); Method2(); Method3(); } }", TestOptions.DebugExe); comp.VerifyDiagnostics(); } [Fact] public void TestForTernary() { var comp = CreateCompilationWithMscorlibAndSpan(@" class Test { static void Method1(bool b) { for (var p = b ? stackalloc int[3] { 1, 2, 3 } : default; false;) {} for (var p = b ? stackalloc int[ ] { 1, 2, 3 } : default; false;) {} for (var p = b ? stackalloc [ ] { 1, 2, 3 } : default; false;) {} } }", TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [Fact] public void TestLock() { var source = @" class Test { static void Method1() { lock (stackalloc int[3] { 1, 2, 3 }) {} lock (stackalloc int[ ] { 1, 2, 3 }) {} lock (stackalloc [ ] { 1, 2, 3 }) {} } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (6,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 15), // (6,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int*").WithLocation(6, 15), // (7,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 15), // (7,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 15), // (8,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(8, 15) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (6,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 15), // (7,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 15), // (8,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 15) ); } [Fact] public void TestSelect() { var source = @" using System.Linq; class Test { static void Method1(int[] array) { var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (7,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 44), // (8,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 44), // (9,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 44) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (7,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 37), // (8,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 37), // (9,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(9, 37) ); } [Fact] public void TestLet() { var source = @" using System.Linq; class Test { static void Method1(int[] array) { var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (7,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 45), // (8,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 45), // (9,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 45) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (7,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(7, 75), // (8,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(8, 75), // (9,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(9, 75) ); } [Fact] public void TestAwait_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System.Threading.Tasks; unsafe class Test { async void M() { var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,32): error CS4004: Cannot await in an unsafe context // var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(1)").WithLocation(7, 32), // (7,60): error CS4004: Cannot await in an unsafe context // var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(2)").WithLocation(7, 60) ); } [Fact] public void TestAwait_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; using System.Threading.Tasks; class Test { async void M() { Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (8,38): error CS0150: A constant value is expected // Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_ConstantExpected, "await Task.FromResult(1)").WithLocation(8, 38), // (8,9): error CS4012: Parameters or locals of type 'Span<int>' cannot be declared in async methods or async lambda expressions. // Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "Span<int>").WithArguments("System.Span<int>").WithLocation(8, 9) ); } [Fact] public void TestSelfInSize() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void M() { var x = stackalloc int[x] { }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,32): error CS0841: Cannot use local variable 'x' before it is declared // var x = stackalloc int[x] { }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 32) ); } [Fact] public void WrongLength() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[10] { }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,20): error CS0847: An array initializer of length '10' is expected // var obj1 = stackalloc int[10] { }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc int[10] { }").WithArguments("10").WithLocation(6, 20) ); } [Fact] public void NoInit() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[]; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,34): error CS1586: Array creation must have array size or array initializer // var obj1 = stackalloc int[]; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 34) ); } [Fact] public void NestedInit() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[1] { { 42 } }; var obj2 = stackalloc int[ ] { { 42 } }; var obj3 = stackalloc [ ] { { 42 } }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj1 = stackalloc int[1] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(6, 40), // (7,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj2 = stackalloc int[ ] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(7, 40), // (8,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj3 = stackalloc [ ] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(8, 40) ); } [Fact] public void AsStatement() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { stackalloc[] {1}; stackalloc int[] {1}; stackalloc int[1] {1}; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc[] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc[] {1}").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc int[] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[] {1}").WithLocation(7, 9), // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc int[1] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[1] {1}").WithLocation(8, 9) ); } [Fact] public void BadRank() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[][] { 1 }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]') // var obj1 = stackalloc int[][] { 1 }; Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(6, 31), // (6,31): error CS1575: A stackalloc expression requires [] after type // var obj1 = stackalloc int[][] { 1 }; Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][]").WithLocation(6, 31) ); } [Fact] public void BadDimension() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[,] { 1 }; var obj2 = stackalloc [,] { 1 }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,35): error CS8381: "Invalid rank specifier: expected ']' // var obj2 = stackalloc [,] { 1 }; Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(7, 35), // (6,31): error CS1575: A stackalloc expression requires [] after type // var obj1 = stackalloc int[,] { 1 }; Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[,]").WithLocation(6, 31) ); } [Fact] public void TestFlowPass1() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { int i, j, k; var obj1 = stackalloc int [1] { i = 1 }; var obj2 = stackalloc int [ ] { j = 2 }; var obj3 = stackalloc [ ] { k = 3 }; Console.Write(i); Console.Write(j); Console.Write(k); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestFlowPass2() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public static void Main() { int i, j, k; var obj1 = stackalloc int [1] { i }; var obj2 = stackalloc int [ ] { j }; var obj3 = stackalloc [ ] { k }; } }", TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,41): error CS0165: Use of unassigned local variable 'i' // var obj1 = stackalloc int [1] { i }; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(7, 41), // (8,41): error CS0165: Use of unassigned local variable 'j' // var obj2 = stackalloc int [ ] { j }; Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(8, 41), // (9,41): error CS0165: Use of unassigned local variable 'k' // var obj3 = stackalloc [ ] { k }; Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k").WithLocation(9, 41) ); } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Implicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { Test obj1 = stackalloc int[3] { 1, 2, 3 }; var obj2 = stackalloc int[3] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[3] { 1, 2, 3 }; int* obj4 = stackalloc int[3] { 1, 2, 3 }; double* obj5 = stackalloc int[3] { 1, 2, 3 }; } public void Method2() { Test obj1 = stackalloc int[] { 1, 2, 3 }; var obj2 = stackalloc int[] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[] { 1, 2, 3 }; int* obj4 = stackalloc int[] { 1, 2, 3 }; double* obj5 = stackalloc int[] { 1, 2, 3 }; } public void Method3() { Test obj1 = stackalloc[] { 1, 2, 3 }; var obj2 = stackalloc[] { 1, 2, 3 }; Span<int> obj3 = stackalloc[] { 1, 2, 3 }; int* obj4 = stackalloc[] { 1, 2, 3 }; double* obj5 = stackalloc[] { 1, 2, 3 }; } public static implicit operator Test(int* value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24), // (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24), // (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(15, variables.Count()); for (int i = 0; i < 15; i += 5) { var obj1 = variables.ElementAt(i); Assert.Equal("obj1", obj1.Identifier.Text); var obj1Value = model.GetSemanticInfoSummary(obj1.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj1Value.Type).PointedAtType.SpecialType); Assert.Equal("Test", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.ImplicitUserDefined, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(i + 1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(i + 2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(i + 3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(i + 4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Explicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { Test obj1 = (Test)stackalloc int[3] { 1, 2, 3 }; var obj2 = stackalloc int[3] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[3] { 1, 2, 3 }; int* obj4 = stackalloc int[3] { 1, 2, 3 }; double* obj5 = stackalloc int[3] { 1, 2, 3 }; } public void Method2() { Test obj1 = (Test)stackalloc int[] { 1, 2, 3 }; var obj2 = stackalloc int[] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[] { 1, 2, 3 }; int* obj4 = stackalloc int[] { 1, 2, 3 }; double* obj5 = stackalloc int[] { 1, 2, 3 }; } public void Method3() { Test obj1 = (Test)stackalloc [] { 1, 2, 3 }; var obj2 = stackalloc[] { 1, 2, 3 }; Span<int> obj3 = stackalloc [] { 1, 2, 3 }; int* obj4 = stackalloc[] { 1, 2, 3 }; double* obj5 = stackalloc[] { 1, 2, 3 }; } public static explicit operator Test(Span<int> value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24), // (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24), // (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(15, variables.Count()); for (int i = 0; i < 15; i += 5) { var obj1 = variables.ElementAt(i); Assert.Equal("obj1", obj1.Identifier.Text); Assert.Equal(SyntaxKind.CastExpression, obj1.Initializer.Value.Kind()); var obj1Value = model.GetSemanticInfoSummary(((CastExpressionSyntax)obj1.Initializer.Value).Expression); Assert.Equal("Span", obj1Value.Type.Name); Assert.Equal("Span", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(i + 1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(i + 2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(i + 3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(i + 4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } } [Fact] public void ConversionError() { CreateCompilationWithMscorlibAndSpan(@" class Test { void Method1() { double x = stackalloc int[3] { 1, 2, 3 }; // implicit short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit } void Method2() { double x = stackalloc int[] { 1, 2, 3 }; // implicit short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit } void Method3() { double x = stackalloc[] { 1, 2, 3 }; // implicit short y = (short)stackalloc[] { 1, 2, 3 }; // explicit } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[3] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(6, 20), // (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(7, 19), // (12,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(12, 20), // (13,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(13, 19), // (18,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc[] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(18, 20), // (19,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc[] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(19, 19) ); } [Fact] public void MissingSpanType() { CreateCompilation(@" class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; } }").VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(6, 9), // (6,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(6, 24), // (7,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(7, 9), // (7,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(7, 24), // (8,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(8, 9), // (8,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(8, 24) ); } [Fact] public void MissingSpanConstructor() { CreateCompilation(@" namespace System { ref struct Span<T> { } class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; } } }").VerifyEmitDiagnostics( // (11,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(11, 28), // (12,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(12, 28), // (13,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(13, 28) ); } [Fact] public void ConditionalExpressionOnSpan_BothStackallocSpans() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3 } : stackalloc int [3] { 1, 2, 3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : stackalloc int [ ] { 1, 2, 3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : stackalloc [ ] { 1, 2, 3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_Convertible() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3 } : (Span<int>)stackalloc int [3] { 1, 2, 3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : (Span<int>)stackalloc int [ ] { 1, 2, 3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : (Span<int>)stackalloc [ ] { 1, 2, 3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_NoCast() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(7, 59), // (8,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(8, 59), // (9,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(9, 59) ); } [Fact] public void ConditionalExpressionOnSpan_CompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a1; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a2; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a3; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_IncompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<short> a = stackalloc short [10]; var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [3] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(8, 18), // (9,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(9, 18), // (10,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(10, 18) ); } [Fact] public void ConditionalExpressionOnSpan_Nested() { CreateCompilationWithMscorlibAndSpan(@" class Test { bool N() => true; void M() { var x = N() ? N() ? stackalloc int[1] { 42 } : stackalloc int[ ] { 42 } : N() ? stackalloc[] { 42 } : N() ? stackalloc int[2] : stackalloc int[3]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void BooleanOperatorOnSpan_NoTargetTyping() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { } if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { } if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { } } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(6, 13), // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(7, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(8, 13) ); } [Fact] public void StackAllocInitializerSyntaxProducesErrorsOnEarlierVersions() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> x1 = stackalloc int [3] { 1, 2, 3 }; Span<int> x2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> x3 = stackalloc [ ] { 1, 2, 3 }; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(7, 24), // (8,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(8, 24), // (9,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(9, 24) ); } [Fact] public void StackAllocSyntaxProducesUnsafeErrorInSafeCode() { CreateCompilation(@" class Test { void M() { var x1 = stackalloc int [3] { 1, 2, 3 }; var x2 = stackalloc int [ ] { 1, 2, 3 }; var x3 = stackalloc [ ] { 1, 2, 3 }; } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 18), // (7,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 18), // (8,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 18) ); } [Fact] public void StackAllocInUsing1() { var test = @" public class Test { unsafe public static void Main() { using (var v1 = stackalloc int [3] { 1, 2, 3 }) using (var v2 = stackalloc int [ ] { 1, 2, 3 }) using (var v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v1 = stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 16), // (7,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v2 = stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 16), // (8,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v3 = stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 16) ); } [Fact] public void StackAllocInUsing2() { var test = @" public class Test { unsafe public static void Main() { using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 }) using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 }) using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [3] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(6, 40), // (7,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(7, 40), // (8,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(8, 40) ); } [Fact] public void StackAllocInFixed() { var test = @" public class Test { unsafe public static void Main() { fixed (int* v1 = stackalloc int [3] { 1, 2, 3 }) fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 }) fixed (int* v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 26), // (7,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 26), // (8,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 26) ); } [Fact] public void ConstStackAllocExpression() { var test = @" unsafe public class Test { void M() { const int* p1 = stackalloc int [3] { 1, 2, 3 }; const int* p2 = stackalloc int [ ] { 1, 2, 3 }; const int* p3 = stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilation(test, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0283: The type 'int*' cannot be declared const // const int* p1 = stackalloc int[1] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(6, 15), // (7,15): error CS0283: The type 'int*' cannot be declared const // const int* p2 = stackalloc int[] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS0283: The type 'int*' cannot be declared const // const int* p3 = stackalloc [] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(8, 15) ); } [Fact] public void RefStackAllocAssignment_ValueToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p1 = stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 23), // (7,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 28), // (8,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p2 = stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 23), // (8,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 28), // (9,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p3 = stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 23), // (9,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 28) ); } [Fact] public void RefStackAllocAssignment_RefToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 }; ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 }; ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 32), // (8,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 32), // (9,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 32) ); } [Fact] public void InvalidPositionForStackAllocSpan() { var test = @" using System; public class Test { void M() { N(stackalloc int [3] { 1, 2, 3 }); N(stackalloc int [ ] { 1, 2, 3 }); N(stackalloc [ ] { 1, 2, 3 }); } void N(Span<int> span) { } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 11), // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11), // (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void CannotDotIntoStackAllocExpression() { var test = @" public class Test { void M() { int length1 = (stackalloc int [3] { 1, 2, 3 }).Length; int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length; int length3 = (stackalloc [ ] { 1, 2, 3 }).Length; int length4 = stackalloc int [3] { 1, 2, 3 }.Length; int length5 = stackalloc int [ ] { 1, 2, 3 }.Length; int length6 = stackalloc [ ] { 1, 2, 3 }.Length; } } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length1 = (stackalloc int [3] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 24), // (7,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 24), // (8,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length3 = (stackalloc [ ] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 24), // (10,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length4 = stackalloc int [3] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 23), // (11,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length5 = stackalloc int [ ] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(11, 23), // (12,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length6 = stackalloc [ ] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(12, 23) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll).VerifyDiagnostics( ); } [Fact] public void OverloadResolution_Fail() { var test = @" using System; unsafe public class Test { static void Main() { Invoke(stackalloc int [3] { 1, 2, 3 }); Invoke(stackalloc int [ ] { 1, 2, 3 }); Invoke(stackalloc [ ] { 1, 2, 3 }); } static void Invoke(Span<short> shortSpan) => Console.WriteLine(""shortSpan""); static void Invoke(Span<bool> boolSpan) => Console.WriteLine(""boolSpan""); static void Invoke(int* intPointer) => Console.WriteLine(""intPointer""); static void Invoke(void* voidPointer) => Console.WriteLine(""voidPointer""); } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 16), // (8,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 16), // (9,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 16) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (7,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(7, 16), // (8,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(8, 16), // (9,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(9, 16) ); } [Fact] public void StackAllocWithDynamic() { CreateCompilation(@" class Program { static void Main() { dynamic d = 1; var d1 = stackalloc dynamic [3] { d }; var d2 = stackalloc dynamic [ ] { d }; var d3 = stackalloc [ ] { d }; } }").VerifyDiagnostics( // (7,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(7, 29), // (7,18): error CS0847: An array initializer of length '3' is expected // var d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(7, 18), // (8,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d2 = stackalloc dynamic [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 29), // (9,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(9, 18), // (9,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { d }").WithLocation(9, 18) ); } [Fact] public void StackAllocWithDynamicSpan() { CreateCompilationWithMscorlibAndSpan(@" using System; class Program { static void Main() { dynamic d = 1; Span<dynamic> d1 = stackalloc dynamic [3] { d }; Span<dynamic> d2 = stackalloc dynamic [ ] { d }; Span<dynamic> d3 = stackalloc [ ] { d }; } }").VerifyDiagnostics( // (8,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 39), // (8,28): error CS0847: An array initializer of length '3' is expected // Span<dynamic> d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(8, 28), // (9,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d2 = stackalloc dynamic [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(9, 39), // (10,28): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(10, 28) ); } [Fact] public void StackAllocAsArgument() { var source = @" class Program { static void N(object p) { } static void Main() { N(stackalloc int [3] { 1, 2, 3 }); N(stackalloc int [ ] { 1, 2, 3 }); N(stackalloc [ ] { 1, 2, 3 }); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11), // (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11), // (10,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 11) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(8, 11), // (9,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(9, 11), // (10,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(10, 11) ); } [Fact] public void StackAllocInParenthesis() { var source = @" class Program { static void Main() { var x1 = (stackalloc int [3] { 1, 2, 3 }); var x2 = (stackalloc int [ ] { 1, 2, 3 }); var x3 = (stackalloc [ ] { 1, 2, 3 }); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = (stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 19), // (7,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = (stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 19), // (8,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = (stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 19) ); CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void StackAllocInNullConditionalOperator() { var source = @" class Program { static void Main() { var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 18), // (6,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 52), // (7,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 18), // (7,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 52), // (8,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 18), // (8,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 52) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(8, 18) ); } [Fact] public void StackAllocInCastAndConditionalOperator() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public void Method() { Test value1 = true ? new Test() : (Test)stackalloc int [3] { 1, 2, 3 }; Test value2 = true ? new Test() : (Test)stackalloc int [ ] { 1, 2, 3 }; Test value3 = true ? new Test() : (Test)stackalloc [ ] { 1, 2, 3 }; } public static explicit operator Test(Span<int> value) { return new Test(); } }", TestOptions.ReleaseDll).VerifyDiagnostics(); } [Fact] public void ERR_StackallocInCatchFinally_Catch() { var text = @" unsafe class C { int x = M(() => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err11 = stackalloc int [3] { 1, 2, 3 }; int* err12 = stackalloc int [ ] { 1, 2, 3 }; int* err13 = stackalloc [ ] { 1, 2, 3 }; } }; } catch { int* err21 = stackalloc int [3] { 1, 2, 3 }; int* err22 = stackalloc int [ ] { 1, 2, 3 }; int* err23 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err31 = stackalloc int [3] { 1, 2, 3 }; int* err32 = stackalloc int [ ] { 1, 2, 3 }; int* err33 = stackalloc [ ] { 1, 2, 3 }; } }; } }); static int M(System.Action action) { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err41 = stackalloc int [3] { 1, 2, 3 }; int* err42 = stackalloc int [ ] { 1, 2, 3 }; int* err43 = stackalloc [ ] { 1, 2, 3 }; } }; } catch { int* err51 = stackalloc int [3] { 1, 2, 3 }; int* err52 = stackalloc int [ ] { 1, 2, 3 }; int* err53 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err61 = stackalloc int [3] { 1, 2, 3 }; int* err62 = stackalloc int [ ] { 1, 2, 3 }; int* err63 = stackalloc [ ] { 1, 2, 3 }; } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (23,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err11 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34), // (24,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err12 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34), // (25,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err13 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34), // (31,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err21 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26), // (32,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err22 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26), // (33,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err23 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26), // (45,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err31 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34), // (46,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err32 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34), // (47,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err33 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34), // (72,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err41 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34), // (73,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err42 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34), // (74,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err43 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34), // (80,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err51 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26), // (81,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err52 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26), // (82,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err53 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26), // (94,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err61 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34), // (95,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err62 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34), // (96,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err63 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34) ); } [Fact] public void ERR_StackallocInCatchFinally_Finally() { var text = @" unsafe class C { int x = M(() => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err11 = stackalloc int [3] { 1, 2, 3 }; int* err12 = stackalloc int [ ] { 1, 2, 3 }; int* err13 = stackalloc [ ] { 1, 2, 3 }; } }; } finally { int* err21 = stackalloc int [3] { 1, 2, 3 }; int* err22 = stackalloc int [ ] { 1, 2, 3 }; int* err23 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err31 = stackalloc int [3] { 1, 2, 3 }; int* err32 = stackalloc int [ ] { 1, 2, 3 }; int* err33 = stackalloc [ ] { 1, 2, 3 }; } }; } }); static int M(System.Action action) { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err41 = stackalloc int [3] { 1, 2, 3 }; int* err42 = stackalloc int [ ] { 1, 2, 3 }; int* err43 = stackalloc [ ] { 1, 2, 3 }; } }; } finally { int* err51 = stackalloc int [3] { 1, 2, 3 }; int* err52 = stackalloc int [ ] { 1, 2, 3 }; int* err53 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err61 = stackalloc int [3] { 1, 2, 3 }; int* err62 = stackalloc int [ ] { 1, 2, 3 }; int* err63 = stackalloc [ ] { 1, 2, 3 }; } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (23,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err11 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34), // (24,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err12 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34), // (25,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err13 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34), // (31,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err21 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26), // (32,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err22 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26), // (33,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err23 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26), // (45,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err31 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34), // (46,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err32 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34), // (47,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err33 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34), // (72,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err41 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34), // (73,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err42 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34), // (74,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err43 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34), // (80,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err51 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26), // (81,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err52 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26), // (82,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err53 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26), // (94,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err61 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34), // (95,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err62 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34), // (96,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err63 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34) ); } [Fact] public void StackAllocArrayCreationExpression_Symbols() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { var obj1 = stackalloc double[2] { 1, 1.2 }; Span<double> obj2 = stackalloc double[2] { 1, 1.2 }; _ = stackalloc double[2] { 1, 1.2 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method // _ = stackalloc double[2] { 1, 1.2 }; Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc double[2] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void ImplicitStackAllocArrayCreationExpression_Symbols() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { var obj1 = stackalloc[] { 1, 1.2 }; Span<double> obj2 = stackalloc[] { 1, 1.2 }; _ = stackalloc[] { 1, 1.2 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method // _ = stackalloc[] { 1, 1.2 }; Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc[] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void StackAllocArrayCreationExpression_Symbols_ErrorCase() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,41): error CS0150: A constant value is expected // short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_ConstantExpected, "*obj1").WithLocation(7, 41), // (8,46): error CS0150: A constant value is expected // Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_ConstantExpected, "obj2.Length").WithLocation(8, 46), // (7,42): error CS0165: Use of unassigned local variable 'obj1' // short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 42), // (8,46): error CS0165: Use of unassigned local variable 'obj2' // Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 46) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(2, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int16*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Int16", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int16", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Int16>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("ref System.Int16 System.Span<System.Int16>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", element1Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", sizeInfo.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void ImplicitStackAllocArrayCreationExpression_Symbols_ErrorCase() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { double* obj1 = stackalloc[] { obj1[0], *obj1 }; Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,39): error CS0165: Use of unassigned local variable 'obj1' // double* obj1 = stackalloc[] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 39), // (8,44): error CS0165: Use of unassigned local variable 'obj2' // Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 44) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(2, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("ref System.Double System.Span<System.Double>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Equal("System.Int32 System.Span<System.Double>.Length { get; }", element1Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } } }
// 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. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.StackAllocInitializer)] public class StackAllocInitializerTests : CompilingTestBase { [Fact, WorkItem(33945, "https://github.com/dotnet/roslyn/issues/33945")] public void RestrictedTypesAllowedInStackalloc() { var comp = CreateCompilationWithMscorlibAndSpan(@" public ref struct RefS { } public ref struct RefG<T> { public T field; } class C { unsafe void M() { var x1 = stackalloc RefS[10]; var x2 = stackalloc RefG<string>[10]; var x3 = stackalloc RefG<int>[10]; var x4 = stackalloc System.TypedReference[10]; // Note: this should be disallowed by adding a dummy field to the ref assembly for TypedReference var x5 = stackalloc System.ArgIterator[10]; var x6 = stackalloc System.RuntimeArgumentHandle[10]; var y1 = new RefS[10]; var y2 = new RefG<string>[10]; var y3 = new RefG<int>[10]; var y4 = new System.TypedReference[10]; var y5 = new System.ArgIterator[10]; var y6 = new System.RuntimeArgumentHandle[10]; RefS[] z1 = null; RefG<string>[] z2 = null; RefG<int>[] z3 = null; System.TypedReference[] z4 = null; System.ArgIterator[] z5 = null; System.RuntimeArgumentHandle[] z6 = null; _ = z1; _ = z2; _ = z3; _ = z4; _ = z5; _ = z6; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (10,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('RefG<string>') // var x2 = stackalloc RefG<string>[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "RefG<string>").WithArguments("RefG<string>").WithLocation(10, 29), // (16,22): error CS0611: Array elements cannot be of type 'RefS' // var y1 = new RefS[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(16, 22), // (17,22): error CS0611: Array elements cannot be of type 'RefG<string>' // var y2 = new RefG<string>[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(17, 22), // (18,22): error CS0611: Array elements cannot be of type 'RefG<int>' // var y3 = new RefG<int>[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(18, 22), // (19,22): error CS0611: Array elements cannot be of type 'TypedReference' // var y4 = new System.TypedReference[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(19, 22), // (20,22): error CS0611: Array elements cannot be of type 'ArgIterator' // var y5 = new System.ArgIterator[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(20, 22), // (21,22): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle' // var y6 = new System.RuntimeArgumentHandle[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(21, 22), // (23,9): error CS0611: Array elements cannot be of type 'RefS' // RefS[] z1 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(23, 9), // (24,9): error CS0611: Array elements cannot be of type 'RefG<string>' // RefG<string>[] z2 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(24, 9), // (25,9): error CS0611: Array elements cannot be of type 'RefG<int>' // RefG<int>[] z3 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(25, 9), // (26,9): error CS0611: Array elements cannot be of type 'TypedReference' // System.TypedReference[] z4 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(26, 9), // (27,9): error CS0611: Array elements cannot be of type 'ArgIterator' // System.ArgIterator[] z5 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(27, 9), // (28,9): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle' // System.RuntimeArgumentHandle[] z6 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(28, 9) ); } [Fact] public void NoBestType_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { struct A {} struct B {} void Method(dynamic d, RefStruct r) { var p0 = stackalloc[] { new A(), new B() }; var p1 = stackalloc[] { }; var p2 = stackalloc[] { VoidMethod() }; var p3 = stackalloc[] { null }; var p4 = stackalloc[] { (1, null) }; var p5 = stackalloc[] { () => { } }; var p6 = stackalloc[] { new {} , new { i = 0 } }; var p7 = stackalloc[] { d }; var p8 = stackalloc[] { _ }; } public void VoidMethod() {} } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 a, T2 b) => throw null; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,28): error CS0246: The type or namespace name 'RefStruct' could not be found (are you missing a using directive or an assembly reference?) // void Method(dynamic d, RefStruct r) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "RefStruct").WithArguments("RefStruct").WithLocation(7, 28), // (9,18): error CS0826: No best type found for implicitly-typed array // var p0 = stackalloc[] { new A(), new B() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var p1 = stackalloc[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var p2 = stackalloc[] { VoidMethod() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var p3 = stackalloc[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var p4 = stackalloc[] { (1, null) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 18), // (14,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Action') // var p5 = stackalloc[] { () => { } }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { () => { } }").WithArguments("System.Action").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var p6 = stackalloc[] { new {} , new { i = 0 } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 18), // (16,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var p7 = stackalloc[] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 18), // (17,33): error CS0103: The name '_' does not exist in the current context // var p8 = stackalloc[] { _ }; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 33) ); } [Fact] public void NoBestType_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { struct A {} struct B {} void Method(dynamic d, bool c) { var p0 = c ? default : stackalloc[] { new A(), new B() }; var p1 = c ? default : stackalloc[] { }; var p2 = c ? default : stackalloc[] { VoidMethod() }; var p3 = c ? default : stackalloc[] { null }; var p4 = c ? default : stackalloc[] { (1, null) }; var p5 = c ? default : stackalloc[] { () => { } }; var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } }; var p7 = c ? default : stackalloc[] { d }; var p8 = c ? default : stackalloc[] { _ }; } public void VoidMethod() {} } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 a, T2 b) => throw null; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (9,32): error CS0826: No best type found for implicitly-typed array // var p0 = c ? default : stackalloc[] { new A(), new B() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 32), // (10,32): error CS0826: No best type found for implicitly-typed array // var p1 = c ? default : stackalloc[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 32), // (11,32): error CS0826: No best type found for implicitly-typed array // var p2 = c ? default : stackalloc[] { VoidMethod() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 32), // (12,32): error CS0826: No best type found for implicitly-typed array // var p3 = c ? default : stackalloc[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 32), // (13,32): error CS0826: No best type found for implicitly-typed array // var p4 = c ? default : stackalloc[] { (1, null) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 32), // (14,32): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Action') // var p5 = c ? default : stackalloc[] { () => { } }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { () => { } }").WithArguments("System.Action").WithLocation(14, 32), // (15,32): error CS0826: No best type found for implicitly-typed array // var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 32), // (16,32): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var p7 = c ? default : stackalloc[] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 32), // (17,47): error CS0103: The name '_' does not exist in the current context // var p8 = c ? default : stackalloc[] { _ }; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 47) ); } [Fact] public void InitializeWithSelf_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void Method1() { var obj1 = stackalloc int[1] { obj1 }; var obj2 = stackalloc int[ ] { obj2 }; var obj3 = stackalloc [ ] { obj3 }; } void Method2() { var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,40): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[1] { obj1 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 40), // (7,40): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 40), // (8,40): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 40), // (13,40): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 40), // (13,50): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 50), // (14,40): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 40), // (14,50): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 50), // (15,40): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 40), // (15,50): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 50) ); } [Fact] public void InitializeWithSelf_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void Method1(bool c) { var obj1 = c ? default : stackalloc int[1] { obj1 }; var obj2 = c ? default : stackalloc int[ ] { obj2 }; var obj3 = c ? default : stackalloc [ ] { obj3 }; } void Method2(bool c) { var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,54): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[1] { obj1 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 54), // (7,54): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 54), // (8,54): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 54), // (13,54): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 54), // (13,64): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 64), // (14,54): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 54), // (14,64): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 64), // (15,54): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 54), // (15,64): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 64) ); } [Fact] public void BadBestType_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { ref struct S {} void Method1(S s) { var obj1 = stackalloc[] { """" }; var obj2 = stackalloc[] { new {} }; var obj3 = stackalloc[] { s }; // OK } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // var obj1 = stackalloc[] { "" }; Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 20), // (8,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>') // var obj2 = stackalloc[] { new {} }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 20) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.String*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.String*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.String", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("<empty anonymous type>*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("Test.S*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("Test.S*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); } [Fact] public void BadBestType_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { ref struct S {} void Method1(S s, bool c) { var obj1 = c ? default : stackalloc[] { """" }; var obj2 = c ? default : stackalloc[] { new {} }; var obj3 = c ? default : stackalloc[] { s }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // var obj1 = c ? default : stackalloc[] { "" }; Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 34), // (8,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>') // var obj2 = c ? default : stackalloc[] { new {} }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 34), // (9,34): error CS0306: The type 'Test.S' may not be used as a type argument // var obj3 = c ? default : stackalloc[] { s }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "stackalloc[] { s }").WithArguments("Test.S").WithLocation(9, 34) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.String>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.String>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.String", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<Test.S>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<Test.S>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); } [Fact] public void TestFor_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { static void Method1() { int i = 0; for (var p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method2() { int i = 0; for (var p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method3() { int i = 0; for (var p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } public static void Main() { Method1(); Method2(); Method3(); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "123123123", verify: Verification.Fails); } [Fact] public void TestFor_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { static void Method1() { int i = 0; for (Span<int> p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method2() { int i = 0; for (Span<int> p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method3() { int i = 0; for (Span<int> p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } public static void Main() { Method1(); Method2(); Method3(); } }", TestOptions.DebugExe); comp.VerifyDiagnostics(); } [Fact] public void TestForTernary() { var comp = CreateCompilationWithMscorlibAndSpan(@" class Test { static void Method1(bool b) { for (var p = b ? stackalloc int[3] { 1, 2, 3 } : default; false;) {} for (var p = b ? stackalloc int[ ] { 1, 2, 3 } : default; false;) {} for (var p = b ? stackalloc [ ] { 1, 2, 3 } : default; false;) {} } }", TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [Fact] public void TestLock() { var source = @" class Test { static void Method1() { lock (stackalloc int[3] { 1, 2, 3 }) {} lock (stackalloc int[ ] { 1, 2, 3 }) {} lock (stackalloc [ ] { 1, 2, 3 }) {} } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (6,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 15), // (6,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int*").WithLocation(6, 15), // (7,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 15), // (7,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 15), // (8,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(8, 15) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (6,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 15), // (7,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 15), // (8,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 15) ); } [Fact] public void TestSelect() { var source = @" using System.Linq; class Test { static void Method1(int[] array) { var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (7,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 44), // (8,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 44), // (9,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 44) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (7,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 37), // (8,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 37), // (9,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(9, 37) ); } [Fact] public void TestLet() { var source = @" using System.Linq; class Test { static void Method1(int[] array) { var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (7,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 45), // (8,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 45), // (9,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 45) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (7,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(7, 75), // (8,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(8, 75), // (9,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(9, 75) ); } [Fact] public void TestAwait_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System.Threading.Tasks; unsafe class Test { async void M() { var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,32): error CS4004: Cannot await in an unsafe context // var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(1)").WithLocation(7, 32), // (7,60): error CS4004: Cannot await in an unsafe context // var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(2)").WithLocation(7, 60) ); } [Fact] public void TestAwait_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; using System.Threading.Tasks; class Test { async void M() { Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (8,38): error CS0150: A constant value is expected // Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_ConstantExpected, "await Task.FromResult(1)").WithLocation(8, 38), // (8,9): error CS4012: Parameters or locals of type 'Span<int>' cannot be declared in async methods or async lambda expressions. // Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "Span<int>").WithArguments("System.Span<int>").WithLocation(8, 9) ); } [Fact] public void TestSelfInSize() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void M() { var x = stackalloc int[x] { }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,32): error CS0841: Cannot use local variable 'x' before it is declared // var x = stackalloc int[x] { }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 32) ); } [Fact] public void WrongLength() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[10] { }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,20): error CS0847: An array initializer of length '10' is expected // var obj1 = stackalloc int[10] { }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc int[10] { }").WithArguments("10").WithLocation(6, 20) ); } [Fact] public void NoInit() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[]; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,34): error CS1586: Array creation must have array size or array initializer // var obj1 = stackalloc int[]; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 34) ); } [Fact] public void NestedInit() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[1] { { 42 } }; var obj2 = stackalloc int[ ] { { 42 } }; var obj3 = stackalloc [ ] { { 42 } }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj1 = stackalloc int[1] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(6, 40), // (7,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj2 = stackalloc int[ ] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(7, 40), // (8,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj3 = stackalloc [ ] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(8, 40) ); } [Fact] public void AsStatement() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { stackalloc[] {1}; stackalloc int[] {1}; stackalloc int[1] {1}; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc[] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc[] {1}").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc int[] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[] {1}").WithLocation(7, 9), // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc int[1] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[1] {1}").WithLocation(8, 9) ); } [Fact] public void BadRank() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[][] { 1 }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]') // var obj1 = stackalloc int[][] { 1 }; Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(6, 31), // (6,31): error CS1575: A stackalloc expression requires [] after type // var obj1 = stackalloc int[][] { 1 }; Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][]").WithLocation(6, 31) ); } [Fact] public void BadDimension() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[,] { 1 }; var obj2 = stackalloc [,] { 1 }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,35): error CS8381: "Invalid rank specifier: expected ']' // var obj2 = stackalloc [,] { 1 }; Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(7, 35), // (6,31): error CS1575: A stackalloc expression requires [] after type // var obj1 = stackalloc int[,] { 1 }; Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[,]").WithLocation(6, 31) ); } [Fact] public void TestFlowPass1() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { int i, j, k; var obj1 = stackalloc int [1] { i = 1 }; var obj2 = stackalloc int [ ] { j = 2 }; var obj3 = stackalloc [ ] { k = 3 }; Console.Write(i); Console.Write(j); Console.Write(k); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestFlowPass2() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public static void Main() { int i, j, k; var obj1 = stackalloc int [1] { i }; var obj2 = stackalloc int [ ] { j }; var obj3 = stackalloc [ ] { k }; } }", TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,41): error CS0165: Use of unassigned local variable 'i' // var obj1 = stackalloc int [1] { i }; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(7, 41), // (8,41): error CS0165: Use of unassigned local variable 'j' // var obj2 = stackalloc int [ ] { j }; Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(8, 41), // (9,41): error CS0165: Use of unassigned local variable 'k' // var obj3 = stackalloc [ ] { k }; Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k").WithLocation(9, 41) ); } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Implicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { Test obj1 = stackalloc int[3] { 1, 2, 3 }; var obj2 = stackalloc int[3] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[3] { 1, 2, 3 }; int* obj4 = stackalloc int[3] { 1, 2, 3 }; double* obj5 = stackalloc int[3] { 1, 2, 3 }; } public void Method2() { Test obj1 = stackalloc int[] { 1, 2, 3 }; var obj2 = stackalloc int[] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[] { 1, 2, 3 }; int* obj4 = stackalloc int[] { 1, 2, 3 }; double* obj5 = stackalloc int[] { 1, 2, 3 }; } public void Method3() { Test obj1 = stackalloc[] { 1, 2, 3 }; var obj2 = stackalloc[] { 1, 2, 3 }; Span<int> obj3 = stackalloc[] { 1, 2, 3 }; int* obj4 = stackalloc[] { 1, 2, 3 }; double* obj5 = stackalloc[] { 1, 2, 3 }; } public static implicit operator Test(int* value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24), // (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24), // (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(15, variables.Count()); for (int i = 0; i < 15; i += 5) { var obj1 = variables.ElementAt(i); Assert.Equal("obj1", obj1.Identifier.Text); var obj1Value = model.GetSemanticInfoSummary(obj1.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj1Value.Type).PointedAtType.SpecialType); Assert.Equal("Test", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.ImplicitUserDefined, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(i + 1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(i + 2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(i + 3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(i + 4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Explicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { Test obj1 = (Test)stackalloc int[3] { 1, 2, 3 }; var obj2 = stackalloc int[3] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[3] { 1, 2, 3 }; int* obj4 = stackalloc int[3] { 1, 2, 3 }; double* obj5 = stackalloc int[3] { 1, 2, 3 }; } public void Method2() { Test obj1 = (Test)stackalloc int[] { 1, 2, 3 }; var obj2 = stackalloc int[] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[] { 1, 2, 3 }; int* obj4 = stackalloc int[] { 1, 2, 3 }; double* obj5 = stackalloc int[] { 1, 2, 3 }; } public void Method3() { Test obj1 = (Test)stackalloc [] { 1, 2, 3 }; var obj2 = stackalloc[] { 1, 2, 3 }; Span<int> obj3 = stackalloc [] { 1, 2, 3 }; int* obj4 = stackalloc[] { 1, 2, 3 }; double* obj5 = stackalloc[] { 1, 2, 3 }; } public static explicit operator Test(Span<int> value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24), // (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24), // (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(15, variables.Count()); for (int i = 0; i < 15; i += 5) { var obj1 = variables.ElementAt(i); Assert.Equal("obj1", obj1.Identifier.Text); Assert.Equal(SyntaxKind.CastExpression, obj1.Initializer.Value.Kind()); var obj1Value = model.GetSemanticInfoSummary(((CastExpressionSyntax)obj1.Initializer.Value).Expression); Assert.Equal("Span", obj1Value.Type.Name); Assert.Equal("Span", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(i + 1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(i + 2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(i + 3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(i + 4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } } [Fact] public void ConversionError() { CreateCompilationWithMscorlibAndSpan(@" class Test { void Method1() { double x = stackalloc int[3] { 1, 2, 3 }; // implicit short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit } void Method2() { double x = stackalloc int[] { 1, 2, 3 }; // implicit short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit } void Method3() { double x = stackalloc[] { 1, 2, 3 }; // implicit short y = (short)stackalloc[] { 1, 2, 3 }; // explicit } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[3] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(6, 20), // (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(7, 19), // (12,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(12, 20), // (13,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(13, 19), // (18,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc[] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(18, 20), // (19,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc[] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(19, 19) ); } [Fact] public void MissingSpanType() { CreateCompilation(@" class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; } }").VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(6, 9), // (6,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(6, 24), // (7,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(7, 9), // (7,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(7, 24), // (8,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(8, 9), // (8,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(8, 24) ); } [Fact] public void MissingSpanConstructor() { CreateCompilation(@" namespace System { ref struct Span<T> { } class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; } } }").VerifyEmitDiagnostics( // (11,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(11, 28), // (12,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(12, 28), // (13,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(13, 28) ); } [Fact] public void ConditionalExpressionOnSpan_BothStackallocSpans() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3 } : stackalloc int [3] { 1, 2, 3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : stackalloc int [ ] { 1, 2, 3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : stackalloc [ ] { 1, 2, 3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_Convertible() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3 } : (Span<int>)stackalloc int [3] { 1, 2, 3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : (Span<int>)stackalloc int [ ] { 1, 2, 3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : (Span<int>)stackalloc [ ] { 1, 2, 3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_NoCast() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(7, 59), // (8,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(8, 59), // (9,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(9, 59) ); } [Fact] public void ConditionalExpressionOnSpan_CompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a1; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a2; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a3; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_IncompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<short> a = stackalloc short [10]; var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [3] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(8, 18), // (9,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(9, 18), // (10,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(10, 18) ); } [Fact] public void ConditionalExpressionOnSpan_Nested() { CreateCompilationWithMscorlibAndSpan(@" class Test { bool N() => true; void M() { var x = N() ? N() ? stackalloc int[1] { 42 } : stackalloc int[ ] { 42 } : N() ? stackalloc[] { 42 } : N() ? stackalloc int[2] : stackalloc int[3]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void BooleanOperatorOnSpan_NoTargetTyping() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { } if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { } if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { } } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(6, 13), // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(7, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(8, 13) ); } [Fact] public void StackAllocInitializerSyntaxProducesErrorsOnEarlierVersions() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> x1 = stackalloc int [3] { 1, 2, 3 }; Span<int> x2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> x3 = stackalloc [ ] { 1, 2, 3 }; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(7, 24), // (8,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(8, 24), // (9,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(9, 24) ); } [Fact] public void StackAllocSyntaxProducesUnsafeErrorInSafeCode() { CreateCompilation(@" class Test { void M() { var x1 = stackalloc int [3] { 1, 2, 3 }; var x2 = stackalloc int [ ] { 1, 2, 3 }; var x3 = stackalloc [ ] { 1, 2, 3 }; } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 18), // (7,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 18), // (8,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 18) ); } [Fact] public void StackAllocInUsing1() { var test = @" public class Test { unsafe public static void Main() { using (var v1 = stackalloc int [3] { 1, 2, 3 }) using (var v2 = stackalloc int [ ] { 1, 2, 3 }) using (var v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v1 = stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 16), // (7,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v2 = stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 16), // (8,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v3 = stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 16) ); } [Fact] public void StackAllocInUsing2() { var test = @" public class Test { unsafe public static void Main() { using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 }) using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 }) using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [3] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(6, 40), // (7,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(7, 40), // (8,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(8, 40) ); } [Fact] public void StackAllocInFixed() { var test = @" public class Test { unsafe public static void Main() { fixed (int* v1 = stackalloc int [3] { 1, 2, 3 }) fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 }) fixed (int* v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 26), // (7,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 26), // (8,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 26) ); } [Fact] public void ConstStackAllocExpression() { var test = @" unsafe public class Test { void M() { const int* p1 = stackalloc int [3] { 1, 2, 3 }; const int* p2 = stackalloc int [ ] { 1, 2, 3 }; const int* p3 = stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilation(test, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0283: The type 'int*' cannot be declared const // const int* p1 = stackalloc int[1] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(6, 15), // (7,15): error CS0283: The type 'int*' cannot be declared const // const int* p2 = stackalloc int[] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS0283: The type 'int*' cannot be declared const // const int* p3 = stackalloc [] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(8, 15) ); } [Fact] public void RefStackAllocAssignment_ValueToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p1 = stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 23), // (7,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 28), // (8,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p2 = stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 23), // (8,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 28), // (9,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p3 = stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 23), // (9,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 28) ); } [Fact] public void RefStackAllocAssignment_RefToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 }; ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 }; ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 32), // (8,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 32), // (9,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 32) ); } [Fact] public void InvalidPositionForStackAllocSpan() { var test = @" using System; public class Test { void M() { N(stackalloc int [3] { 1, 2, 3 }); N(stackalloc int [ ] { 1, 2, 3 }); N(stackalloc [ ] { 1, 2, 3 }); } void N(Span<int> span) { } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 11), // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11), // (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void CannotDotIntoStackAllocExpression() { var test = @" public class Test { void M() { int length1 = (stackalloc int [3] { 1, 2, 3 }).Length; int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length; int length3 = (stackalloc [ ] { 1, 2, 3 }).Length; int length4 = stackalloc int [3] { 1, 2, 3 }.Length; int length5 = stackalloc int [ ] { 1, 2, 3 }.Length; int length6 = stackalloc [ ] { 1, 2, 3 }.Length; } } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length1 = (stackalloc int [3] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 24), // (7,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 24), // (8,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length3 = (stackalloc [ ] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 24), // (10,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length4 = stackalloc int [3] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 23), // (11,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length5 = stackalloc int [ ] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(11, 23), // (12,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length6 = stackalloc [ ] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(12, 23) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll).VerifyDiagnostics( ); } [Fact] public void OverloadResolution_Fail() { var test = @" using System; unsafe public class Test { static void Main() { Invoke(stackalloc int [3] { 1, 2, 3 }); Invoke(stackalloc int [ ] { 1, 2, 3 }); Invoke(stackalloc [ ] { 1, 2, 3 }); } static void Invoke(Span<short> shortSpan) => Console.WriteLine(""shortSpan""); static void Invoke(Span<bool> boolSpan) => Console.WriteLine(""boolSpan""); static void Invoke(int* intPointer) => Console.WriteLine(""intPointer""); static void Invoke(void* voidPointer) => Console.WriteLine(""voidPointer""); } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 16), // (8,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 16), // (9,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 16) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (7,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(7, 16), // (8,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(8, 16), // (9,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(9, 16) ); } [Fact] public void StackAllocWithDynamic() { CreateCompilation(@" class Program { static void Main() { dynamic d = 1; var d1 = stackalloc dynamic [3] { d }; var d2 = stackalloc dynamic [ ] { d }; var d3 = stackalloc [ ] { d }; } }").VerifyDiagnostics( // (7,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(7, 29), // (7,18): error CS0847: An array initializer of length '3' is expected // var d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(7, 18), // (8,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d2 = stackalloc dynamic [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 29), // (9,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(9, 18), // (9,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { d }").WithLocation(9, 18) ); } [Fact] public void StackAllocWithDynamicSpan() { CreateCompilationWithMscorlibAndSpan(@" using System; class Program { static void Main() { dynamic d = 1; Span<dynamic> d1 = stackalloc dynamic [3] { d }; Span<dynamic> d2 = stackalloc dynamic [ ] { d }; Span<dynamic> d3 = stackalloc [ ] { d }; } }").VerifyDiagnostics( // (8,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 39), // (8,28): error CS0847: An array initializer of length '3' is expected // Span<dynamic> d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(8, 28), // (9,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d2 = stackalloc dynamic [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(9, 39), // (10,28): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(10, 28) ); } [Fact] public void StackAllocAsArgument() { var source = @" class Program { static void N(object p) { } static void Main() { N(stackalloc int [3] { 1, 2, 3 }); N(stackalloc int [ ] { 1, 2, 3 }); N(stackalloc [ ] { 1, 2, 3 }); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11), // (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11), // (10,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 11) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(8, 11), // (9,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(9, 11), // (10,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(10, 11) ); } [Fact] public void StackAllocInParenthesis() { var source = @" class Program { static void Main() { var x1 = (stackalloc int [3] { 1, 2, 3 }); var x2 = (stackalloc int [ ] { 1, 2, 3 }); var x3 = (stackalloc [ ] { 1, 2, 3 }); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = (stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 19), // (7,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = (stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 19), // (8,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = (stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 19) ); CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void StackAllocInNullConditionalOperator() { var source = @" class Program { static void Main() { var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 18), // (6,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 52), // (7,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 18), // (7,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 52), // (8,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 18), // (8,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 52) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(8, 18) ); } [Fact] public void StackAllocInCastAndConditionalOperator() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public void Method() { Test value1 = true ? new Test() : (Test)stackalloc int [3] { 1, 2, 3 }; Test value2 = true ? new Test() : (Test)stackalloc int [ ] { 1, 2, 3 }; Test value3 = true ? new Test() : (Test)stackalloc [ ] { 1, 2, 3 }; } public static explicit operator Test(Span<int> value) { return new Test(); } }", TestOptions.ReleaseDll).VerifyDiagnostics(); } [Fact] public void ERR_StackallocInCatchFinally_Catch() { var text = @" unsafe class C { int x = M(() => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err11 = stackalloc int [3] { 1, 2, 3 }; int* err12 = stackalloc int [ ] { 1, 2, 3 }; int* err13 = stackalloc [ ] { 1, 2, 3 }; } }; } catch { int* err21 = stackalloc int [3] { 1, 2, 3 }; int* err22 = stackalloc int [ ] { 1, 2, 3 }; int* err23 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err31 = stackalloc int [3] { 1, 2, 3 }; int* err32 = stackalloc int [ ] { 1, 2, 3 }; int* err33 = stackalloc [ ] { 1, 2, 3 }; } }; } }); static int M(System.Action action) { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err41 = stackalloc int [3] { 1, 2, 3 }; int* err42 = stackalloc int [ ] { 1, 2, 3 }; int* err43 = stackalloc [ ] { 1, 2, 3 }; } }; } catch { int* err51 = stackalloc int [3] { 1, 2, 3 }; int* err52 = stackalloc int [ ] { 1, 2, 3 }; int* err53 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err61 = stackalloc int [3] { 1, 2, 3 }; int* err62 = stackalloc int [ ] { 1, 2, 3 }; int* err63 = stackalloc [ ] { 1, 2, 3 }; } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (23,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err11 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34), // (24,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err12 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34), // (25,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err13 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34), // (31,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err21 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26), // (32,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err22 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26), // (33,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err23 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26), // (45,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err31 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34), // (46,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err32 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34), // (47,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err33 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34), // (72,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err41 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34), // (73,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err42 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34), // (74,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err43 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34), // (80,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err51 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26), // (81,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err52 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26), // (82,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err53 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26), // (94,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err61 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34), // (95,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err62 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34), // (96,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err63 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34) ); } [Fact] public void ERR_StackallocInCatchFinally_Finally() { var text = @" unsafe class C { int x = M(() => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err11 = stackalloc int [3] { 1, 2, 3 }; int* err12 = stackalloc int [ ] { 1, 2, 3 }; int* err13 = stackalloc [ ] { 1, 2, 3 }; } }; } finally { int* err21 = stackalloc int [3] { 1, 2, 3 }; int* err22 = stackalloc int [ ] { 1, 2, 3 }; int* err23 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err31 = stackalloc int [3] { 1, 2, 3 }; int* err32 = stackalloc int [ ] { 1, 2, 3 }; int* err33 = stackalloc [ ] { 1, 2, 3 }; } }; } }); static int M(System.Action action) { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err41 = stackalloc int [3] { 1, 2, 3 }; int* err42 = stackalloc int [ ] { 1, 2, 3 }; int* err43 = stackalloc [ ] { 1, 2, 3 }; } }; } finally { int* err51 = stackalloc int [3] { 1, 2, 3 }; int* err52 = stackalloc int [ ] { 1, 2, 3 }; int* err53 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err61 = stackalloc int [3] { 1, 2, 3 }; int* err62 = stackalloc int [ ] { 1, 2, 3 }; int* err63 = stackalloc [ ] { 1, 2, 3 }; } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (23,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err11 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34), // (24,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err12 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34), // (25,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err13 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34), // (31,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err21 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26), // (32,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err22 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26), // (33,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err23 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26), // (45,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err31 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34), // (46,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err32 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34), // (47,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err33 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34), // (72,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err41 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34), // (73,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err42 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34), // (74,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err43 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34), // (80,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err51 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26), // (81,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err52 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26), // (82,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err53 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26), // (94,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err61 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34), // (95,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err62 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34), // (96,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err63 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34) ); } [Fact] public void StackAllocArrayCreationExpression_Symbols() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { var obj1 = stackalloc double[2] { 1, 1.2 }; Span<double> obj2 = stackalloc double[2] { 1, 1.2 }; _ = stackalloc double[2] { 1, 1.2 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method // _ = stackalloc double[2] { 1, 1.2 }; Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc double[2] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void ImplicitStackAllocArrayCreationExpression_Symbols() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { var obj1 = stackalloc[] { 1, 1.2 }; Span<double> obj2 = stackalloc[] { 1, 1.2 }; _ = stackalloc[] { 1, 1.2 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method // _ = stackalloc[] { 1, 1.2 }; Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc[] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void StackAllocArrayCreationExpression_Symbols_ErrorCase() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,41): error CS0150: A constant value is expected // short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_ConstantExpected, "*obj1").WithLocation(7, 41), // (8,46): error CS0150: A constant value is expected // Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_ConstantExpected, "obj2.Length").WithLocation(8, 46), // (7,42): error CS0165: Use of unassigned local variable 'obj1' // short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 42), // (8,46): error CS0165: Use of unassigned local variable 'obj2' // Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 46) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(2, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int16*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Int16", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int16", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Int16>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("ref System.Int16 System.Span<System.Int16>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", element1Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", sizeInfo.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void ImplicitStackAllocArrayCreationExpression_Symbols_ErrorCase() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { double* obj1 = stackalloc[] { obj1[0], *obj1 }; Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,39): error CS0165: Use of unassigned local variable 'obj1' // double* obj1 = stackalloc[] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 39), // (8,44): error CS0165: Use of unassigned local variable 'obj2' // Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 44) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(2, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("ref System.Double System.Span<System.Double>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Equal("System.Int32 System.Span<System.Double>.Length { get; }", element1Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/CSharp/Portable/SignatureHelp/GenericNamePartiallyWrittenSignatureHelpProvider.cs
// 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 System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("GenericNamePartiallyWrittenSignatureHelpProvider", LanguageNames.CSharp), Shared] internal class GenericNamePartiallyWrittenSignatureHelpProvider : GenericNameSignatureHelpProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GenericNamePartiallyWrittenSignatureHelpProvider() { } protected override bool TryGetGenericIdentifier(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out SyntaxToken genericIdentifier, out SyntaxToken lessThanToken) => root.SyntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out lessThanToken); protected override TextSpan GetTextSpan(SyntaxToken genericIdentifier, SyntaxToken lessThanToken) { var lastToken = genericIdentifier.FindLastTokenOfPartialGenericName(); var nextToken = lastToken.GetNextNonZeroWidthTokenOrEndOfFile(); Contract.ThrowIfTrue(nextToken.Kind() == 0); return TextSpan.FromBounds(genericIdentifier.SpanStart, nextToken.SpanStart); } } }
// 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 System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("GenericNamePartiallyWrittenSignatureHelpProvider", LanguageNames.CSharp), Shared] internal class GenericNamePartiallyWrittenSignatureHelpProvider : GenericNameSignatureHelpProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GenericNamePartiallyWrittenSignatureHelpProvider() { } protected override bool TryGetGenericIdentifier(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out SyntaxToken genericIdentifier, out SyntaxToken lessThanToken) => root.SyntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out lessThanToken); protected override TextSpan GetTextSpan(SyntaxToken genericIdentifier, SyntaxToken lessThanToken) { var lastToken = genericIdentifier.FindLastTokenOfPartialGenericName(); var nextToken = lastToken.GetNextNonZeroWidthTokenOrEndOfFile(); Contract.ThrowIfTrue(nextToken.Kind() == 0); return TextSpan.FromBounds(genericIdentifier.SpanStart, nextToken.SpanStart); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/VisualStudio/Core/Def/Implementation/AnalyzerDependency/AnalyzerDependencyConflict.cs
// 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. #nullable disable using Microsoft.CodeAnalysis; using System.Diagnostics; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal sealed class AnalyzerDependencyConflict { public AnalyzerDependencyConflict(AssemblyIdentity identity, string analyzerFilePath1, string analyzerFilePath2) { Debug.Assert(identity != null); Debug.Assert(analyzerFilePath1 != null); Debug.Assert(analyzerFilePath2 != null); Identity = identity; AnalyzerFilePath1 = analyzerFilePath1; AnalyzerFilePath2 = analyzerFilePath2; } public string AnalyzerFilePath1 { get; } public string AnalyzerFilePath2 { get; } public AssemblyIdentity Identity { get; } } }
// 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. #nullable disable using Microsoft.CodeAnalysis; using System.Diagnostics; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal sealed class AnalyzerDependencyConflict { public AnalyzerDependencyConflict(AssemblyIdentity identity, string analyzerFilePath1, string analyzerFilePath2) { Debug.Assert(identity != null); Debug.Assert(analyzerFilePath1 != null); Debug.Assert(analyzerFilePath2 != null); Identity = identity; AnalyzerFilePath1 = analyzerFilePath1; AnalyzerFilePath2 = analyzerFilePath2; } public string AnalyzerFilePath1 { get; } public string AnalyzerFilePath2 { get; } public AssemblyIdentity Identity { get; } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/Core/Portable/SpellCheck/AbstractSpellCheckCodeFixProvider.cs
// 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. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SpellCheck { internal abstract class AbstractSpellCheckCodeFixProvider<TSimpleName> : CodeFixProvider where TSimpleName : SyntaxNode { private const int MinTokenLength = 3; public override FixAllProvider GetFixAllProvider() { // Fix All is not supported by this code fix // https://github.com/dotnet/roslyn/issues/34462 return null; } protected abstract bool IsGeneric(SyntaxToken nameToken); protected abstract bool IsGeneric(TSimpleName nameNode); protected abstract bool IsGeneric(CompletionItem completionItem); protected abstract SyntaxToken CreateIdentifier(SyntaxToken nameToken, string newName); public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var span = context.Span; var cancellationToken = context.CancellationToken; var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = syntaxRoot.FindNode(span); if (node != null && node.Span == span) { await CheckNodeAsync(context, document, node, cancellationToken).ConfigureAwait(false); return; } // didn't get a node that matches the span. see if there's a token that matches. var token = syntaxRoot.FindToken(span.Start); if (token.RawKind != 0 && token.Span == span) { await CheckTokenAsync(context, document, token, cancellationToken).ConfigureAwait(false); return; } } private async Task CheckNodeAsync(CodeFixContext context, Document document, SyntaxNode node, CancellationToken cancellationToken) { SemanticModel semanticModel = null; foreach (var name in node.DescendantNodesAndSelf(DescendIntoChildren).OfType<TSimpleName>()) { if (!ShouldSpellCheck(name)) { continue; } // Only bother with identifiers that are at least 3 characters long. // We don't want to be too noisy as you're just starting to type something. var token = name.GetFirstToken(); var nameText = token.ValueText; if (nameText?.Length >= MinTokenLength) { semanticModel ??= await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbolInfo = semanticModel.GetSymbolInfo(name, cancellationToken); if (symbolInfo.Symbol == null) { await CreateSpellCheckCodeIssueAsync(context, token, IsGeneric(name), cancellationToken).ConfigureAwait(false); } } } } private async Task CheckTokenAsync(CodeFixContext context, Document document, SyntaxToken token, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (!syntaxFacts.IsWord(token)) { return; } var nameText = token.ValueText; if (nameText?.Length >= MinTokenLength) { await CreateSpellCheckCodeIssueAsync(context, token, IsGeneric(token), cancellationToken).ConfigureAwait(false); } } protected abstract bool ShouldSpellCheck(TSimpleName name); protected abstract bool DescendIntoChildren(SyntaxNode arg); private async Task CreateSpellCheckCodeIssueAsync( CodeFixContext context, SyntaxToken nameToken, bool isGeneric, CancellationToken cancellationToken) { var document = context.Document; var service = CompletionService.GetService(document); // Disable snippets and unimported types from ever appearing in the completion items. // - It's very unlikely the user would ever misspell a snippet, then use spell-checking to fix it, // then try to invoke the snippet. // - We believe spell-check should only compare what you have typed to what symbol would be offered here. var originalOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var options = originalOptions .WithChangedOption(CompletionOptions.SnippetsBehavior, document.Project.Language, SnippetsRule.NeverInclude) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, document.Project.Language, false) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false); var completionList = await service.GetCompletionsAsync( document, nameToken.SpanStart, options: options, cancellationToken: cancellationToken).ConfigureAwait(false); if (completionList == null) { return; } var nameText = nameToken.ValueText; var similarityChecker = WordSimilarityChecker.Allocate(nameText, substringsAreSimilar: true); try { await CheckItemsAsync( context, nameToken, isGeneric, completionList, similarityChecker).ConfigureAwait(false); } finally { similarityChecker.Free(); } } private async Task CheckItemsAsync( CodeFixContext context, SyntaxToken nameToken, bool isGeneric, CompletionList completionList, WordSimilarityChecker similarityChecker) { var document = context.Document; var cancellationToken = context.CancellationToken; var onlyConsiderGenerics = isGeneric; var results = new MultiDictionary<double, string>(); foreach (var item in completionList.Items) { if (onlyConsiderGenerics && !IsGeneric(item)) { continue; } var candidateText = item.FilterText; if (!similarityChecker.AreSimilar(candidateText, out var matchCost)) { continue; } var insertionText = await GetInsertionTextAsync(document, item, completionList.Span, cancellationToken: cancellationToken).ConfigureAwait(false); results.Add(matchCost, insertionText); } var nameText = nameToken.ValueText; var codeActions = results.OrderBy(kvp => kvp.Key) .SelectMany(kvp => kvp.Value.Order()) .Where(t => t != nameText) .Take(3) .Select(n => CreateCodeAction(nameToken, nameText, n, document)) .ToImmutableArrayOrEmpty<CodeAction>(); if (codeActions.Length > 1) { // Wrap the spell checking actions into a single top level suggestion // so as to not clutter the list. context.RegisterCodeFix(new MyCodeAction( string.Format(FeaturesResources.Fix_typo_0, nameText), codeActions), context.Diagnostics); } else { context.RegisterFixes(codeActions, context.Diagnostics); } } private static readonly char[] s_punctuation = new[] { '(', '[', '<' }; private static async Task<string> GetInsertionTextAsync(Document document, CompletionItem item, TextSpan completionListSpan, CancellationToken cancellationToken) { var service = CompletionService.GetService(document); var change = await service.GetChangeAsync(document, item, commitCharacter: null, cancellationToken).ConfigureAwait(false); var text = change.TextChange.NewText; var nonCharIndex = text.IndexOfAny(s_punctuation); return nonCharIndex > 0 ? text[0..nonCharIndex] : text; } private SpellCheckCodeAction CreateCodeAction(SyntaxToken nameToken, string oldName, string newName, Document document) { return new SpellCheckCodeAction( string.Format(FeaturesResources.Change_0_to_1, oldName, newName), c => UpdateAsync(document, nameToken, newName, c), equivalenceKey: newName); } private async Task<Document> UpdateAsync(Document document, SyntaxToken nameToken, string newName, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = root.ReplaceToken(nameToken, CreateIdentifier(nameToken, newName)); return document.WithSyntaxRoot(newRoot); } private class SpellCheckCodeAction : CodeAction.DocumentChangeAction { public SpellCheckCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } private class MyCodeAction : CodeAction.CodeActionWithNestedActions { public MyCodeAction(string title, ImmutableArray<CodeAction> nestedActions) : base(title, nestedActions, isInlinable: true) { } } } }
// 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. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SpellCheck { internal abstract class AbstractSpellCheckCodeFixProvider<TSimpleName> : CodeFixProvider where TSimpleName : SyntaxNode { private const int MinTokenLength = 3; public override FixAllProvider GetFixAllProvider() { // Fix All is not supported by this code fix // https://github.com/dotnet/roslyn/issues/34462 return null; } protected abstract bool IsGeneric(SyntaxToken nameToken); protected abstract bool IsGeneric(TSimpleName nameNode); protected abstract bool IsGeneric(CompletionItem completionItem); protected abstract SyntaxToken CreateIdentifier(SyntaxToken nameToken, string newName); public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var span = context.Span; var cancellationToken = context.CancellationToken; var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = syntaxRoot.FindNode(span); if (node != null && node.Span == span) { await CheckNodeAsync(context, document, node, cancellationToken).ConfigureAwait(false); return; } // didn't get a node that matches the span. see if there's a token that matches. var token = syntaxRoot.FindToken(span.Start); if (token.RawKind != 0 && token.Span == span) { await CheckTokenAsync(context, document, token, cancellationToken).ConfigureAwait(false); return; } } private async Task CheckNodeAsync(CodeFixContext context, Document document, SyntaxNode node, CancellationToken cancellationToken) { SemanticModel semanticModel = null; foreach (var name in node.DescendantNodesAndSelf(DescendIntoChildren).OfType<TSimpleName>()) { if (!ShouldSpellCheck(name)) { continue; } // Only bother with identifiers that are at least 3 characters long. // We don't want to be too noisy as you're just starting to type something. var token = name.GetFirstToken(); var nameText = token.ValueText; if (nameText?.Length >= MinTokenLength) { semanticModel ??= await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbolInfo = semanticModel.GetSymbolInfo(name, cancellationToken); if (symbolInfo.Symbol == null) { await CreateSpellCheckCodeIssueAsync(context, token, IsGeneric(name), cancellationToken).ConfigureAwait(false); } } } } private async Task CheckTokenAsync(CodeFixContext context, Document document, SyntaxToken token, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (!syntaxFacts.IsWord(token)) { return; } var nameText = token.ValueText; if (nameText?.Length >= MinTokenLength) { await CreateSpellCheckCodeIssueAsync(context, token, IsGeneric(token), cancellationToken).ConfigureAwait(false); } } protected abstract bool ShouldSpellCheck(TSimpleName name); protected abstract bool DescendIntoChildren(SyntaxNode arg); private async Task CreateSpellCheckCodeIssueAsync( CodeFixContext context, SyntaxToken nameToken, bool isGeneric, CancellationToken cancellationToken) { var document = context.Document; var service = CompletionService.GetService(document); // Disable snippets and unimported types from ever appearing in the completion items. // - It's very unlikely the user would ever misspell a snippet, then use spell-checking to fix it, // then try to invoke the snippet. // - We believe spell-check should only compare what you have typed to what symbol would be offered here. var originalOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var options = originalOptions .WithChangedOption(CompletionOptions.SnippetsBehavior, document.Project.Language, SnippetsRule.NeverInclude) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, document.Project.Language, false) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false); var completionList = await service.GetCompletionsAsync( document, nameToken.SpanStart, options: options, cancellationToken: cancellationToken).ConfigureAwait(false); if (completionList == null) { return; } var nameText = nameToken.ValueText; var similarityChecker = WordSimilarityChecker.Allocate(nameText, substringsAreSimilar: true); try { await CheckItemsAsync( context, nameToken, isGeneric, completionList, similarityChecker).ConfigureAwait(false); } finally { similarityChecker.Free(); } } private async Task CheckItemsAsync( CodeFixContext context, SyntaxToken nameToken, bool isGeneric, CompletionList completionList, WordSimilarityChecker similarityChecker) { var document = context.Document; var cancellationToken = context.CancellationToken; var onlyConsiderGenerics = isGeneric; var results = new MultiDictionary<double, string>(); foreach (var item in completionList.Items) { if (onlyConsiderGenerics && !IsGeneric(item)) { continue; } var candidateText = item.FilterText; if (!similarityChecker.AreSimilar(candidateText, out var matchCost)) { continue; } var insertionText = await GetInsertionTextAsync(document, item, completionList.Span, cancellationToken: cancellationToken).ConfigureAwait(false); results.Add(matchCost, insertionText); } var nameText = nameToken.ValueText; var codeActions = results.OrderBy(kvp => kvp.Key) .SelectMany(kvp => kvp.Value.Order()) .Where(t => t != nameText) .Take(3) .Select(n => CreateCodeAction(nameToken, nameText, n, document)) .ToImmutableArrayOrEmpty<CodeAction>(); if (codeActions.Length > 1) { // Wrap the spell checking actions into a single top level suggestion // so as to not clutter the list. context.RegisterCodeFix(new MyCodeAction( string.Format(FeaturesResources.Fix_typo_0, nameText), codeActions), context.Diagnostics); } else { context.RegisterFixes(codeActions, context.Diagnostics); } } private static readonly char[] s_punctuation = new[] { '(', '[', '<' }; private static async Task<string> GetInsertionTextAsync(Document document, CompletionItem item, TextSpan completionListSpan, CancellationToken cancellationToken) { var service = CompletionService.GetService(document); var change = await service.GetChangeAsync(document, item, commitCharacter: null, cancellationToken).ConfigureAwait(false); var text = change.TextChange.NewText; var nonCharIndex = text.IndexOfAny(s_punctuation); return nonCharIndex > 0 ? text[0..nonCharIndex] : text; } private SpellCheckCodeAction CreateCodeAction(SyntaxToken nameToken, string oldName, string newName, Document document) { return new SpellCheckCodeAction( string.Format(FeaturesResources.Change_0_to_1, oldName, newName), c => UpdateAsync(document, nameToken, newName, c), equivalenceKey: newName); } private async Task<Document> UpdateAsync(Document document, SyntaxToken nameToken, string newName, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = root.ReplaceToken(nameToken, CreateIdentifier(nameToken, newName)); return document.WithSyntaxRoot(newRoot); } private class SpellCheckCodeAction : CodeAction.DocumentChangeAction { public SpellCheckCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } private class MyCodeAction : CodeAction.CodeActionWithNestedActions { public MyCodeAction(string title, ImmutableArray<CodeAction> nestedActions) : base(title, nestedActions, isInlinable: true) { } } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/TestUtilities/Extensions/ExportProviderExtensions.cs
// 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. #nullable disable using System.Linq; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Composition; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { internal static class ExportProviderExtensions { public static TCommandHandler GetCommandHandler<TCommandHandler>(this ExportProvider exportProvider, string name) where TCommandHandler : ICommandHandler { var lazyCommandHandlers = exportProvider.GetExports<ICommandHandler, OrderableMetadata>(); return Assert.IsType<TCommandHandler>(lazyCommandHandlers.Single(lazyCommandHandler => lazyCommandHandler.Metadata.Name == name).Value); } public static TCommandHandler GetCommandHandler<TCommandHandler>(this ExportProvider exportProvider, string name, string contentType) where TCommandHandler : ICommandHandler { var lazyCommandHandlers = exportProvider.GetExports<ICommandHandler, OrderableContentTypeMetadata>(); return Assert.IsType<TCommandHandler>(lazyCommandHandlers.Single(lazyCommandHandler => lazyCommandHandler.Metadata.Name == name && lazyCommandHandler.Metadata.ContentTypes.Contains(contentType)).Value); } } }
// 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. #nullable disable using System.Linq; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Composition; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { internal static class ExportProviderExtensions { public static TCommandHandler GetCommandHandler<TCommandHandler>(this ExportProvider exportProvider, string name) where TCommandHandler : ICommandHandler { var lazyCommandHandlers = exportProvider.GetExports<ICommandHandler, OrderableMetadata>(); return Assert.IsType<TCommandHandler>(lazyCommandHandlers.Single(lazyCommandHandler => lazyCommandHandler.Metadata.Name == name).Value); } public static TCommandHandler GetCommandHandler<TCommandHandler>(this ExportProvider exportProvider, string name, string contentType) where TCommandHandler : ICommandHandler { var lazyCommandHandlers = exportProvider.GetExports<ICommandHandler, OrderableContentTypeMetadata>(); return Assert.IsType<TCommandHandler>(lazyCommandHandlers.Single(lazyCommandHandler => lazyCommandHandler.Metadata.Name == name && lazyCommandHandler.Metadata.ContentTypes.Contains(contentType)).Value); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.cs
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderLocalFunctionParametersAndArguments_OnDeclaration() { var markup = @" using System; class MyClass { public void M() { Goo(1, 2); void $$Goo(int x, string y) { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void M() { Goo(2, 1); void Goo(string y, int x) { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderLocalFunctionParametersAndArguments_OnInvocation() { var markup = @" using System; class MyClass { public void M() { $$Goo(1, null); void Goo(int x, string y) { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void M() { Goo(null, 1); void Goo(string y, int x) { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters() { var markup = @" using System; class MyClass { public void $$Goo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParametersAndArguments() { var markup = @" using System; class MyClass { public void $$Goo(int x, string y) { Goo(3, ""hello""); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { Goo(""hello"", 3); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParametersAndArgumentsOfNestedCalls() { var markup = @" using System; class MyClass { public int $$Goo(int x, string y) { return Goo(Goo(4, ""inner""), ""outer""); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public int Goo(string y, int x) { return Goo(""outer"", Goo(""inner"", 4)); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderConstructorParametersAndArguments() { var markup = @" using System; class MyClass2 : MyClass { public MyClass2() : base(5, ""test2"") { } } class MyClass { public MyClass() : this(2, ""test"") { } public $$MyClass(int x, string y) { var t = new MyClass(x, y); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass2 : MyClass { public MyClass2() : base(""test2"", 5) { } } class MyClass { public MyClass() : this(""test"", 2) { } public MyClass(string y, int x) { var t = new MyClass(y, x); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WorkItem(44126, "https://github.com/dotnet/roslyn/issues/44126")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderConstructorParametersAndArguments_ImplicitObjectCreation() { var markup = @" using System; class MyClass2 : MyClass { public MyClass2() : base(5, ""test2"") { } } class MyClass { public MyClass() : this(2, ""test"") { } public MyClass(int x, string y) { MyClass t = new$$(x, y); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass2 : MyClass { public MyClass2() : base(""test2"", 5) { } } class MyClass { public MyClass() : this(""test"", 2) { } public MyClass(string y, int x) { MyClass t = new(y, x); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderAttributeConstructorParametersAndArguments() { var markup = @" [My(""test"", 8)] class MyClass { } class MyAttribute : System.Attribute { public MyAttribute(string x, int y)$$ { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" [My(8, ""test"")] class MyClass { } class MyAttribute : System.Attribute { public MyAttribute(int y, string x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderExtensionMethodParametersAndArguments_StaticCall() { var markup = @" public class C { static void Main(string[] args) { CExt.M(new C(), 1, 2, ""three"", ""four"", ""five""); } } public static class CExt { public static void M(this $$C goo, int x, int y, string a = ""test_a"", string b = ""test_b"", string c = ""test_c"") { } }"; var permutation = new[] { 0, 2, 1, 5, 4, 3 }; var updatedCode = @" public class C { static void Main(string[] args) { CExt.M(new C(), 2, 1, ""five"", ""four"", ""three""); } } public static class CExt { public static void M(this C goo, int y, int x, string c = ""test_c"", string b = ""test_b"", string a = ""test_a"") { } }"; // Although the `ParameterConfig` has 0 for the `SelectedIndex`, the UI dialog will make an adjustment // and select parameter `y` instead because the `this` parameter cannot be moved or removed. await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderExtensionMethodParametersAndArguments_ExtensionCall() { var markup = @" public class C { static void Main(string[] args) { new C().M(1, 2, ""three"", ""four"", ""five""); } } public static class CExt { public static void M(this C goo, int x$$, int y, string a = ""test_a"", string b = ""test_b"", string c = ""test_c"") { } }"; var permutation = new[] { 0, 2, 1, 5, 4, 3 }; var updatedCode = @" public class C { static void Main(string[] args) { new C().M(2, 1, ""five"", ""four"", ""three""); } } public static class CExt { public static void M(this C goo, int y, int x, string c = ""test_c"", string b = ""test_b"", string a = ""test_a"") { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 1); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamsMethodParametersAndArguments_ParamsAsArray() { var markup = @" public class C { void $$M(int x, int y, params int[] p) { M(x, y, new[] { 1, 2, 3 }); } }"; var permutation = new[] { 1, 0, 2 }; var updatedCode = @" public class C { void M(int y, int x, params int[] p) { M(y, x, new[] { 1, 2, 3 }); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamsMethodParametersAndArguments_ParamsExpanded() { var markup = @" public class C { void $$M(int x, int y, params int[] p) { M(x, y, 1, 2, 3); } }"; var permutation = new[] { 1, 0, 2 }; var updatedCode = @" public class C { void M(int y, int x, params int[] p) { M(y, x, 1, 2, 3); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderExtensionAndParamsMethodParametersAndArguments_VariedCallsites() { var markup = @" public class C { static void Main(string[] args) { CExt.M(new C(), 1, 2, ""three"", ""four"", ""five"", new[] { 6, 7, 8 }); CExt.M(new C(), 1, 2, ""three"", ""four"", ""five"", 6, 7, 8); new C().M(1, 2, ""three"", ""four"", ""five"", new[] { 6, 7, 8 }); new C().M(1, 2, ""three"", ""four"", ""five"", 6, 7, 8); } } public static class CExt { public static void $$M(this C goo, int x, int y, string a = ""test_a"", string b = ""test_b"", string c = ""test_c"", params int[] p) { } }"; var permutation = new[] { 0, 2, 1, 5, 4, 3, 6 }; var updatedCode = @" public class C { static void Main(string[] args) { CExt.M(new C(), 2, 1, ""five"", ""four"", ""three"", new[] { 6, 7, 8 }); CExt.M(new C(), 2, 1, ""five"", ""four"", ""three"", 6, 7, 8); new C().M(2, 1, ""five"", ""four"", ""three"", new[] { 6, 7, 8 }); new C().M(2, 1, ""five"", ""four"", ""three"", 6, 7, 8); } } public static class CExt { public static void M(this C goo, int y, int x, string c = ""test_c"", string b = ""test_b"", string a = ""test_a"", params int[] p) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParametersAndArguments() { var markup = @" class Program { void M() { var x = new Program()[1, 2]; new Program()[1, 2] = x; } public int this[int x, int y]$$ { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M() { var x = new Program()[2, 1]; new Program()[2, 1] = x; } public int this[int y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_SingleLineDocComments_OnIndividualLines() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""c""></param> /// <param name=""b""></param> /// <param name=""a""></param> void Goo(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_SingleLineDocComments_OnSameLine() { var markup = @" public class C { /// <param name=""a"">a is fun</param><param name=""b"">b is fun</param><param name=""c"">c is fun</param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""c"">c is fun</param><param name=""b"">b is fun</param><param name=""a"">a is fun</param> void Goo(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_SingleLineDocComments_MixedLineDistribution() { var markup = @" public class C { /// <param name=""a""></param><param name=""b""></param> /// <param name=""c""></param> /// <param name=""d""></param> /// <param name=""e"">Comments spread /// over several /// lines</param><param name=""f""></param> void $$Goo(int a, int b, int c, int d, int e, int f) { } }"; var permutation = new[] { 5, 4, 3, 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""f""></param><param name=""e"">Comments spread /// over several /// lines</param> /// <param name=""d""></param> /// <param name=""c""></param> /// <param name=""b""></param><param name=""a""></param> void Goo(int f, int e, int d, int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_SingleLineDocComments_MixedWithRegularComments() { var markup = @" public class C { /// <param name=""a""></param><param name=""b""></param> // Why is there a regular comment here? /// <param name=""c""></param><param name=""d""></param><param name=""e""></param> void $$Goo(int a, int b, int c, int d, int e) { } }"; var permutation = new[] { 4, 3, 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""e""></param><param name=""d""></param> // Why is there a regular comment here? /// <param name=""c""></param><param name=""b""></param><param name=""a""></param> void Goo(int e, int d, int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_MultiLineDocComments_OnSeparateLines1() { var markup = @" class Program { /** * <param name=""x"">x!</param> * <param name=""y"">y!</param> * <param name=""z"">z!</param> */ static void $$M(int x, int y, int z) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" class Program { /** * <param name=""z"">z!</param> * <param name=""y"">y!</param> * <param name=""x"">x!</param> */ static void M(int z, int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_MultiLineDocComments_OnSingleLine() { var markup = @" class Program { /** <param name=""x"">x!</param><param name=""y"">y!</param><param name=""z"">z!</param> */ static void $$M(int x, int y, int z) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" class Program { /** <param name=""z"">z!</param><param name=""y"">y!</param><param name=""x"">x!</param> */ static void M(int z, int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_IncorrectOrder_MaintainsOrder() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> /// <param name=""b""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> /// <param name=""b""></param> void Goo(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_WrongNames_MaintainsOrder() { var markup = @" public class C { /// <param name=""a2""></param> /// <param name=""b""></param> /// <param name=""c""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""a2""></param> /// <param name=""b""></param> /// <param name=""c""></param> void Goo(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_InsufficientTags_MaintainsOrder() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> void Goo(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_ExcessiveTags_MaintainsOrder() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> /// <param name=""d""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> /// <param name=""d""></param> void Goo(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_OnConstructors() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> public $$C(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""c""></param> /// <param name=""b""></param> /// <param name=""a""></param> public C(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_OnIndexers() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> public int $$this[int a, int b, int c] { get { return 5; } set { } } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""c""></param> /// <param name=""b""></param> /// <param name=""a""></param> public int this[int c, int b, int a] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParametersInCrefs() { var markup = @" class C { /// <summary> /// See <see cref=""M(int, string)""/> and <see cref=""M""/> /// </summary> $$void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class C { /// <summary> /// See <see cref=""M(string, int)""/> and <see cref=""M""/> /// </summary> void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParametersInMethodThatImplementsInterfaceMethodOnlyThroughADerivedType1() { var markup = @" interface I { $$void M(int x, string y); } class C { public void M(int x, string y) { } } class D : C, I { }"; var permutation = new[] { 1, 0 }; var updatedCode = @" interface I { void M(string y, int x); } class C { public void M(string y, int x) { } } class D : C, I { }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParametersInMethodThatImplementsInterfaceMethodOnlyThroughADerivedType2() { var markup = @" interface I { void M(int x, string y); } class C { $$public void M(int x, string y) { } } class D : C, I { }"; var permutation = new[] { 1, 0 }; var updatedCode = @" interface I { void M(string y, int x); } class C { public void M(string y, int x) { } } class D : C, I { }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_Record() { var markup = @" /// <param name=""A""></param> /// <param name=""B""></param> /// <param name=""C""></param> record $$R(int A, int B, int C) { public static R Instance = new(0, 1, 2); }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" /// <param name=""C""></param> /// <param name=""B""></param> /// <param name=""A""></param> record R(int C, int B, int A) { public static R Instance = new(2, 1, 0); }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } } }
// 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderLocalFunctionParametersAndArguments_OnDeclaration() { var markup = @" using System; class MyClass { public void M() { Goo(1, 2); void $$Goo(int x, string y) { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void M() { Goo(2, 1); void Goo(string y, int x) { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderLocalFunctionParametersAndArguments_OnInvocation() { var markup = @" using System; class MyClass { public void M() { $$Goo(1, null); void Goo(int x, string y) { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void M() { Goo(null, 1); void Goo(string y, int x) { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters() { var markup = @" using System; class MyClass { public void $$Goo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParametersAndArguments() { var markup = @" using System; class MyClass { public void $$Goo(int x, string y) { Goo(3, ""hello""); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { Goo(""hello"", 3); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParametersAndArgumentsOfNestedCalls() { var markup = @" using System; class MyClass { public int $$Goo(int x, string y) { return Goo(Goo(4, ""inner""), ""outer""); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public int Goo(string y, int x) { return Goo(""outer"", Goo(""inner"", 4)); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderConstructorParametersAndArguments() { var markup = @" using System; class MyClass2 : MyClass { public MyClass2() : base(5, ""test2"") { } } class MyClass { public MyClass() : this(2, ""test"") { } public $$MyClass(int x, string y) { var t = new MyClass(x, y); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass2 : MyClass { public MyClass2() : base(""test2"", 5) { } } class MyClass { public MyClass() : this(""test"", 2) { } public MyClass(string y, int x) { var t = new MyClass(y, x); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WorkItem(44126, "https://github.com/dotnet/roslyn/issues/44126")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderConstructorParametersAndArguments_ImplicitObjectCreation() { var markup = @" using System; class MyClass2 : MyClass { public MyClass2() : base(5, ""test2"") { } } class MyClass { public MyClass() : this(2, ""test"") { } public MyClass(int x, string y) { MyClass t = new$$(x, y); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass2 : MyClass { public MyClass2() : base(""test2"", 5) { } } class MyClass { public MyClass() : this(""test"", 2) { } public MyClass(string y, int x) { MyClass t = new(y, x); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderAttributeConstructorParametersAndArguments() { var markup = @" [My(""test"", 8)] class MyClass { } class MyAttribute : System.Attribute { public MyAttribute(string x, int y)$$ { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" [My(8, ""test"")] class MyClass { } class MyAttribute : System.Attribute { public MyAttribute(int y, string x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderExtensionMethodParametersAndArguments_StaticCall() { var markup = @" public class C { static void Main(string[] args) { CExt.M(new C(), 1, 2, ""three"", ""four"", ""five""); } } public static class CExt { public static void M(this $$C goo, int x, int y, string a = ""test_a"", string b = ""test_b"", string c = ""test_c"") { } }"; var permutation = new[] { 0, 2, 1, 5, 4, 3 }; var updatedCode = @" public class C { static void Main(string[] args) { CExt.M(new C(), 2, 1, ""five"", ""four"", ""three""); } } public static class CExt { public static void M(this C goo, int y, int x, string c = ""test_c"", string b = ""test_b"", string a = ""test_a"") { } }"; // Although the `ParameterConfig` has 0 for the `SelectedIndex`, the UI dialog will make an adjustment // and select parameter `y` instead because the `this` parameter cannot be moved or removed. await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderExtensionMethodParametersAndArguments_ExtensionCall() { var markup = @" public class C { static void Main(string[] args) { new C().M(1, 2, ""three"", ""four"", ""five""); } } public static class CExt { public static void M(this C goo, int x$$, int y, string a = ""test_a"", string b = ""test_b"", string c = ""test_c"") { } }"; var permutation = new[] { 0, 2, 1, 5, 4, 3 }; var updatedCode = @" public class C { static void Main(string[] args) { new C().M(2, 1, ""five"", ""four"", ""three""); } } public static class CExt { public static void M(this C goo, int y, int x, string c = ""test_c"", string b = ""test_b"", string a = ""test_a"") { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 1); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamsMethodParametersAndArguments_ParamsAsArray() { var markup = @" public class C { void $$M(int x, int y, params int[] p) { M(x, y, new[] { 1, 2, 3 }); } }"; var permutation = new[] { 1, 0, 2 }; var updatedCode = @" public class C { void M(int y, int x, params int[] p) { M(y, x, new[] { 1, 2, 3 }); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamsMethodParametersAndArguments_ParamsExpanded() { var markup = @" public class C { void $$M(int x, int y, params int[] p) { M(x, y, 1, 2, 3); } }"; var permutation = new[] { 1, 0, 2 }; var updatedCode = @" public class C { void M(int y, int x, params int[] p) { M(y, x, 1, 2, 3); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderExtensionAndParamsMethodParametersAndArguments_VariedCallsites() { var markup = @" public class C { static void Main(string[] args) { CExt.M(new C(), 1, 2, ""three"", ""four"", ""five"", new[] { 6, 7, 8 }); CExt.M(new C(), 1, 2, ""three"", ""four"", ""five"", 6, 7, 8); new C().M(1, 2, ""three"", ""four"", ""five"", new[] { 6, 7, 8 }); new C().M(1, 2, ""three"", ""four"", ""five"", 6, 7, 8); } } public static class CExt { public static void $$M(this C goo, int x, int y, string a = ""test_a"", string b = ""test_b"", string c = ""test_c"", params int[] p) { } }"; var permutation = new[] { 0, 2, 1, 5, 4, 3, 6 }; var updatedCode = @" public class C { static void Main(string[] args) { CExt.M(new C(), 2, 1, ""five"", ""four"", ""three"", new[] { 6, 7, 8 }); CExt.M(new C(), 2, 1, ""five"", ""four"", ""three"", 6, 7, 8); new C().M(2, 1, ""five"", ""four"", ""three"", new[] { 6, 7, 8 }); new C().M(2, 1, ""five"", ""four"", ""three"", 6, 7, 8); } } public static class CExt { public static void M(this C goo, int y, int x, string c = ""test_c"", string b = ""test_b"", string a = ""test_a"", params int[] p) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParametersAndArguments() { var markup = @" class Program { void M() { var x = new Program()[1, 2]; new Program()[1, 2] = x; } public int this[int x, int y]$$ { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M() { var x = new Program()[2, 1]; new Program()[2, 1] = x; } public int this[int y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_SingleLineDocComments_OnIndividualLines() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""c""></param> /// <param name=""b""></param> /// <param name=""a""></param> void Goo(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_SingleLineDocComments_OnSameLine() { var markup = @" public class C { /// <param name=""a"">a is fun</param><param name=""b"">b is fun</param><param name=""c"">c is fun</param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""c"">c is fun</param><param name=""b"">b is fun</param><param name=""a"">a is fun</param> void Goo(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_SingleLineDocComments_MixedLineDistribution() { var markup = @" public class C { /// <param name=""a""></param><param name=""b""></param> /// <param name=""c""></param> /// <param name=""d""></param> /// <param name=""e"">Comments spread /// over several /// lines</param><param name=""f""></param> void $$Goo(int a, int b, int c, int d, int e, int f) { } }"; var permutation = new[] { 5, 4, 3, 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""f""></param><param name=""e"">Comments spread /// over several /// lines</param> /// <param name=""d""></param> /// <param name=""c""></param> /// <param name=""b""></param><param name=""a""></param> void Goo(int f, int e, int d, int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_SingleLineDocComments_MixedWithRegularComments() { var markup = @" public class C { /// <param name=""a""></param><param name=""b""></param> // Why is there a regular comment here? /// <param name=""c""></param><param name=""d""></param><param name=""e""></param> void $$Goo(int a, int b, int c, int d, int e) { } }"; var permutation = new[] { 4, 3, 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""e""></param><param name=""d""></param> // Why is there a regular comment here? /// <param name=""c""></param><param name=""b""></param><param name=""a""></param> void Goo(int e, int d, int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_MultiLineDocComments_OnSeparateLines1() { var markup = @" class Program { /** * <param name=""x"">x!</param> * <param name=""y"">y!</param> * <param name=""z"">z!</param> */ static void $$M(int x, int y, int z) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" class Program { /** * <param name=""z"">z!</param> * <param name=""y"">y!</param> * <param name=""x"">x!</param> */ static void M(int z, int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_MultiLineDocComments_OnSingleLine() { var markup = @" class Program { /** <param name=""x"">x!</param><param name=""y"">y!</param><param name=""z"">z!</param> */ static void $$M(int x, int y, int z) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" class Program { /** <param name=""z"">z!</param><param name=""y"">y!</param><param name=""x"">x!</param> */ static void M(int z, int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_IncorrectOrder_MaintainsOrder() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> /// <param name=""b""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> /// <param name=""b""></param> void Goo(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_WrongNames_MaintainsOrder() { var markup = @" public class C { /// <param name=""a2""></param> /// <param name=""b""></param> /// <param name=""c""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""a2""></param> /// <param name=""b""></param> /// <param name=""c""></param> void Goo(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_InsufficientTags_MaintainsOrder() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""a""></param> /// <param name=""c""></param> void Goo(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_ExcessiveTags_MaintainsOrder() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> /// <param name=""d""></param> void $$Goo(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> /// <param name=""d""></param> void Goo(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_OnConstructors() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> public $$C(int a, int b, int c) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""c""></param> /// <param name=""b""></param> /// <param name=""a""></param> public C(int c, int b, int a) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_OnIndexers() { var markup = @" public class C { /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> public int $$this[int a, int b, int c] { get { return 5; } set { } } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" public class C { /// <param name=""c""></param> /// <param name=""b""></param> /// <param name=""a""></param> public int this[int c, int b, int a] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParametersInCrefs() { var markup = @" class C { /// <summary> /// See <see cref=""M(int, string)""/> and <see cref=""M""/> /// </summary> $$void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class C { /// <summary> /// See <see cref=""M(string, int)""/> and <see cref=""M""/> /// </summary> void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParametersInMethodThatImplementsInterfaceMethodOnlyThroughADerivedType1() { var markup = @" interface I { $$void M(int x, string y); } class C { public void M(int x, string y) { } } class D : C, I { }"; var permutation = new[] { 1, 0 }; var updatedCode = @" interface I { void M(string y, int x); } class C { public void M(string y, int x) { } } class D : C, I { }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParametersInMethodThatImplementsInterfaceMethodOnlyThroughADerivedType2() { var markup = @" interface I { void M(int x, string y); } class C { $$public void M(int x, string y) { } } class D : C, I { }"; var permutation = new[] { 1, 0 }; var updatedCode = @" interface I { void M(string y, int x); } class C { public void M(string y, int x) { } } class D : C, I { }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParamTagsInDocComments_Record() { var markup = @" /// <param name=""A""></param> /// <param name=""B""></param> /// <param name=""C""></param> record $$R(int A, int B, int C) { public static R Instance = new(0, 1, 2); }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" /// <param name=""C""></param> /// <param name=""B""></param> /// <param name=""A""></param> record R(int C, int B, int A) { public static R Instance = new(2, 1, 0); }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ITypeImportCompletionService.cs
// 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 System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion { internal interface ITypeImportCompletionService : ILanguageService { /// <summary> /// Get completion items for all the accessible top level types from the given project and all its references. /// Each array returned contains all items from one of the reachable entities (i.e. projects and PE references.) /// Returns null if we don't have all the items cached and <paramref name="forceCacheCreation"/> is false. /// </summary> /// <remarks> /// Because items from each entity are cached as a separate array, we simply return them as is instead of an /// aggregated array to avoid unnecessary allocations. /// </remarks> Task<ImmutableArray<ImmutableArray<CompletionItem>>?> GetAllTopLevelTypesAsync( Project project, SyntaxContext syntaxContext, bool forceCacheCreation, CancellationToken cancellationToken); Task WarmUpCacheAsync(Project project, CancellationToken cancellationToken); } }
// 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 System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion { internal interface ITypeImportCompletionService : ILanguageService { /// <summary> /// Get completion items for all the accessible top level types from the given project and all its references. /// Each array returned contains all items from one of the reachable entities (i.e. projects and PE references.) /// Returns null if we don't have all the items cached and <paramref name="forceCacheCreation"/> is false. /// </summary> /// <remarks> /// Because items from each entity are cached as a separate array, we simply return them as is instead of an /// aggregated array to avoid unnecessary allocations. /// </remarks> Task<ImmutableArray<ImmutableArray<CompletionItem>>?> GetAllTopLevelTypesAsync( Project project, SyntaxContext syntaxContext, bool forceCacheCreation, CancellationToken cancellationToken); Task WarmUpCacheAsync(Project project, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/VisualStudio/CSharp/Impl/CodeModel/MethodXml/MethodXmlBuilder.cs
// 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. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.MethodXml { internal class MethodXmlBuilder : AbstractMethodXmlBuilder { private MethodXmlBuilder(IMethodSymbol symbol, SemanticModel semanticModel) : base(symbol, semanticModel) { } private void GenerateBlock(BlockSyntax block) { using (BlockTag()) { foreach (var statement in block.Statements) { GenerateComments(statement.GetLeadingTrivia()); GenerateStatement(statement); } // Handle any additional comments now, but only comments within the extent of this block. GenerateComments(block.CloseBraceToken.LeadingTrivia); } } private void GenerateComments(SyntaxTriviaList triviaList) { foreach (var trivia in triviaList) { // Multi-line comment forms are ignored. if (trivia.Kind() == SyntaxKind.SingleLineCommentTrivia) { // In order to be valid, the comment must appear on its own line. var line = Text.Lines.GetLineFromPosition(trivia.SpanStart); var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition() ?? -1; if (firstNonWhitespacePosition == trivia.SpanStart) { using var tag = CommentTag(); // Skip initial slashes var trimmedComment = trivia.ToString().Substring(2); EncodedText(trimmedComment); } } } } private void GenerateStatement(StatementSyntax statement) { var success = false; var mark = GetMark(); switch (statement.Kind()) { case SyntaxKind.LocalDeclarationStatement: success = TryGenerateLocal((LocalDeclarationStatementSyntax)statement); break; case SyntaxKind.Block: success = true; GenerateBlock((BlockSyntax)statement); break; case SyntaxKind.ExpressionStatement: success = TryGenerateExpressionStatement((ExpressionStatementSyntax)statement); break; } if (!success) { Rewind(mark); GenerateUnknown(statement); } // Just for readability LineBreak(); } private bool TryGenerateLocal(LocalDeclarationStatementSyntax localDeclarationStatement) { /* - <ElementType name="Local" content="eltOnly"> <attribute type="id" /> <attribute type="static" /> <attribute type="instance" /> <attribute type="implicit" /> <attribute type="constant" /> - <group order="one"> <element type="Type" /> <element type="ArrayType" /> </group> - <group minOccurs="1" maxOccurs="*" order="seq"> <element type="LocalName" /> <element type="Expression" minOccurs="0" maxOccurs="1" /> </group> </ElementType> */ using (LocalTag(GetLineNumber(localDeclarationStatement))) { // Spew the type first if (!TryGenerateType(localDeclarationStatement.Declaration.Type)) { return false; } // Now spew the list of variables foreach (var variable in localDeclarationStatement.Declaration.Variables) { GenerateName(variable.Identifier.ToString()); if (variable.Initializer != null) { if (!TryGenerateExpression(variable.Initializer.Value)) { return false; } } } } return true; } private bool TryGenerateExpressionStatement(ExpressionStatementSyntax expressionStatement) { using (ExpressionStatementTag(GetLineNumber(expressionStatement))) { return TryGenerateExpression(expressionStatement.Expression); } } private bool TryGenerateType(TypeSyntax type) { var typeSymbol = SemanticModel.GetTypeInfo(type).Type; if (typeSymbol == null) { return false; } GenerateType(typeSymbol); return true; } private bool TryGenerateExpression(ExpressionSyntax expression) { using (ExpressionTag()) { return TryGenerateExpressionSansTag(expression); } } private bool TryGenerateExpressionSansTag(ExpressionSyntax expression) { switch (expression.Kind()) { case SyntaxKind.CharacterLiteralExpression: return TryGenerateCharLiteral(expression); case SyntaxKind.UnaryMinusExpression: case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: return TryGenerateLiteral(expression); case SyntaxKind.NullLiteralExpression: GenerateNullLiteral(); return true; case SyntaxKind.ParenthesizedExpression: return TryGenerateParentheses((ParenthesizedExpressionSyntax)expression); case SyntaxKind.AddExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.BitwiseAndExpression: return TryGenerateBinaryOperation((BinaryExpressionSyntax)expression); case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: return TryGenerateAssignment((AssignmentExpressionSyntax)expression); case SyntaxKind.CastExpression: return TryGenerateCast((CastExpressionSyntax)expression); case SyntaxKind.ObjectCreationExpression: return TryGenerateNewClass((ObjectCreationExpressionSyntax)expression); case SyntaxKind.ArrayCreationExpression: return TryGenerateNewArray((ArrayCreationExpressionSyntax)expression); case SyntaxKind.ArrayInitializerExpression: return TryGenerateArrayLiteral((InitializerExpressionSyntax)expression); case SyntaxKind.SimpleMemberAccessExpression: return TryGenerateNameRef((MemberAccessExpressionSyntax)expression); case SyntaxKind.IdentifierName: return TryGenerateNameRef((IdentifierNameSyntax)expression); case SyntaxKind.InvocationExpression: return GenerateMethodCall((InvocationExpressionSyntax)expression); case SyntaxKind.ElementAccessExpression: return TryGenerateArrayElementAccess((ElementAccessExpressionSyntax)expression); case SyntaxKind.TypeOfExpression: return TryGenerateTypeOfExpression((TypeOfExpressionSyntax)expression); case SyntaxKind.ThisExpression: GenerateThisReference(); return true; case SyntaxKind.BaseExpression: GenerateBaseReference(); return true; } return false; } private bool TryGenerateLiteral(ExpressionSyntax expression) { /* <ElementType name="Literal" content="eltOnly"> - <group order="one"> <element type="Null" /> <element type="Number" /> <element type="Boolean" /> <element type="Char" /> <element type="String" /> <element type="Array" /> <element type="Type" /> </group> </ElementType> */ using (LiteralTag()) { var constantValue = SemanticModel.GetConstantValue(expression); if (!constantValue.HasValue) { return false; } var type = SemanticModel.GetTypeInfo(expression).Type; if (type == null) { return false; } switch (expression.Kind()) { case SyntaxKind.UnaryMinusExpression: case SyntaxKind.NumericLiteralExpression: GenerateNumber(constantValue.Value, type); return true; case SyntaxKind.StringLiteralExpression: GenerateString((string)constantValue.Value); return true; case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: GenerateBoolean((bool)constantValue.Value); return true; } return false; } } private bool TryGenerateCharLiteral(ExpressionSyntax expression) { // For non-letters and digits, generate a cast of the numeric value to a char. // Otherwise, we might end up generating invalid XML. if (expression.Kind() != SyntaxKind.CharacterLiteralExpression) { return false; } var constantValue = SemanticModel.GetConstantValue(expression); if (!constantValue.HasValue) { return false; } var ch = (char)constantValue.Value; if (!char.IsLetterOrDigit(ch)) { using (CastTag()) { GenerateType(SpecialType.System_Char); using (ExpressionTag()) using (LiteralTag()) { GenerateNumber((ushort)ch, SpecialType.System_UInt16); } } } else { using (LiteralTag()) { GenerateChar(ch); } } return true; } private bool TryGenerateParentheses(ParenthesizedExpressionSyntax parenthesizedExpression) { using (ParenthesesTag()) { return TryGenerateExpression(parenthesizedExpression.Expression); } } private bool TryGenerateBinaryOperation(BinaryExpressionSyntax binaryExpression) { BinaryOperatorKind kind; switch (binaryExpression.Kind()) { case SyntaxKind.AddExpression: kind = BinaryOperatorKind.Plus; break; case SyntaxKind.BitwiseOrExpression: kind = BinaryOperatorKind.BitwiseOr; break; case SyntaxKind.BitwiseAndExpression: kind = BinaryOperatorKind.BitwiseAnd; break; default: return false; } using (BinaryOperationTag(kind)) { return TryGenerateExpression(binaryExpression.Left) && TryGenerateExpression(binaryExpression.Right); } } private bool TryGenerateAssignment(AssignmentExpressionSyntax binaryExpression) { var kind = BinaryOperatorKind.None; switch (binaryExpression.Kind()) { case SyntaxKind.AddAssignmentExpression: kind = BinaryOperatorKind.AddDelegate; break; } using (AssignmentTag(kind)) { return TryGenerateExpression(binaryExpression.Left) && TryGenerateExpression(binaryExpression.Right); } } private bool TryGenerateCast(CastExpressionSyntax castExpression) { var type = SemanticModel.GetTypeInfo(castExpression.Type).Type; if (type == null) { return false; } using (CastTag()) { GenerateType(type); return TryGenerateExpression(castExpression.Expression); } } private bool TryGenerateNewClass(ObjectCreationExpressionSyntax objectCreationExpression) { if (!(SemanticModel.GetSymbolInfo(objectCreationExpression.Type).Symbol is ITypeSymbol type)) { return false; } using (NewClassTag()) { GenerateType(type); foreach (var argument in objectCreationExpression.ArgumentList.Arguments) { if (!TryGenerateArgument(argument)) { return false; } } } return true; } private bool TryGenerateNewArray(ArrayCreationExpressionSyntax arrayCreationExpression) { var type = SemanticModel.GetTypeInfo(arrayCreationExpression).Type; if (type == null) { return false; } using (NewArrayTag()) { GenerateType(type); if (arrayCreationExpression.Initializer != null) { using (BoundTag()) using (ExpressionTag()) using (LiteralTag()) using (NumberTag()) { EncodedText(arrayCreationExpression.Initializer.Expressions.Count.ToString()); } if (!TryGenerateExpression(arrayCreationExpression.Initializer)) { return false; } } else { foreach (var rankSpecifier in arrayCreationExpression.Type.RankSpecifiers) { foreach (var size in rankSpecifier.Sizes) { using (BoundTag()) { if (!TryGenerateExpression(size)) { return false; } } } } } } return true; } private bool TryGenerateArrayLiteral(InitializerExpressionSyntax initializerExpression) { using (LiteralTag()) using (ArrayTag()) { foreach (var expression in initializerExpression.Expressions) { if (!TryGenerateExpression(expression)) { return false; } } } return true; } private bool TryGenerateNameRef(MemberAccessExpressionSyntax memberAccessExpression) { var symbol = SemanticModel.GetSymbolInfo(memberAccessExpression).Symbol; // No null check for 'symbol' here. If 'symbol' unknown, we'll // generate an "unknown" name ref. using (NameRefTag(GetVariableKind(symbol))) { var leftHandSymbol = SemanticModel.GetSymbolInfo(memberAccessExpression.Expression).Symbol; if (leftHandSymbol != null) { if (leftHandSymbol.Kind == SymbolKind.Alias) { leftHandSymbol = ((IAliasSymbol)leftHandSymbol).Target; } } // If the left-hand side is a named type, we generate a literal expression // with the type name. Otherwise, we generate the expression normally. if (leftHandSymbol != null && leftHandSymbol.Kind == SymbolKind.NamedType) { using (ExpressionTag()) using (LiteralTag()) { GenerateType((ITypeSymbol)leftHandSymbol); } } else if (!TryGenerateExpression(memberAccessExpression.Expression)) { return false; } GenerateName(memberAccessExpression.Name.Identifier.ValueText); } return true; } private bool TryGenerateNameRef(IdentifierNameSyntax identifierName) { var symbol = SemanticModel.GetSymbolInfo(identifierName).Symbol; // No null check for 'symbol' here. If 'symbol' unknown, we'll // generate an "unknown" name ref. var variableKind = GetVariableKind(symbol); using (NameRefTag(variableKind)) { if (symbol != null && variableKind != VariableKind.Local) { using (ExpressionTag()) { GenerateThisReference(); } } GenerateName(identifierName.Identifier.ToString()); } return true; } private bool GenerateMethodCall(InvocationExpressionSyntax invocationExpression) { using (MethodCallTag()) { if (!TryGenerateExpression(invocationExpression.Expression)) { return false; } foreach (var argument in invocationExpression.ArgumentList.Arguments) { if (!TryGenerateArgument(argument)) { return false; } } } return true; } private bool TryGenerateTypeOfExpression(TypeOfExpressionSyntax typeOfExpression) { if (typeOfExpression.Type == null) { return false; } var type = SemanticModel.GetTypeInfo(typeOfExpression.Type).Type; if (type == null) { return false; } GenerateType(type); return true; } private bool TryGenerateArrayElementAccess(ElementAccessExpressionSyntax elementAccessExpression) { using (ArrayElementAccessTag()) { if (!TryGenerateExpression(elementAccessExpression.Expression)) { return false; } foreach (var argument in elementAccessExpression.ArgumentList.Arguments) { if (!TryGenerateExpression(argument.Expression)) { return false; } } } return true; } private bool TryGenerateArgument(ArgumentSyntax argument) { using (ArgumentTag()) { return TryGenerateExpression(argument.Expression); } } public static string Generate(MethodDeclarationSyntax methodDeclaration, SemanticModel semanticModel) { var symbol = semanticModel.GetDeclaredSymbol(methodDeclaration); var builder = new MethodXmlBuilder(symbol, semanticModel); builder.GenerateBlock(methodDeclaration.Body); return builder.ToString(); } } }
// 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. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.MethodXml { internal class MethodXmlBuilder : AbstractMethodXmlBuilder { private MethodXmlBuilder(IMethodSymbol symbol, SemanticModel semanticModel) : base(symbol, semanticModel) { } private void GenerateBlock(BlockSyntax block) { using (BlockTag()) { foreach (var statement in block.Statements) { GenerateComments(statement.GetLeadingTrivia()); GenerateStatement(statement); } // Handle any additional comments now, but only comments within the extent of this block. GenerateComments(block.CloseBraceToken.LeadingTrivia); } } private void GenerateComments(SyntaxTriviaList triviaList) { foreach (var trivia in triviaList) { // Multi-line comment forms are ignored. if (trivia.Kind() == SyntaxKind.SingleLineCommentTrivia) { // In order to be valid, the comment must appear on its own line. var line = Text.Lines.GetLineFromPosition(trivia.SpanStart); var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition() ?? -1; if (firstNonWhitespacePosition == trivia.SpanStart) { using var tag = CommentTag(); // Skip initial slashes var trimmedComment = trivia.ToString().Substring(2); EncodedText(trimmedComment); } } } } private void GenerateStatement(StatementSyntax statement) { var success = false; var mark = GetMark(); switch (statement.Kind()) { case SyntaxKind.LocalDeclarationStatement: success = TryGenerateLocal((LocalDeclarationStatementSyntax)statement); break; case SyntaxKind.Block: success = true; GenerateBlock((BlockSyntax)statement); break; case SyntaxKind.ExpressionStatement: success = TryGenerateExpressionStatement((ExpressionStatementSyntax)statement); break; } if (!success) { Rewind(mark); GenerateUnknown(statement); } // Just for readability LineBreak(); } private bool TryGenerateLocal(LocalDeclarationStatementSyntax localDeclarationStatement) { /* - <ElementType name="Local" content="eltOnly"> <attribute type="id" /> <attribute type="static" /> <attribute type="instance" /> <attribute type="implicit" /> <attribute type="constant" /> - <group order="one"> <element type="Type" /> <element type="ArrayType" /> </group> - <group minOccurs="1" maxOccurs="*" order="seq"> <element type="LocalName" /> <element type="Expression" minOccurs="0" maxOccurs="1" /> </group> </ElementType> */ using (LocalTag(GetLineNumber(localDeclarationStatement))) { // Spew the type first if (!TryGenerateType(localDeclarationStatement.Declaration.Type)) { return false; } // Now spew the list of variables foreach (var variable in localDeclarationStatement.Declaration.Variables) { GenerateName(variable.Identifier.ToString()); if (variable.Initializer != null) { if (!TryGenerateExpression(variable.Initializer.Value)) { return false; } } } } return true; } private bool TryGenerateExpressionStatement(ExpressionStatementSyntax expressionStatement) { using (ExpressionStatementTag(GetLineNumber(expressionStatement))) { return TryGenerateExpression(expressionStatement.Expression); } } private bool TryGenerateType(TypeSyntax type) { var typeSymbol = SemanticModel.GetTypeInfo(type).Type; if (typeSymbol == null) { return false; } GenerateType(typeSymbol); return true; } private bool TryGenerateExpression(ExpressionSyntax expression) { using (ExpressionTag()) { return TryGenerateExpressionSansTag(expression); } } private bool TryGenerateExpressionSansTag(ExpressionSyntax expression) { switch (expression.Kind()) { case SyntaxKind.CharacterLiteralExpression: return TryGenerateCharLiteral(expression); case SyntaxKind.UnaryMinusExpression: case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: return TryGenerateLiteral(expression); case SyntaxKind.NullLiteralExpression: GenerateNullLiteral(); return true; case SyntaxKind.ParenthesizedExpression: return TryGenerateParentheses((ParenthesizedExpressionSyntax)expression); case SyntaxKind.AddExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.BitwiseAndExpression: return TryGenerateBinaryOperation((BinaryExpressionSyntax)expression); case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: return TryGenerateAssignment((AssignmentExpressionSyntax)expression); case SyntaxKind.CastExpression: return TryGenerateCast((CastExpressionSyntax)expression); case SyntaxKind.ObjectCreationExpression: return TryGenerateNewClass((ObjectCreationExpressionSyntax)expression); case SyntaxKind.ArrayCreationExpression: return TryGenerateNewArray((ArrayCreationExpressionSyntax)expression); case SyntaxKind.ArrayInitializerExpression: return TryGenerateArrayLiteral((InitializerExpressionSyntax)expression); case SyntaxKind.SimpleMemberAccessExpression: return TryGenerateNameRef((MemberAccessExpressionSyntax)expression); case SyntaxKind.IdentifierName: return TryGenerateNameRef((IdentifierNameSyntax)expression); case SyntaxKind.InvocationExpression: return GenerateMethodCall((InvocationExpressionSyntax)expression); case SyntaxKind.ElementAccessExpression: return TryGenerateArrayElementAccess((ElementAccessExpressionSyntax)expression); case SyntaxKind.TypeOfExpression: return TryGenerateTypeOfExpression((TypeOfExpressionSyntax)expression); case SyntaxKind.ThisExpression: GenerateThisReference(); return true; case SyntaxKind.BaseExpression: GenerateBaseReference(); return true; } return false; } private bool TryGenerateLiteral(ExpressionSyntax expression) { /* <ElementType name="Literal" content="eltOnly"> - <group order="one"> <element type="Null" /> <element type="Number" /> <element type="Boolean" /> <element type="Char" /> <element type="String" /> <element type="Array" /> <element type="Type" /> </group> </ElementType> */ using (LiteralTag()) { var constantValue = SemanticModel.GetConstantValue(expression); if (!constantValue.HasValue) { return false; } var type = SemanticModel.GetTypeInfo(expression).Type; if (type == null) { return false; } switch (expression.Kind()) { case SyntaxKind.UnaryMinusExpression: case SyntaxKind.NumericLiteralExpression: GenerateNumber(constantValue.Value, type); return true; case SyntaxKind.StringLiteralExpression: GenerateString((string)constantValue.Value); return true; case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: GenerateBoolean((bool)constantValue.Value); return true; } return false; } } private bool TryGenerateCharLiteral(ExpressionSyntax expression) { // For non-letters and digits, generate a cast of the numeric value to a char. // Otherwise, we might end up generating invalid XML. if (expression.Kind() != SyntaxKind.CharacterLiteralExpression) { return false; } var constantValue = SemanticModel.GetConstantValue(expression); if (!constantValue.HasValue) { return false; } var ch = (char)constantValue.Value; if (!char.IsLetterOrDigit(ch)) { using (CastTag()) { GenerateType(SpecialType.System_Char); using (ExpressionTag()) using (LiteralTag()) { GenerateNumber((ushort)ch, SpecialType.System_UInt16); } } } else { using (LiteralTag()) { GenerateChar(ch); } } return true; } private bool TryGenerateParentheses(ParenthesizedExpressionSyntax parenthesizedExpression) { using (ParenthesesTag()) { return TryGenerateExpression(parenthesizedExpression.Expression); } } private bool TryGenerateBinaryOperation(BinaryExpressionSyntax binaryExpression) { BinaryOperatorKind kind; switch (binaryExpression.Kind()) { case SyntaxKind.AddExpression: kind = BinaryOperatorKind.Plus; break; case SyntaxKind.BitwiseOrExpression: kind = BinaryOperatorKind.BitwiseOr; break; case SyntaxKind.BitwiseAndExpression: kind = BinaryOperatorKind.BitwiseAnd; break; default: return false; } using (BinaryOperationTag(kind)) { return TryGenerateExpression(binaryExpression.Left) && TryGenerateExpression(binaryExpression.Right); } } private bool TryGenerateAssignment(AssignmentExpressionSyntax binaryExpression) { var kind = BinaryOperatorKind.None; switch (binaryExpression.Kind()) { case SyntaxKind.AddAssignmentExpression: kind = BinaryOperatorKind.AddDelegate; break; } using (AssignmentTag(kind)) { return TryGenerateExpression(binaryExpression.Left) && TryGenerateExpression(binaryExpression.Right); } } private bool TryGenerateCast(CastExpressionSyntax castExpression) { var type = SemanticModel.GetTypeInfo(castExpression.Type).Type; if (type == null) { return false; } using (CastTag()) { GenerateType(type); return TryGenerateExpression(castExpression.Expression); } } private bool TryGenerateNewClass(ObjectCreationExpressionSyntax objectCreationExpression) { if (!(SemanticModel.GetSymbolInfo(objectCreationExpression.Type).Symbol is ITypeSymbol type)) { return false; } using (NewClassTag()) { GenerateType(type); foreach (var argument in objectCreationExpression.ArgumentList.Arguments) { if (!TryGenerateArgument(argument)) { return false; } } } return true; } private bool TryGenerateNewArray(ArrayCreationExpressionSyntax arrayCreationExpression) { var type = SemanticModel.GetTypeInfo(arrayCreationExpression).Type; if (type == null) { return false; } using (NewArrayTag()) { GenerateType(type); if (arrayCreationExpression.Initializer != null) { using (BoundTag()) using (ExpressionTag()) using (LiteralTag()) using (NumberTag()) { EncodedText(arrayCreationExpression.Initializer.Expressions.Count.ToString()); } if (!TryGenerateExpression(arrayCreationExpression.Initializer)) { return false; } } else { foreach (var rankSpecifier in arrayCreationExpression.Type.RankSpecifiers) { foreach (var size in rankSpecifier.Sizes) { using (BoundTag()) { if (!TryGenerateExpression(size)) { return false; } } } } } } return true; } private bool TryGenerateArrayLiteral(InitializerExpressionSyntax initializerExpression) { using (LiteralTag()) using (ArrayTag()) { foreach (var expression in initializerExpression.Expressions) { if (!TryGenerateExpression(expression)) { return false; } } } return true; } private bool TryGenerateNameRef(MemberAccessExpressionSyntax memberAccessExpression) { var symbol = SemanticModel.GetSymbolInfo(memberAccessExpression).Symbol; // No null check for 'symbol' here. If 'symbol' unknown, we'll // generate an "unknown" name ref. using (NameRefTag(GetVariableKind(symbol))) { var leftHandSymbol = SemanticModel.GetSymbolInfo(memberAccessExpression.Expression).Symbol; if (leftHandSymbol != null) { if (leftHandSymbol.Kind == SymbolKind.Alias) { leftHandSymbol = ((IAliasSymbol)leftHandSymbol).Target; } } // If the left-hand side is a named type, we generate a literal expression // with the type name. Otherwise, we generate the expression normally. if (leftHandSymbol != null && leftHandSymbol.Kind == SymbolKind.NamedType) { using (ExpressionTag()) using (LiteralTag()) { GenerateType((ITypeSymbol)leftHandSymbol); } } else if (!TryGenerateExpression(memberAccessExpression.Expression)) { return false; } GenerateName(memberAccessExpression.Name.Identifier.ValueText); } return true; } private bool TryGenerateNameRef(IdentifierNameSyntax identifierName) { var symbol = SemanticModel.GetSymbolInfo(identifierName).Symbol; // No null check for 'symbol' here. If 'symbol' unknown, we'll // generate an "unknown" name ref. var variableKind = GetVariableKind(symbol); using (NameRefTag(variableKind)) { if (symbol != null && variableKind != VariableKind.Local) { using (ExpressionTag()) { GenerateThisReference(); } } GenerateName(identifierName.Identifier.ToString()); } return true; } private bool GenerateMethodCall(InvocationExpressionSyntax invocationExpression) { using (MethodCallTag()) { if (!TryGenerateExpression(invocationExpression.Expression)) { return false; } foreach (var argument in invocationExpression.ArgumentList.Arguments) { if (!TryGenerateArgument(argument)) { return false; } } } return true; } private bool TryGenerateTypeOfExpression(TypeOfExpressionSyntax typeOfExpression) { if (typeOfExpression.Type == null) { return false; } var type = SemanticModel.GetTypeInfo(typeOfExpression.Type).Type; if (type == null) { return false; } GenerateType(type); return true; } private bool TryGenerateArrayElementAccess(ElementAccessExpressionSyntax elementAccessExpression) { using (ArrayElementAccessTag()) { if (!TryGenerateExpression(elementAccessExpression.Expression)) { return false; } foreach (var argument in elementAccessExpression.ArgumentList.Arguments) { if (!TryGenerateExpression(argument.Expression)) { return false; } } } return true; } private bool TryGenerateArgument(ArgumentSyntax argument) { using (ArgumentTag()) { return TryGenerateExpression(argument.Expression); } } public static string Generate(MethodDeclarationSyntax methodDeclaration, SemanticModel semanticModel) { var symbol = semanticModel.GetDeclaredSymbol(methodDeclaration); var builder = new MethodXmlBuilder(symbol, semanticModel); builder.GenerateBlock(methodDeclaration.Body); return builder.ToString(); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/VisualBasic/Portable/CodeGeneration/FieldGenerator.vb
' 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. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Module FieldGenerator Private Function LastField(Of TDeclaration As SyntaxNode)( members As SyntaxList(Of TDeclaration), fieldDeclaration As FieldDeclarationSyntax) As TDeclaration Dim lastConst = members.OfType(Of FieldDeclarationSyntax). Where(Function(f) f.Modifiers.Any(SyntaxKind.ConstKeyword)). LastOrDefault() ' Place a const after the last existing const. If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then Return DirectCast(DirectCast(lastConst, Object), TDeclaration) End If Dim lastReadOnly = members.OfType(Of FieldDeclarationSyntax)(). Where(Function(f) f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)). LastOrDefault() Dim lastNormal = members.OfType(Of FieldDeclarationSyntax)(). Where(Function(f) Not f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) AndAlso Not f.Modifiers.Any(SyntaxKind.ConstKeyword)). LastOrDefault() Dim result = If(fieldDeclaration.Modifiers.Any(SyntaxKind.ReadOnlyKeyword), If(lastReadOnly, If(lastNormal, lastConst)), If(lastNormal, If(lastReadOnly, lastConst))) Return DirectCast(DirectCast(result, Object), TDeclaration) End Function Friend Function AddFieldTo(destination As CompilationUnitSyntax, field As IFieldSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean)) As CompilationUnitSyntax Dim fieldDeclaration = GenerateFieldDeclaration(field, CodeGenerationDestination.CompilationUnit, options) Dim members = Insert(destination.Members, fieldDeclaration, options, availableIndices, after:=Function(m) LastField(m, fieldDeclaration), before:=AddressOf FirstMember) Return destination.WithMembers(members) End Function Friend Function AddFieldTo(destination As TypeBlockSyntax, field As IFieldSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean)) As TypeBlockSyntax Dim fieldDeclaration = GenerateFieldDeclaration(field, GetDestination(destination), options) Dim members = Insert(destination.Members, fieldDeclaration, options, availableIndices, after:=Function(m) LastField(m, fieldDeclaration), before:=AddressOf FirstMember) ' Find the best place to put the field. It should go after the last field if we already ' have fields, or at the beginning of the file if we don't. Return FixTerminators(destination.WithMembers(members)) End Function Public Function GenerateFieldDeclaration(field As IFieldSymbol, destination As CodeGenerationDestination, options As CodeGenerationOptions) As FieldDeclarationSyntax Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of ModifiedIdentifierSyntax)(field, options) If reusableSyntax IsNot Nothing Then Dim variableDeclarator = TryCast(reusableSyntax.Parent, VariableDeclaratorSyntax) If variableDeclarator IsNot Nothing Then Dim names = (New SeparatedSyntaxList(Of ModifiedIdentifierSyntax)).Add(reusableSyntax) Dim newVariableDeclarator = variableDeclarator.WithNames(names) Dim fieldDecl = TryCast(variableDeclarator.Parent, FieldDeclarationSyntax) If fieldDecl IsNot Nothing Then Return fieldDecl.WithDeclarators((New SeparatedSyntaxList(Of VariableDeclaratorSyntax)).Add(newVariableDeclarator)) End If End If End If Dim initializerNode = TryCast(CodeGenerationFieldInfo.GetInitializer(field), ExpressionSyntax) Dim initializer = If(initializerNode IsNot Nothing, SyntaxFactory.EqualsValue(initializerNode), GenerateEqualsValue(field)) Dim fieldDeclaration = SyntaxFactory.FieldDeclaration( AttributeGenerator.GenerateAttributeBlocks(field.GetAttributes(), options), GenerateModifiers(field, destination, options), SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( SyntaxFactory.SingletonSeparatedList(field.Name.ToModifiedIdentifier), SyntaxFactory.SimpleAsClause(field.Type.GenerateTypeSyntax()), initializer))) Return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(EnsureLastElasticTrivia(fieldDeclaration), field, options)) End Function Private Function GenerateEqualsValue(field As IFieldSymbol) As EqualsValueSyntax If field.HasConstantValue Then Dim canUseFieldReference = field.Type IsNot Nothing AndAlso Not field.Type.Equals(field.ContainingType) Return SyntaxFactory.EqualsValue(ExpressionGenerator.GenerateExpression(field.Type, field.ConstantValue, canUseFieldReference)) End If Return Nothing End Function Private Function GenerateModifiers(field As IFieldSymbol, destination As CodeGenerationDestination, options As CodeGenerationOptions) As SyntaxTokenList Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens) AddAccessibilityModifiers(field.DeclaredAccessibility, tokens, destination, options, Accessibility.Private) If field.IsConst Then tokens.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) Else If field.IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword)) End If If field.IsReadOnly Then tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)) End If If CodeGenerationFieldInfo.GetIsWithEvents(field) Then tokens.Add(SyntaxFactory.Token(SyntaxKind.WithEventsKeyword)) End If If tokens.Count = 0 Then tokens.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If End If Return SyntaxFactory.TokenList(tokens) End Using End Function End Module End Namespace
' 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. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Module FieldGenerator Private Function LastField(Of TDeclaration As SyntaxNode)( members As SyntaxList(Of TDeclaration), fieldDeclaration As FieldDeclarationSyntax) As TDeclaration Dim lastConst = members.OfType(Of FieldDeclarationSyntax). Where(Function(f) f.Modifiers.Any(SyntaxKind.ConstKeyword)). LastOrDefault() ' Place a const after the last existing const. If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then Return DirectCast(DirectCast(lastConst, Object), TDeclaration) End If Dim lastReadOnly = members.OfType(Of FieldDeclarationSyntax)(). Where(Function(f) f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)). LastOrDefault() Dim lastNormal = members.OfType(Of FieldDeclarationSyntax)(). Where(Function(f) Not f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) AndAlso Not f.Modifiers.Any(SyntaxKind.ConstKeyword)). LastOrDefault() Dim result = If(fieldDeclaration.Modifiers.Any(SyntaxKind.ReadOnlyKeyword), If(lastReadOnly, If(lastNormal, lastConst)), If(lastNormal, If(lastReadOnly, lastConst))) Return DirectCast(DirectCast(result, Object), TDeclaration) End Function Friend Function AddFieldTo(destination As CompilationUnitSyntax, field As IFieldSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean)) As CompilationUnitSyntax Dim fieldDeclaration = GenerateFieldDeclaration(field, CodeGenerationDestination.CompilationUnit, options) Dim members = Insert(destination.Members, fieldDeclaration, options, availableIndices, after:=Function(m) LastField(m, fieldDeclaration), before:=AddressOf FirstMember) Return destination.WithMembers(members) End Function Friend Function AddFieldTo(destination As TypeBlockSyntax, field As IFieldSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean)) As TypeBlockSyntax Dim fieldDeclaration = GenerateFieldDeclaration(field, GetDestination(destination), options) Dim members = Insert(destination.Members, fieldDeclaration, options, availableIndices, after:=Function(m) LastField(m, fieldDeclaration), before:=AddressOf FirstMember) ' Find the best place to put the field. It should go after the last field if we already ' have fields, or at the beginning of the file if we don't. Return FixTerminators(destination.WithMembers(members)) End Function Public Function GenerateFieldDeclaration(field As IFieldSymbol, destination As CodeGenerationDestination, options As CodeGenerationOptions) As FieldDeclarationSyntax Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of ModifiedIdentifierSyntax)(field, options) If reusableSyntax IsNot Nothing Then Dim variableDeclarator = TryCast(reusableSyntax.Parent, VariableDeclaratorSyntax) If variableDeclarator IsNot Nothing Then Dim names = (New SeparatedSyntaxList(Of ModifiedIdentifierSyntax)).Add(reusableSyntax) Dim newVariableDeclarator = variableDeclarator.WithNames(names) Dim fieldDecl = TryCast(variableDeclarator.Parent, FieldDeclarationSyntax) If fieldDecl IsNot Nothing Then Return fieldDecl.WithDeclarators((New SeparatedSyntaxList(Of VariableDeclaratorSyntax)).Add(newVariableDeclarator)) End If End If End If Dim initializerNode = TryCast(CodeGenerationFieldInfo.GetInitializer(field), ExpressionSyntax) Dim initializer = If(initializerNode IsNot Nothing, SyntaxFactory.EqualsValue(initializerNode), GenerateEqualsValue(field)) Dim fieldDeclaration = SyntaxFactory.FieldDeclaration( AttributeGenerator.GenerateAttributeBlocks(field.GetAttributes(), options), GenerateModifiers(field, destination, options), SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( SyntaxFactory.SingletonSeparatedList(field.Name.ToModifiedIdentifier), SyntaxFactory.SimpleAsClause(field.Type.GenerateTypeSyntax()), initializer))) Return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(EnsureLastElasticTrivia(fieldDeclaration), field, options)) End Function Private Function GenerateEqualsValue(field As IFieldSymbol) As EqualsValueSyntax If field.HasConstantValue Then Dim canUseFieldReference = field.Type IsNot Nothing AndAlso Not field.Type.Equals(field.ContainingType) Return SyntaxFactory.EqualsValue(ExpressionGenerator.GenerateExpression(field.Type, field.ConstantValue, canUseFieldReference)) End If Return Nothing End Function Private Function GenerateModifiers(field As IFieldSymbol, destination As CodeGenerationDestination, options As CodeGenerationOptions) As SyntaxTokenList Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens) AddAccessibilityModifiers(field.DeclaredAccessibility, tokens, destination, options, Accessibility.Private) If field.IsConst Then tokens.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) Else If field.IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword)) End If If field.IsReadOnly Then tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)) End If If CodeGenerationFieldInfo.GetIsWithEvents(field) Then tokens.Add(SyntaxFactory.Token(SyntaxKind.WithEventsKeyword)) End If If tokens.Count = 0 Then tokens.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword)) End If End If Return SyntaxFactory.TokenList(tokens) End Using End Function End Module End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/CSharp/Portable/Structure/Providers/IndexerDeclarationStructureProvider.cs
// 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 System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class IndexerDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<IndexerDeclarationSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, IndexerDeclarationSyntax indexerDeclaration, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CSharpStructureHelpers.CollectCommentBlockSpans(indexerDeclaration, ref spans, optionProvider); // fault tolerance if (indexerDeclaration.AccessorList == null || indexerDeclaration.AccessorList.IsMissing || indexerDeclaration.AccessorList.OpenBraceToken.IsMissing || indexerDeclaration.AccessorList.CloseBraceToken.IsMissing) { return; } SyntaxNodeOrToken current = indexerDeclaration; var nextSibling = current.GetNextSibling(); // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Indexers are grouped together with properties in Metadata as Source. var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.IndexerDeclaration) || nextSibling.IsKind(SyntaxKind.PropertyDeclaration)); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( indexerDeclaration, indexerDeclaration.ParameterList.GetLastToken(includeZeroWidth: true), compressEmptyLines: compressEmptyLines, autoCollapse: true, type: BlockTypes.Member, isCollapsible: true)); } } }
// 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 System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class IndexerDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<IndexerDeclarationSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, IndexerDeclarationSyntax indexerDeclaration, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CSharpStructureHelpers.CollectCommentBlockSpans(indexerDeclaration, ref spans, optionProvider); // fault tolerance if (indexerDeclaration.AccessorList == null || indexerDeclaration.AccessorList.IsMissing || indexerDeclaration.AccessorList.OpenBraceToken.IsMissing || indexerDeclaration.AccessorList.CloseBraceToken.IsMissing) { return; } SyntaxNodeOrToken current = indexerDeclaration; var nextSibling = current.GetNextSibling(); // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Indexers are grouped together with properties in Metadata as Source. var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.IndexerDeclaration) || nextSibling.IsKind(SyntaxKind.PropertyDeclaration)); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( indexerDeclaration, indexerDeclaration.ParameterList.GetLastToken(includeZeroWidth: true), compressEmptyLines: compressEmptyLines, autoCollapse: true, type: BlockTypes.Member, isCollapsible: true)); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Core/Portable/Emit/ErrorType.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using System.Reflection.Metadata; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Error type symbols should be replaced with an object of this class /// in the translation layer for emit. /// </summary> internal class ErrorType : Cci.INamespaceTypeReference { public static readonly ErrorType Singleton = new ErrorType(); /// <summary> /// For the name we will use a word "Error" followed by a guid, generated on the spot. /// </summary> private static readonly string s_name = "Error" + Guid.NewGuid().ToString("B"); Cci.IUnitReference Cci.INamespaceTypeReference.GetUnit(EmitContext context) { return ErrorAssembly.Singleton; } string Cci.INamespaceTypeReference.NamespaceName { get { return ""; } } ushort Cci.INamedTypeReference.GenericParameterCount { get { return 0; } } bool Cci.INamedTypeReference.MangleName { get { return false; } } bool Cci.ITypeReference.IsEnum { get { return false; } } bool Cci.ITypeReference.IsValueType { get { return false; } } Cci.ITypeDefinition Cci.ITypeReference.GetResolvedType(EmitContext context) { return null; } Cci.PrimitiveTypeCode Cci.ITypeReference.TypeCode { get { return Cci.PrimitiveTypeCode.NotPrimitive; } } TypeDefinitionHandle Cci.ITypeReference.TypeDef { get { return default(TypeDefinitionHandle); } } Cci.IGenericMethodParameterReference Cci.ITypeReference.AsGenericMethodParameterReference { get { return null; } } Cci.IGenericTypeInstanceReference Cci.ITypeReference.AsGenericTypeInstanceReference { get { return null; } } Cci.IGenericTypeParameterReference Cci.ITypeReference.AsGenericTypeParameterReference { get { return null; } } Cci.INamespaceTypeDefinition Cci.ITypeReference.AsNamespaceTypeDefinition(EmitContext context) { return null; } Cci.INamespaceTypeReference Cci.ITypeReference.AsNamespaceTypeReference { get { return this; } } Cci.INestedTypeDefinition Cci.ITypeReference.AsNestedTypeDefinition(EmitContext context) { return null; } Cci.INestedTypeReference Cci.ITypeReference.AsNestedTypeReference { get { return null; } } Cci.ISpecializedNestedTypeReference Cci.ITypeReference.AsSpecializedNestedTypeReference { get { return null; } } Cci.ITypeDefinition Cci.ITypeReference.AsTypeDefinition(EmitContext context) { return null; } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.INamespaceTypeReference)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return null; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name { get { return s_name; } } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } /// <summary> /// A fake containing assembly for an ErrorType object. /// </summary> private sealed class ErrorAssembly : Cci.IAssemblyReference { public static readonly ErrorAssembly Singleton = new ErrorAssembly(); /// <summary> /// For the name we will use a word "Error" followed by a guid, generated on the spot. /// </summary> private static readonly AssemblyIdentity s_identity = new AssemblyIdentity( name: "Error" + Guid.NewGuid().ToString("B"), version: AssemblyIdentity.NullVersion, cultureName: "", publicKeyOrToken: ImmutableArray<byte>.Empty, hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.Default); AssemblyIdentity Cci.IAssemblyReference.Identity => s_identity; Version Cci.IAssemblyReference.AssemblyVersionPattern => null; Cci.IAssemblyReference Cci.IModuleReference.GetContainingAssembly(EmitContext context) { return this; } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IAssemblyReference)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return null; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name => s_identity.Name; } } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using System.Reflection.Metadata; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Error type symbols should be replaced with an object of this class /// in the translation layer for emit. /// </summary> internal class ErrorType : Cci.INamespaceTypeReference { public static readonly ErrorType Singleton = new ErrorType(); /// <summary> /// For the name we will use a word "Error" followed by a guid, generated on the spot. /// </summary> private static readonly string s_name = "Error" + Guid.NewGuid().ToString("B"); Cci.IUnitReference Cci.INamespaceTypeReference.GetUnit(EmitContext context) { return ErrorAssembly.Singleton; } string Cci.INamespaceTypeReference.NamespaceName { get { return ""; } } ushort Cci.INamedTypeReference.GenericParameterCount { get { return 0; } } bool Cci.INamedTypeReference.MangleName { get { return false; } } bool Cci.ITypeReference.IsEnum { get { return false; } } bool Cci.ITypeReference.IsValueType { get { return false; } } Cci.ITypeDefinition Cci.ITypeReference.GetResolvedType(EmitContext context) { return null; } Cci.PrimitiveTypeCode Cci.ITypeReference.TypeCode { get { return Cci.PrimitiveTypeCode.NotPrimitive; } } TypeDefinitionHandle Cci.ITypeReference.TypeDef { get { return default(TypeDefinitionHandle); } } Cci.IGenericMethodParameterReference Cci.ITypeReference.AsGenericMethodParameterReference { get { return null; } } Cci.IGenericTypeInstanceReference Cci.ITypeReference.AsGenericTypeInstanceReference { get { return null; } } Cci.IGenericTypeParameterReference Cci.ITypeReference.AsGenericTypeParameterReference { get { return null; } } Cci.INamespaceTypeDefinition Cci.ITypeReference.AsNamespaceTypeDefinition(EmitContext context) { return null; } Cci.INamespaceTypeReference Cci.ITypeReference.AsNamespaceTypeReference { get { return this; } } Cci.INestedTypeDefinition Cci.ITypeReference.AsNestedTypeDefinition(EmitContext context) { return null; } Cci.INestedTypeReference Cci.ITypeReference.AsNestedTypeReference { get { return null; } } Cci.ISpecializedNestedTypeReference Cci.ITypeReference.AsSpecializedNestedTypeReference { get { return null; } } Cci.ITypeDefinition Cci.ITypeReference.AsTypeDefinition(EmitContext context) { return null; } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.INamespaceTypeReference)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return null; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name { get { return s_name; } } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } /// <summary> /// A fake containing assembly for an ErrorType object. /// </summary> private sealed class ErrorAssembly : Cci.IAssemblyReference { public static readonly ErrorAssembly Singleton = new ErrorAssembly(); /// <summary> /// For the name we will use a word "Error" followed by a guid, generated on the spot. /// </summary> private static readonly AssemblyIdentity s_identity = new AssemblyIdentity( name: "Error" + Guid.NewGuid().ToString("B"), version: AssemblyIdentity.NullVersion, cultureName: "", publicKeyOrToken: ImmutableArray<byte>.Empty, hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.Default); AssemblyIdentity Cci.IAssemblyReference.Identity => s_identity; Version Cci.IAssemblyReference.AssemblyVersionPattern => null; Cci.IAssemblyReference Cci.IModuleReference.GetContainingAssembly(EmitContext context) { return this; } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IAssemblyReference)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return null; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name => s_identity.Name; } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService.cs
// 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. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.IntroduceVariable; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable { [ExportLanguageService(typeof(IIntroduceVariableService), LanguageNames.CSharp), Shared] internal partial class CSharpIntroduceVariableService : AbstractIntroduceVariableService<CSharpIntroduceVariableService, ExpressionSyntax, TypeSyntax, TypeDeclarationSyntax, QueryExpressionSyntax, NameSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpIntroduceVariableService() { } protected override bool IsInNonFirstQueryClause(ExpressionSyntax expression) { var query = expression.GetAncestor<QueryExpressionSyntax>(); if (query != null) { // Can't introduce for the first clause in a query. var fromClause = expression.GetAncestor<FromClauseSyntax>(); if (fromClause == null || query.FromClause != fromClause) { return true; } } return false; } protected override bool IsInFieldInitializer(ExpressionSyntax expression) { return expression.GetAncestorOrThis<VariableDeclaratorSyntax>() .GetAncestorOrThis<FieldDeclarationSyntax>() != null; } protected override bool IsInParameterInitializer(ExpressionSyntax expression) => expression.GetAncestorOrThis<EqualsValueClauseSyntax>().IsParentKind(SyntaxKind.Parameter); protected override bool IsInConstructorInitializer(ExpressionSyntax expression) => expression.GetAncestorOrThis<ConstructorInitializerSyntax>() != null; protected override bool IsInAutoPropertyInitializer(ExpressionSyntax expression) => expression.GetAncestorOrThis<EqualsValueClauseSyntax>().IsParentKind(SyntaxKind.PropertyDeclaration); protected override bool IsInExpressionBodiedMember(ExpressionSyntax expression) { // walk up until we find a nearest enclosing block or arrow expression. for (SyntaxNode node = expression; node != null; node = node.Parent) { // If we are in an expression bodied member and if the expression has a block body, then, // act as if we're in a block context and not in an expression body context at all. if (node.IsKind(SyntaxKind.Block)) { return false; } else if (node.IsKind(SyntaxKind.ArrowExpressionClause)) { return true; } } return false; } protected override bool IsInAttributeArgumentInitializer(ExpressionSyntax expression) { // Don't call the base here. We want to let the user extract a constant if they've // said "Goo(a = 10)" var attributeArgument = expression.GetAncestorOrThis<AttributeArgumentSyntax>(); if (attributeArgument != null) { // Can't extract an attribute initializer if it contains an array initializer of any // sort. Also, we can't extract if there's any typeof expression within it. if (!expression.DepthFirstTraversal().Any(n => n.RawKind == (int)SyntaxKind.ArrayCreationExpression) && !expression.DepthFirstTraversal().Any(n => n.RawKind == (int)SyntaxKind.TypeOfExpression)) { var attributeDecl = attributeArgument.GetAncestorOrThis<AttributeListSyntax>(); // Also can't extract an attribute initializer if the attribute is a global one. if (!attributeDecl.IsParentKind(SyntaxKind.CompilationUnit)) { return true; } } } return false; } /// <summary> /// Checks for conditions where we should not generate a variable for an expression /// </summary> protected override bool CanIntroduceVariableFor(ExpressionSyntax expression) { // (a) If that's the only expression in a statement. // Otherwise we'll end up with something like "v;" which is not legal in C#. if (expression.WalkUpParentheses().IsParentKind(SyntaxKind.ExpressionStatement)) { return false; } // (b) For Null Literals, as AllOccurrences could introduce semantic errors. if (expression.IsKind(SyntaxKind.NullLiteralExpression)) { return false; } // (c) For throw expressions. if (expression.IsKind(SyntaxKind.ThrowExpression)) { return false; } return true; } protected override IEnumerable<SyntaxNode> GetContainingExecutableBlocks(ExpressionSyntax expression) => expression.GetAncestorsOrThis<BlockSyntax>(); protected override IList<bool> GetInsertionIndices(TypeDeclarationSyntax destination, CancellationToken cancellationToken) => destination.GetInsertionIndices(cancellationToken); protected override bool CanReplace(ExpressionSyntax expression) => true; protected override bool IsExpressionInStaticLocalFunction(ExpressionSyntax expression) { var localFunction = expression.GetAncestor<LocalFunctionStatementSyntax>(); return localFunction != null && localFunction.Modifiers.Any(SyntaxKind.StaticKeyword); } protected override TNode RewriteCore<TNode>( TNode node, SyntaxNode replacementNode, ISet<ExpressionSyntax> matches) { return (TNode)Rewriter.Visit(node, replacementNode, matches); } } }
// 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. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.IntroduceVariable; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable { [ExportLanguageService(typeof(IIntroduceVariableService), LanguageNames.CSharp), Shared] internal partial class CSharpIntroduceVariableService : AbstractIntroduceVariableService<CSharpIntroduceVariableService, ExpressionSyntax, TypeSyntax, TypeDeclarationSyntax, QueryExpressionSyntax, NameSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpIntroduceVariableService() { } protected override bool IsInNonFirstQueryClause(ExpressionSyntax expression) { var query = expression.GetAncestor<QueryExpressionSyntax>(); if (query != null) { // Can't introduce for the first clause in a query. var fromClause = expression.GetAncestor<FromClauseSyntax>(); if (fromClause == null || query.FromClause != fromClause) { return true; } } return false; } protected override bool IsInFieldInitializer(ExpressionSyntax expression) { return expression.GetAncestorOrThis<VariableDeclaratorSyntax>() .GetAncestorOrThis<FieldDeclarationSyntax>() != null; } protected override bool IsInParameterInitializer(ExpressionSyntax expression) => expression.GetAncestorOrThis<EqualsValueClauseSyntax>().IsParentKind(SyntaxKind.Parameter); protected override bool IsInConstructorInitializer(ExpressionSyntax expression) => expression.GetAncestorOrThis<ConstructorInitializerSyntax>() != null; protected override bool IsInAutoPropertyInitializer(ExpressionSyntax expression) => expression.GetAncestorOrThis<EqualsValueClauseSyntax>().IsParentKind(SyntaxKind.PropertyDeclaration); protected override bool IsInExpressionBodiedMember(ExpressionSyntax expression) { // walk up until we find a nearest enclosing block or arrow expression. for (SyntaxNode node = expression; node != null; node = node.Parent) { // If we are in an expression bodied member and if the expression has a block body, then, // act as if we're in a block context and not in an expression body context at all. if (node.IsKind(SyntaxKind.Block)) { return false; } else if (node.IsKind(SyntaxKind.ArrowExpressionClause)) { return true; } } return false; } protected override bool IsInAttributeArgumentInitializer(ExpressionSyntax expression) { // Don't call the base here. We want to let the user extract a constant if they've // said "Goo(a = 10)" var attributeArgument = expression.GetAncestorOrThis<AttributeArgumentSyntax>(); if (attributeArgument != null) { // Can't extract an attribute initializer if it contains an array initializer of any // sort. Also, we can't extract if there's any typeof expression within it. if (!expression.DepthFirstTraversal().Any(n => n.RawKind == (int)SyntaxKind.ArrayCreationExpression) && !expression.DepthFirstTraversal().Any(n => n.RawKind == (int)SyntaxKind.TypeOfExpression)) { var attributeDecl = attributeArgument.GetAncestorOrThis<AttributeListSyntax>(); // Also can't extract an attribute initializer if the attribute is a global one. if (!attributeDecl.IsParentKind(SyntaxKind.CompilationUnit)) { return true; } } } return false; } /// <summary> /// Checks for conditions where we should not generate a variable for an expression /// </summary> protected override bool CanIntroduceVariableFor(ExpressionSyntax expression) { // (a) If that's the only expression in a statement. // Otherwise we'll end up with something like "v;" which is not legal in C#. if (expression.WalkUpParentheses().IsParentKind(SyntaxKind.ExpressionStatement)) { return false; } // (b) For Null Literals, as AllOccurrences could introduce semantic errors. if (expression.IsKind(SyntaxKind.NullLiteralExpression)) { return false; } // (c) For throw expressions. if (expression.IsKind(SyntaxKind.ThrowExpression)) { return false; } return true; } protected override IEnumerable<SyntaxNode> GetContainingExecutableBlocks(ExpressionSyntax expression) => expression.GetAncestorsOrThis<BlockSyntax>(); protected override IList<bool> GetInsertionIndices(TypeDeclarationSyntax destination, CancellationToken cancellationToken) => destination.GetInsertionIndices(cancellationToken); protected override bool CanReplace(ExpressionSyntax expression) => true; protected override bool IsExpressionInStaticLocalFunction(ExpressionSyntax expression) { var localFunction = expression.GetAncestor<LocalFunctionStatementSyntax>(); return localFunction != null && localFunction.Modifiers.Any(SyntaxKind.StaticKeyword); } protected override TNode RewriteCore<TNode>( TNode node, SyntaxNode replacementNode, ISet<ExpressionSyntax> matches) { return (TNode)Rewriter.Visit(node, replacementNode, matches); } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/Core/Portable/Diagnostic/ReportDiagnostic.cs
// 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. namespace Microsoft.CodeAnalysis { /// <summary> /// Describes how to report a warning diagnostic. /// </summary> public enum ReportDiagnostic { /// <summary> /// Report a diagnostic by default. /// </summary> Default = 0, /// <summary> /// Report a diagnostic as an error. /// </summary> Error = 1, /// <summary> /// Report a diagnostic as a warning even though /warnaserror is specified. /// </summary> Warn = 2, /// <summary> /// Report a diagnostic as an info. /// </summary> Info = 3, /// <summary> /// Report a diagnostic as hidden. /// </summary> Hidden = 4, /// <summary> /// Suppress a diagnostic. /// </summary> Suppress = 5, } }
// 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. namespace Microsoft.CodeAnalysis { /// <summary> /// Describes how to report a warning diagnostic. /// </summary> public enum ReportDiagnostic { /// <summary> /// Report a diagnostic by default. /// </summary> Default = 0, /// <summary> /// Report a diagnostic as an error. /// </summary> Error = 1, /// <summary> /// Report a diagnostic as a warning even though /warnaserror is specified. /// </summary> Warn = 2, /// <summary> /// Report a diagnostic as an info. /// </summary> Info = 3, /// <summary> /// Report a diagnostic as hidden. /// </summary> Hidden = 4, /// <summary> /// Suppress a diagnostic. /// </summary> Suppress = 5, } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Features/CSharp/Portable/ConvertNumericLiteral/CSharpConvertNumericLiteralCodeRefactoringProvider.cs
// 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. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertNumericLiteral; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertNumericLiteral { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertNumericLiteral), Shared] internal sealed class CSharpConvertNumericLiteralCodeRefactoringProvider : AbstractConvertNumericLiteralCodeRefactoringProvider<LiteralExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertNumericLiteralCodeRefactoringProvider() { } protected override (string hexPrefix, string binaryPrefix) GetNumericLiteralPrefixes() => (hexPrefix: "0x", binaryPrefix: "0b"); } }
// 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. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertNumericLiteral; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertNumericLiteral { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertNumericLiteral), Shared] internal sealed class CSharpConvertNumericLiteralCodeRefactoringProvider : AbstractConvertNumericLiteralCodeRefactoringProvider<LiteralExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertNumericLiteralCodeRefactoringProvider() { } protected override (string hexPrefix, string binaryPrefix) GetNumericLiteralPrefixes() => (hexPrefix: "0x", binaryPrefix: "0b"); } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationDestructorSymbol.cs
// 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. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationDestructorSymbol : CodeGenerationMethodSymbol { public CodeGenerationDestructorSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes) : base(containingType, attributes, Accessibility.NotApplicable, default, returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: string.Empty, typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters: ImmutableArray<IParameterSymbol>.Empty, returnTypeAttributes: ImmutableArray<AttributeData>.Empty) { } public override MethodKind MethodKind => MethodKind.Destructor; protected override CodeGenerationSymbol Clone() { var result = new CodeGenerationDestructorSymbol(this.ContainingType, this.GetAttributes()); CodeGenerationDestructorInfo.Attach(result, CodeGenerationDestructorInfo.GetTypeName(this), CodeGenerationDestructorInfo.GetStatements(this)); return result; } } }
// 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. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationDestructorSymbol : CodeGenerationMethodSymbol { public CodeGenerationDestructorSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes) : base(containingType, attributes, Accessibility.NotApplicable, default, returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: string.Empty, typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters: ImmutableArray<IParameterSymbol>.Empty, returnTypeAttributes: ImmutableArray<AttributeData>.Empty) { } public override MethodKind MethodKind => MethodKind.Destructor; protected override CodeGenerationSymbol Clone() { var result = new CodeGenerationDestructorSymbol(this.ContainingType, this.GetAttributes()); CodeGenerationDestructorInfo.Attach(result, CodeGenerationDestructorInfo.GetTypeName(this), CodeGenerationDestructorInfo.GetStatements(this)); return result; } } }
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/AbstractRegionDataFlowPass.vb
' 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. Imports System Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ' Note: this code has a copy-and-paste sibling in AbstractRegionControlFlowPass. ' Any fix to one should be applied to the other. Friend MustInherit Class AbstractRegionDataFlowPass Inherits DataFlowPass Friend Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, Optional initiallyAssignedVariables As HashSet(Of Symbol) = Nothing, Optional trackUnassignments As Boolean = False, Optional trackStructsWithIntrinsicTypedFields As Boolean = False) MyBase.New(info, region, False, initiallyAssignedVariables, trackUnassignments, trackStructsWithIntrinsicTypedFields) End Sub Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode MakeSlots(node.LambdaSymbol.Parameters) Dim result = MyBase.VisitLambda(node) Return result End Function Private Sub MakeSlots(parameters As ImmutableArray(Of ParameterSymbol)) For Each parameter In parameters GetOrCreateSlot(parameter) Next End Sub Protected Overrides ReadOnly Property SuppressRedimOperandRvalueOnPreserve As Boolean Get Return False End Get End Property Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode If node.ParameterSymbol.ContainingSymbol.IsQueryLambdaMethod Then Return Nothing End If Return MyBase.VisitParameter(node) End Function Protected Overrides Function CreateLocalSymbolForVariables(declarations As ImmutableArray(Of BoundLocalDeclaration)) As LocalSymbol If declarations.Length = 1 Then Return declarations(0).LocalSymbol End If Dim locals(declarations.Length - 1) As LocalSymbol For i = 0 To declarations.Length - 1 locals(i) = declarations(i).LocalSymbol Next Return AmbiguousLocalsPseudoSymbol.Create(locals.AsImmutableOrNull()) End Function Protected Overrides ReadOnly Property IgnoreOutSemantics As Boolean Get Return False End Get End Property Protected Overrides ReadOnly Property EnableBreakingFlowAnalysisFeatures As Boolean Get Return True End Get End Property End Class End Namespace
' 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. Imports System Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ' Note: this code has a copy-and-paste sibling in AbstractRegionControlFlowPass. ' Any fix to one should be applied to the other. Friend MustInherit Class AbstractRegionDataFlowPass Inherits DataFlowPass Friend Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, Optional initiallyAssignedVariables As HashSet(Of Symbol) = Nothing, Optional trackUnassignments As Boolean = False, Optional trackStructsWithIntrinsicTypedFields As Boolean = False) MyBase.New(info, region, False, initiallyAssignedVariables, trackUnassignments, trackStructsWithIntrinsicTypedFields) End Sub Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode MakeSlots(node.LambdaSymbol.Parameters) Dim result = MyBase.VisitLambda(node) Return result End Function Private Sub MakeSlots(parameters As ImmutableArray(Of ParameterSymbol)) For Each parameter In parameters GetOrCreateSlot(parameter) Next End Sub Protected Overrides ReadOnly Property SuppressRedimOperandRvalueOnPreserve As Boolean Get Return False End Get End Property Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode If node.ParameterSymbol.ContainingSymbol.IsQueryLambdaMethod Then Return Nothing End If Return MyBase.VisitParameter(node) End Function Protected Overrides Function CreateLocalSymbolForVariables(declarations As ImmutableArray(Of BoundLocalDeclaration)) As LocalSymbol If declarations.Length = 1 Then Return declarations(0).LocalSymbol End If Dim locals(declarations.Length - 1) As LocalSymbol For i = 0 To declarations.Length - 1 locals(i) = declarations(i).LocalSymbol Next Return AmbiguousLocalsPseudoSymbol.Create(locals.AsImmutableOrNull()) End Function Protected Overrides ReadOnly Property IgnoreOutSemantics As Boolean Get Return False End Get End Property Protected Overrides ReadOnly Property EnableBreakingFlowAnalysisFeatures As Boolean Get Return True End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,224
EnC - Tests for lambda improvements
C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
davidwengier
2021-07-29T11:36:37Z
2021-08-30T20:11:14Z
8de6661fc91b8c6c93d1c506ca573e8180bae139
3fdd28bc26238f717ec1124efc7e1f9c2158bce2
EnC - Tests for lambda improvements. C# 10 Lambda improvements: * Attributes: added editing and metadata tests * Explicit return types: added editing test * Natural type: N/A (and I used it in one of the tests just in case anyway) /cc @cston in case I missed any improvements or important scenarios.
./src/EditorFeatures/TestUtilities/StubVsEditorAdaptersFactoryService.cs
// 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. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; using IServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [Export(typeof(IVsEditorAdaptersFactoryService))] [PartNotDiscoverable] internal class StubVsEditorAdaptersFactoryService : IVsEditorAdaptersFactoryService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StubVsEditorAdaptersFactoryService() { } public IVsCodeWindow CreateVsCodeWindowAdapter(IServiceProvider serviceProvider) => throw new NotImplementedException(); public IVsTextBuffer CreateVsTextBufferAdapter(IServiceProvider serviceProvider) => throw new NotImplementedException(); public IVsTextBuffer CreateVsTextBufferAdapter(IServiceProvider serviceProvider, IContentType contentType) => throw new NotImplementedException(); public IVsTextBuffer CreateVsTextBufferAdapterForSecondaryBuffer(IServiceProvider serviceProvider, ITextBuffer secondaryBuffer) => throw new NotImplementedException(); public IVsTextBufferCoordinator CreateVsTextBufferCoordinatorAdapter() => throw new NotImplementedException(); public IVsTextView CreateVsTextViewAdapter(IServiceProvider serviceProvider) => throw new NotImplementedException(); public IVsTextView CreateVsTextViewAdapter(IServiceProvider serviceProvider, ITextViewRoleSet roles) => throw new NotImplementedException(); public IVsTextBuffer GetBufferAdapter(ITextBuffer textBuffer) => throw new NotImplementedException(); public ITextBuffer GetDataBuffer(IVsTextBuffer bufferAdapter) => throw new NotImplementedException(); public ITextBuffer GetDocumentBuffer(IVsTextBuffer bufferAdapter) => throw new NotImplementedException(); public IVsTextView GetViewAdapter(ITextView textView) => throw new NotImplementedException(); public IWpfTextView GetWpfTextView(IVsTextView viewAdapter) => throw new NotImplementedException(); public IWpfTextViewHost GetWpfTextViewHost(IVsTextView viewAdapter) => throw new NotImplementedException(); public void SetDataBuffer(IVsTextBuffer bufferAdapter, ITextBuffer dataBuffer) => throw new NotImplementedException(); } }
// 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. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; using IServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [Export(typeof(IVsEditorAdaptersFactoryService))] [PartNotDiscoverable] internal class StubVsEditorAdaptersFactoryService : IVsEditorAdaptersFactoryService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StubVsEditorAdaptersFactoryService() { } public IVsCodeWindow CreateVsCodeWindowAdapter(IServiceProvider serviceProvider) => throw new NotImplementedException(); public IVsTextBuffer CreateVsTextBufferAdapter(IServiceProvider serviceProvider) => throw new NotImplementedException(); public IVsTextBuffer CreateVsTextBufferAdapter(IServiceProvider serviceProvider, IContentType contentType) => throw new NotImplementedException(); public IVsTextBuffer CreateVsTextBufferAdapterForSecondaryBuffer(IServiceProvider serviceProvider, ITextBuffer secondaryBuffer) => throw new NotImplementedException(); public IVsTextBufferCoordinator CreateVsTextBufferCoordinatorAdapter() => throw new NotImplementedException(); public IVsTextView CreateVsTextViewAdapter(IServiceProvider serviceProvider) => throw new NotImplementedException(); public IVsTextView CreateVsTextViewAdapter(IServiceProvider serviceProvider, ITextViewRoleSet roles) => throw new NotImplementedException(); public IVsTextBuffer GetBufferAdapter(ITextBuffer textBuffer) => throw new NotImplementedException(); public ITextBuffer GetDataBuffer(IVsTextBuffer bufferAdapter) => throw new NotImplementedException(); public ITextBuffer GetDocumentBuffer(IVsTextBuffer bufferAdapter) => throw new NotImplementedException(); public IVsTextView GetViewAdapter(ITextView textView) => throw new NotImplementedException(); public IWpfTextView GetWpfTextView(IVsTextView viewAdapter) => throw new NotImplementedException(); public IWpfTextViewHost GetWpfTextViewHost(IVsTextView viewAdapter) => throw new NotImplementedException(); public void SetDataBuffer(IVsTextBuffer bufferAdapter, ITextBuffer dataBuffer) => throw new NotImplementedException(); } }
-1