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,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpGoToImplementation.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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpGoToImplementation : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpGoToImplementation(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpGoToImplementation)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.GoToImplementation), Trait(Traits.Editor, Traits.Editors.LanguageServerProtocol)] public void SimpleGoToImplementation() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "FileImplementation.cs"); VisualStudio.SolutionExplorer.OpenFile(project, "FileImplementation.cs"); VisualStudio.Editor.SetText( @"class Implementation : IGoo { }"); VisualStudio.SolutionExplorer.AddFile(project, "FileInterface.cs"); VisualStudio.SolutionExplorer.OpenFile(project, "FileInterface.cs"); VisualStudio.Editor.SetText( @"interface IGoo { }"); VisualStudio.Editor.PlaceCaret("interface IGoo"); VisualStudio.Editor.GoToImplementation("FileImplementation.cs"); VisualStudio.Editor.Verify.TextContains(@"class Implementation$$", assertCaretPosition: true); Assert.False(VisualStudio.Shell.IsActiveTabProvisional()); } [WpfFact, Trait(Traits.Feature, Traits.Features.GoToImplementation), Trait(Traits.Editor, Traits.Editors.LanguageServerProtocol)] public void GoToImplementationOpensProvisionalTabIfDocumentNotOpen() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "FileImplementation.cs"); VisualStudio.SolutionExplorer.OpenFile(project, "FileImplementation.cs"); VisualStudio.Editor.SetText( @"class Implementation : IBar { } "); VisualStudio.SolutionExplorer.CloseCodeFile(project, "FileImplementation.cs", saveFile: true); VisualStudio.SolutionExplorer.AddFile(project, "FileInterface.cs"); VisualStudio.SolutionExplorer.OpenFile(project, "FileInterface.cs"); VisualStudio.Editor.SetText( @"interface IBar { }"); VisualStudio.Editor.PlaceCaret("interface IBar"); VisualStudio.Editor.GoToImplementation("FileImplementation.cs"); VisualStudio.Editor.Verify.TextContains(@"class Implementation$$", assertCaretPosition: true); Assert.True(VisualStudio.Shell.IsActiveTabProvisional()); } // TODO: Enable this once the GoToDefinition tests are merged [WpfFact, Trait(Traits.Feature, Traits.Features.GoToImplementation)] public void GoToImplementationFromMetadataAsSource() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "FileImplementation.cs"); VisualStudio.SolutionExplorer.OpenFile(project, "FileImplementation.cs"); VisualStudio.Editor.SetText( @"using System; class Implementation : IDisposable { public void SomeMethod() { IDisposable d; } }"); VisualStudio.Editor.PlaceCaret("IDisposable d", charsOffset: -1); VisualStudio.Editor.GoToDefinition("IDisposable [from metadata]"); VisualStudio.Editor.GoToImplementation("FileImplementation.cs"); VisualStudio.Editor.Verify.TextContains(@"class Implementation$$ : IDisposable", assertCaretPosition: 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpGoToImplementation : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpGoToImplementation(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpGoToImplementation)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.GoToImplementation), Trait(Traits.Editor, Traits.Editors.LanguageServerProtocol)] public void SimpleGoToImplementation() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "FileImplementation.cs"); VisualStudio.SolutionExplorer.OpenFile(project, "FileImplementation.cs"); VisualStudio.Editor.SetText( @"class Implementation : IGoo { }"); VisualStudio.SolutionExplorer.AddFile(project, "FileInterface.cs"); VisualStudio.SolutionExplorer.OpenFile(project, "FileInterface.cs"); VisualStudio.Editor.SetText( @"interface IGoo { }"); VisualStudio.Editor.PlaceCaret("interface IGoo"); VisualStudio.Editor.GoToImplementation("FileImplementation.cs"); VisualStudio.Editor.Verify.TextContains(@"class Implementation$$", assertCaretPosition: true); Assert.False(VisualStudio.Shell.IsActiveTabProvisional()); } [WpfFact, Trait(Traits.Feature, Traits.Features.GoToImplementation), Trait(Traits.Editor, Traits.Editors.LanguageServerProtocol)] public void GoToImplementationOpensProvisionalTabIfDocumentNotOpen() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "FileImplementation.cs"); VisualStudio.SolutionExplorer.OpenFile(project, "FileImplementation.cs"); VisualStudio.Editor.SetText( @"class Implementation : IBar { } "); VisualStudio.SolutionExplorer.CloseCodeFile(project, "FileImplementation.cs", saveFile: true); VisualStudio.SolutionExplorer.AddFile(project, "FileInterface.cs"); VisualStudio.SolutionExplorer.OpenFile(project, "FileInterface.cs"); VisualStudio.Editor.SetText( @"interface IBar { }"); VisualStudio.Editor.PlaceCaret("interface IBar"); VisualStudio.Editor.GoToImplementation("FileImplementation.cs"); VisualStudio.Editor.Verify.TextContains(@"class Implementation$$", assertCaretPosition: true); Assert.True(VisualStudio.Shell.IsActiveTabProvisional()); } // TODO: Enable this once the GoToDefinition tests are merged [WpfFact, Trait(Traits.Feature, Traits.Features.GoToImplementation)] public void GoToImplementationFromMetadataAsSource() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "FileImplementation.cs"); VisualStudio.SolutionExplorer.OpenFile(project, "FileImplementation.cs"); VisualStudio.Editor.SetText( @"using System; class Implementation : IDisposable { public void SomeMethod() { IDisposable d; } }"); VisualStudio.Editor.PlaceCaret("IDisposable d", charsOffset: -1); VisualStudio.Editor.GoToDefinition("IDisposable [from metadata]"); VisualStudio.Editor.GoToImplementation("FileImplementation.cs"); VisualStudio.Editor.Verify.TextContains(@"class Implementation$$ : IDisposable", assertCaretPosition: true); } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests_FixAllTests.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 Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType { public partial class UseExplicitTypeTests { #region "Fix all occurrences tests" [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocumentScope_PreferExplicitTypeEverywhere() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { {|FixAllInDocument:var|} i1 = 0; var p = new Program(); var tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { int i1 = 0; Program2 p = new Program2(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i1 = 0; Program2 p = new Program2(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { int i1 = 0; Program p = new Program(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { int i1 = 0; Program2 p = new Program2(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i1 = 0; Program2 p = new Program2(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: ExplicitTypeEverywhere()); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject_PreferExplicitTypeEverywhere() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { {|FixAllInProject:var|} i1 = 0; var p = new Program(); var tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { var i2 = 0; var p2 = new Program2(); var tuple2 = Tuple.Create(true, 1); return i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i3 = 0; Program2 p3 = new Program2(); Tuple&lt;bool, int&gt; tuple3 = Tuple.Create(true, 1); return i3; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { int i1 = 0; Program p = new Program(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { int i2 = 0; Program2 p2 = new Program2(); Tuple&lt;bool, int&gt; tuple2 = Tuple.Create(true, 1); return i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i3 = 0; Program2 p3 = new Program2(); Tuple&lt;bool, int&gt; tuple3 = Tuple.Create(true, 1); return i3; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: ExplicitTypeEverywhere()); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_PreferExplicitTypeEverywhere() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { {|FixAllInSolution:var|} i1 = 0; var p = new Program(); var tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { var i2 = 0; var p2 = new Program2(); var tuple2 = Tuple.Create(true, 1); return i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { var i3 = 0; var p3 = new Program2(); var tuple3 = Tuple.Create(true, 1); return i3; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { int i1 = 0; Program p = new Program(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { int i2 = 0; Program2 p2 = new Program2(); Tuple&lt;bool, int&gt; tuple2 = Tuple.Create(true, 1); return i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i3 = 0; Program2 p3 = new Program2(); Tuple&lt;bool, int&gt; tuple3 = Tuple.Create(true, 1); return i3; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: ExplicitTypeEverywhere()); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocumentScope_PreferExplicitTypeExceptWhereApparent() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { {|FixAllInDocument:var|} p = this; var i1 = 0; var tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { Program p = this; int i1 = 0; var tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: ExplicitTypeExceptWhereApparent()); } #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.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType { public partial class UseExplicitTypeTests { #region "Fix all occurrences tests" [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocumentScope_PreferExplicitTypeEverywhere() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { {|FixAllInDocument:var|} i1 = 0; var p = new Program(); var tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { int i1 = 0; Program2 p = new Program2(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i1 = 0; Program2 p = new Program2(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { int i1 = 0; Program p = new Program(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { int i1 = 0; Program2 p = new Program2(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i1 = 0; Program2 p = new Program2(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: ExplicitTypeEverywhere()); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject_PreferExplicitTypeEverywhere() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { {|FixAllInProject:var|} i1 = 0; var p = new Program(); var tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { var i2 = 0; var p2 = new Program2(); var tuple2 = Tuple.Create(true, 1); return i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i3 = 0; Program2 p3 = new Program2(); Tuple&lt;bool, int&gt; tuple3 = Tuple.Create(true, 1); return i3; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { int i1 = 0; Program p = new Program(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { int i2 = 0; Program2 p2 = new Program2(); Tuple&lt;bool, int&gt; tuple2 = Tuple.Create(true, 1); return i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i3 = 0; Program2 p3 = new Program2(); Tuple&lt;bool, int&gt; tuple3 = Tuple.Create(true, 1); return i3; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: ExplicitTypeEverywhere()); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_PreferExplicitTypeEverywhere() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { {|FixAllInSolution:var|} i1 = 0; var p = new Program(); var tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { var i2 = 0; var p2 = new Program2(); var tuple2 = Tuple.Create(true, 1); return i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { var i3 = 0; var p3 = new Program2(); var tuple3 = Tuple.Create(true, 1); return i3; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { int i1 = 0; Program p = new Program(); Tuple&lt;bool, int&gt; tuple = Tuple.Create(true, 1); return i1; } } </Document> <Document> using System; class Program2 { static int F(int x, int y) { int i2 = 0; Program2 p2 = new Program2(); Tuple&lt;bool, int&gt; tuple2 = Tuple.Create(true, 1); return i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, int y) { int i3 = 0; Program2 p3 = new Program2(); Tuple&lt;bool, int&gt; tuple3 = Tuple.Create(true, 1); return i3; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: ExplicitTypeEverywhere()); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocumentScope_PreferExplicitTypeExceptWhereApparent() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { {|FixAllInDocument:var|} p = this; var i1 = 0; var tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, int y) { Program p = this; int i1 = 0; var tuple = Tuple.Create(true, 1); return i1; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: ExplicitTypeExceptWhereApparent()); } #endregion } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Features/CSharp/Portable/AliasAmbiguousType/CSharpAliasAmbiguousTypeCodeFixProvider.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 System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.AliasAmbiguousType; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.AliasAmbiguousType { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AliasAmbiguousType), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.FullyQualify)] internal class CSharpAliasAmbiguousTypeCodeFixProvider : AbstractAliasAmbiguousTypeCodeFixProvider { /// <summary> /// 'reference' is an ambiguous reference between 'identifier' and 'identifier' /// </summary> private const string CS0104 = nameof(CS0104); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpAliasAmbiguousTypeCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS0104); protected override string GetTextPreviewOfChange(string alias, ITypeSymbol typeSymbol) => $"using { alias } = { typeSymbol.ToNameDisplayString() };"; } }
// 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 System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.AliasAmbiguousType; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.AliasAmbiguousType { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AliasAmbiguousType), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.FullyQualify)] internal class CSharpAliasAmbiguousTypeCodeFixProvider : AbstractAliasAmbiguousTypeCodeFixProvider { /// <summary> /// 'reference' is an ambiguous reference between 'identifier' and 'identifier' /// </summary> private const string CS0104 = nameof(CS0104); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpAliasAmbiguousTypeCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS0104); protected override string GetTextPreviewOfChange(string alias, ITypeSymbol typeSymbol) => $"using { alias } = { typeSymbol.ToNameDisplayString() };"; } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/VisualStudio/Core/Test.Next/Services/LspDiagnosticsTests.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.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient; using Microsoft.VisualStudio.Threading; using Moq; using Nerdbank.Streams; using Newtonsoft.Json.Linq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using StreamJsonRpc; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Roslyn.VisualStudio.Next.UnitTests.Services { [UseExportProvider] public class LspDiagnosticsTests : AbstractLanguageServerProtocolTests { [Fact] public async Task AddDiagnosticTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create a mock that returns a diagnostic for the document. SetupMockWithDiagnostics(diagnosticsMock, document.Id, await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false)); // Publish one document change diagnostic notification -> // 1. doc1 with id. // // We expect one publish diagnostic notification -> // 1. from doc1 with id. var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 1, document).ConfigureAwait(false); var result = Assert.Single(results); Assert.Equal(new Uri(document.FilePath), result.Uri); Assert.Equal("id", result.Diagnostics.Single().Code); } [Fact] public async Task NoDiagnosticsWhenInPullMode() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; workspace.SetOptions(workspace.Options.WithChangedOption( InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Pull)); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create a mock that returns a diagnostic for the document. SetupMockWithDiagnostics(diagnosticsMock, document.Id, await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false)); var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 0, document).ConfigureAwait(false); Assert.Empty(results); } [Fact] public async Task AddDiagnosticWithMappedFilesTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create two mapped diagnostics for the document. SetupMockWithDiagnostics(diagnosticsMock, document.Id, await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", document.FilePath + "m1"), ("id2", document.FilePath + "m2")).ConfigureAwait(false)); // Publish one document change diagnostic notification -> // 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2. // // We expect two publish diagnostic notifications -> // 1. from m1 with id1 (from 1 above). // 2. from m2 with id2 (from 1 above). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, expectedNumberOfCallbacks: 2, document).ConfigureAwait(false); Assert.Equal(2, results.Count); Assert.Equal(new Uri(document.FilePath + "m1"), results[0].Uri); Assert.Equal("id1", results[0].Diagnostics.Single().Code); Assert.Equal(new Uri(document.FilePath + "m2"), results[1].Uri); Assert.Equal("id2", results[1].Diagnostics.Single().Code); } [Fact] public async Task AddDiagnosticWithMappedFileToManyDocumentsTestAsync() { using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace; var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create diagnostic for the first document that has a mapped location. var mappedFilePath = documents[0].FilePath + "m1"; var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false); // Create diagnostic for the second document that maps to the same location as the first document diagnostic. var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false); SetupMockWithDiagnostics(diagnosticsMock, documents[0].Id, documentOneDiagnostic); SetupMockWithDiagnostics(diagnosticsMock, documents[1].Id, documentTwoDiagnostic); // Publish two document change diagnostic notifications -> // 1. doc1 with doc1Diagnostic = mapped file m1. // 2. doc2 with doc2Diagnostic = mapped file m1. // // We expect two publish diagnostic notifications -> // 1. from m1 with doc1Diagnostic (from 1 above). // 2. from m1 with doc1Diagnostic and doc2Diagnostic (from 2 above adding doc2Diagnostic to m1). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 2, documents[0], documents[1]).ConfigureAwait(false); Assert.Equal(2, results.Count); var expectedUri = new Uri(mappedFilePath); Assert.Equal(expectedUri, results[0].Uri); Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code); Assert.Equal(expectedUri, results[1].Uri); Assert.Equal(2, results[1].Diagnostics.Length); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic"); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic"); } [Fact] public async Task RemoveDiagnosticTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Setup the mock so the first call for a document returns a diagnostic, but the second returns empty. SetupMockDiagnosticSequence(diagnosticsMock, document.Id, await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false), ImmutableArray<DiagnosticData>.Empty); // Publish two document change diagnostic notifications -> // 1. doc1 with id. // 2. doc1 with empty. // // We expect two publish diagnostic notifications -> // 1. from doc1 with id. // 2. from doc1 with empty (from 2 above clearing out diagnostics from doc1). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 2, document, document).ConfigureAwait(false); Assert.Equal(2, results.Count); Assert.Equal(new Uri(document.FilePath), results[0].Uri); Assert.Equal("id", results[0].Diagnostics.Single().Code); Assert.Equal(new Uri(document.FilePath), results[1].Uri); Assert.True(results[1].Diagnostics.IsEmpty()); Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris()); Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics()); } [Fact] public async Task RemoveDiagnosticForMappedFilesTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); var mappedFilePathM1 = document.FilePath + "m1"; var mappedFilePathM2 = document.FilePath + "m2"; // Create two mapped diagnostics for the document on first call. // On the second call, return only the second mapped diagnostic for the document. SetupMockDiagnosticSequence(diagnosticsMock, document.Id, await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", mappedFilePathM1), ("id2", mappedFilePathM2)).ConfigureAwait(false), await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id2", mappedFilePathM2)).ConfigureAwait(false)); // Publish three document change diagnostic notifications -> // 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2. // 2. doc1 with just id2 = mapped file m2. // // We expect four publish diagnostic notifications -> // 1. from m1 with id1 (from 1 above). // 2. from m2 with id2 (from 1 above). // 3. from m1 with empty (from 2 above clearing out diagnostics for m1). // 4. from m2 with id2 (from 2 above clearing out diagnostics for m1). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, document, document).ConfigureAwait(false); var mappedFileURIM1 = new Uri(mappedFilePathM1); var mappedFileURIM2 = new Uri(mappedFilePathM2); Assert.Equal(4, results.Count); // First document update. Assert.Equal(mappedFileURIM1, results[0].Uri); Assert.Equal("id1", results[0].Diagnostics.Single().Code); Assert.Equal(mappedFileURIM2, results[1].Uri); Assert.Equal("id2", results[1].Diagnostics.Single().Code); // Second document update. Assert.Equal(mappedFileURIM1, results[2].Uri); Assert.True(results[2].Diagnostics.IsEmpty()); Assert.Equal(mappedFileURIM2, results[3].Uri); Assert.Equal("id2", results[3].Diagnostics.Single().Code); Assert.Single(testAccessor.GetFileUrisForDocument(document.Id), mappedFileURIM2); Assert.Equal("id2", testAccessor.GetDiagnosticsForUriAndDocument(document.Id, mappedFileURIM2).Single().Code); Assert.Empty(testAccessor.GetDiagnosticsForUriAndDocument(document.Id, mappedFileURIM1)); } [Fact] public async Task RemoveDiagnosticForMappedFileToManyDocumentsTestAsync() { using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace; var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create diagnostic for the first document that has a mapped location. var mappedFilePath = documents[0].FilePath + "m1"; var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false); // Create diagnostic for the second document that maps to the same location as the first document diagnostic. var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false); // On the first call for this document, return the mapped diagnostic. On the second, return nothing. SetupMockDiagnosticSequence(diagnosticsMock, documents[0].Id, documentOneDiagnostic, ImmutableArray<DiagnosticData>.Empty); // Always return the mapped diagnostic for this document. SetupMockWithDiagnostics(diagnosticsMock, documents[1].Id, documentTwoDiagnostic); // Publish three document change diagnostic notifications -> // 1. doc1 with doc1Diagnostic = mapped file path m1 // 2. doc2 with doc2Diagnostic = mapped file path m1 // 3. doc1 with empty. // // We expect three publish diagnostics -> // 1. from m1 with doc1Diagnostic (triggered by 1 above to add doc1Diagnostic). // 2. from m1 with doc1Diagnostic and doc2Diagnostic (triggered by 2 above to add doc2Diagnostic). // 3. from m1 with just doc2Diagnostic (triggered by 3 above to remove doc1Diagnostic). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 3, documents[0], documents[1], documents[0]).ConfigureAwait(false); Assert.Equal(3, results.Count); var expectedUri = new Uri(mappedFilePath); Assert.Equal(expectedUri, results[0].Uri); Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code); Assert.Equal(expectedUri, results[1].Uri); Assert.Equal(2, results[1].Diagnostics.Length); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic"); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic"); Assert.Equal(expectedUri, results[2].Uri); Assert.Equal(1, results[2].Diagnostics.Length); Assert.Contains(results[2].Diagnostics, d => d.Code == "doc2Diagnostic"); Assert.Single(testAccessor.GetFileUrisForDocument(documents[1].Id), expectedUri); Assert.Equal("doc2Diagnostic", testAccessor.GetDiagnosticsForUriAndDocument(documents[1].Id, expectedUri).Single().Code); Assert.Empty(testAccessor.GetDiagnosticsForUriAndDocument(documents[0].Id, expectedUri)); } [Fact] public async Task ClearAllDiagnosticsForMappedFilesTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); var mappedFilePathM1 = document.FilePath + "m1"; var mappedFilePathM2 = document.FilePath + "m2"; // Create two mapped diagnostics for the document on first call. // On the second call, return only empty diagnostics. SetupMockDiagnosticSequence(diagnosticsMock, document.Id, await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", mappedFilePathM1), ("id2", mappedFilePathM2)).ConfigureAwait(false), ImmutableArray<DiagnosticData>.Empty); // Publish two document change diagnostic notifications -> // 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2. // 2. doc1 with empty. // // We expect four publish diagnostic notifications - the first two are the two mapped files from 1. // The second two are the two mapped files being cleared by 2. var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, document, document).ConfigureAwait(false); var mappedFileURIM1 = new Uri(document.FilePath + "m1"); var mappedFileURIM2 = new Uri(document.FilePath + "m2"); Assert.Equal(4, results.Count); // Document's first update. Assert.Equal(mappedFileURIM1, results[0].Uri); Assert.Equal("id1", results[0].Diagnostics.Single().Code); Assert.Equal(mappedFileURIM2, results[1].Uri); Assert.Equal("id2", results[1].Diagnostics.Single().Code); // Document's second update. Assert.Equal(mappedFileURIM1, results[2].Uri); Assert.True(results[2].Diagnostics.IsEmpty()); Assert.Equal(mappedFileURIM2, results[3].Uri); Assert.True(results[3].Diagnostics.IsEmpty()); Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris()); Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics()); } [Fact] public async Task ClearAllDiagnosticsForMappedFileToManyDocumentsTestAsync() { using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace; var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create diagnostic for the first document that has a mapped location. var mappedFilePath = documents[0].FilePath + "m1"; var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false); // Create diagnostic for the second document that maps to the same location as the first document diagnostic. var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false); // On the first call for the documents, return the mapped diagnostic. On the second, return nothing. SetupMockDiagnosticSequence(diagnosticsMock, documents[0].Id, documentOneDiagnostic, ImmutableArray<DiagnosticData>.Empty); SetupMockDiagnosticSequence(diagnosticsMock, documents[1].Id, documentTwoDiagnostic, ImmutableArray<DiagnosticData>.Empty); // Publish four document change diagnostic notifications -> // 1. doc1 with doc1Diagnostic = mapped file m1. // 2. doc2 with doc2Diagnostic = mapped file m1. // 3. doc1 with empty diagnostics. // 4. doc2 with empty diagnostics. // // We expect four publish diagnostics -> // 1. from URI m1 with doc1Diagnostic (triggered by 1 above to add doc1Diagnostic). // 2. from URI m1 with doc1Diagnostic and doc2Diagnostic (triggered by 2 above to add doc2Diagnostic). // 3. from URI m1 with just doc2Diagnostic (triggered by 3 above to clear doc1 diagnostic). // 4. from URI m1 with empty (triggered by 4 above to also clear doc2 diagnostic). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, documents[0], documents[1], documents[0], documents[1]).ConfigureAwait(false); Assert.Equal(4, results.Count); var expectedUri = new Uri(mappedFilePath); Assert.Equal(expectedUri, results[0].Uri); Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code); Assert.Equal(expectedUri, results[1].Uri); Assert.Equal(2, results[1].Diagnostics.Length); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic"); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic"); Assert.Equal(expectedUri, results[2].Uri); Assert.Equal(1, results[2].Diagnostics.Length); Assert.Contains(results[2].Diagnostics, d => d.Code == "doc2Diagnostic"); Assert.Equal(expectedUri, results[3].Uri); Assert.True(results[3].Diagnostics.IsEmpty()); Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris()); Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics()); } private async Task<(VisualStudioInProcLanguageServer.TestAccessor, List<LSP.PublishDiagnosticParams>)> RunPublishDiagnosticsAsync( TestWorkspace workspace, IDiagnosticService diagnosticService, int expectedNumberOfCallbacks, params Document[] documentsToPublish) { var (clientStream, serverStream) = FullDuplexStream.CreatePair(); var languageServer = CreateLanguageServer(serverStream, serverStream, workspace, diagnosticService); // Notification target for tests to receive the notification details var callback = new Callback(expectedNumberOfCallbacks); using var jsonRpc = new JsonRpc(clientStream, clientStream, callback) { ExceptionStrategy = ExceptionProcessing.ISerializable, }; // The json rpc messages won't necessarily come back in order by default. // So use a synchronization context to preserve the original ordering. // https://github.com/microsoft/vs-streamjsonrpc/blob/bc970c61b90db5db135a1b3d1c72ef355c2112af/doc/resiliency.md#when-message-order-is-important jsonRpc.SynchronizationContext = new RpcOrderPreservingSynchronizationContext(); jsonRpc.StartListening(); // Triggers language server to send notifications. await languageServer.ProcessDiagnosticUpdatedBatchAsync( diagnosticService, documentsToPublish.SelectAsArray(d => d.Id), CancellationToken.None); // Waits for all notifications to be received. await callback.CallbackCompletedTask.ConfigureAwait(false); return (languageServer.GetTestAccessor(), callback.Results); static VisualStudioInProcLanguageServer CreateLanguageServer(Stream inputStream, Stream outputStream, TestWorkspace workspace, IDiagnosticService mockDiagnosticService) { var dispatcherFactory = workspace.ExportProvider.GetExportedValue<RequestDispatcherFactory>(); var listenerProvider = workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>(); var lspWorkspaceRegistrationService = workspace.ExportProvider.GetExportedValue<ILspWorkspaceRegistrationService>(); var capabilitiesProvider = workspace.ExportProvider.GetExportedValue<DefaultCapabilitiesProvider>(); var jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream)) { ExceptionStrategy = ExceptionProcessing.ISerializable, }; var languageServer = new VisualStudioInProcLanguageServer( dispatcherFactory, jsonRpc, capabilitiesProvider, lspWorkspaceRegistrationService, listenerProvider, NoOpLspLogger.Instance, mockDiagnosticService, clientName: null, userVisibleServerName: string.Empty, telemetryServerTypeName: string.Empty); jsonRpc.StartListening(); return languageServer; } } private void SetupMockWithDiagnostics(Mock<IDiagnosticService> diagnosticServiceMock, DocumentId documentId, ImmutableArray<DiagnosticData> diagnostics) { diagnosticServiceMock.Setup(d => d.GetPushDiagnosticsAsync( It.IsAny<Workspace>(), It.IsAny<ProjectId>(), documentId, It.IsAny<object>(), It.IsAny<bool>(), It.IsAny<Option2<DiagnosticMode>>(), It.IsAny<CancellationToken>())).Returns(new ValueTask<ImmutableArray<DiagnosticData>>(diagnostics)); } private void SetupMockDiagnosticSequence(Mock<IDiagnosticService> diagnosticServiceMock, DocumentId documentId, ImmutableArray<DiagnosticData> firstDiagnostics, ImmutableArray<DiagnosticData> secondDiagnostics) { diagnosticServiceMock.SetupSequence(d => d.GetPushDiagnosticsAsync( It.IsAny<Workspace>(), It.IsAny<ProjectId>(), documentId, It.IsAny<object>(), It.IsAny<bool>(), It.IsAny<Option2<DiagnosticMode>>(), It.IsAny<CancellationToken>())) .Returns(new ValueTask<ImmutableArray<DiagnosticData>>(firstDiagnostics)) .Returns(new ValueTask<ImmutableArray<DiagnosticData>>(secondDiagnostics)); } private async Task<ImmutableArray<DiagnosticData>> CreateMockDiagnosticDataAsync(Document document, string id) { var descriptor = new DiagnosticDescriptor(id, "", "", "", DiagnosticSeverity.Error, true); var location = Location.Create(await document.GetRequiredSyntaxTreeAsync(CancellationToken.None).ConfigureAwait(false), new TextSpan()); return ImmutableArray.Create(DiagnosticData.Create(Diagnostic.Create(descriptor, location), document)); } private async Task<ImmutableArray<DiagnosticData>> CreateMockDiagnosticDatasWithMappedLocationAsync(Document document, params (string diagnosticId, string mappedFilePath)[] diagnostics) { var tree = await document.GetRequiredSyntaxTreeAsync(CancellationToken.None).ConfigureAwait(false); return diagnostics.Select(d => CreateMockDiagnosticDataWithMappedLocation(document, tree, d.diagnosticId, d.mappedFilePath)).ToImmutableArray(); static DiagnosticData CreateMockDiagnosticDataWithMappedLocation(Document document, SyntaxTree tree, string id, string mappedFilePath) { var descriptor = new DiagnosticDescriptor(id, "", "", "", DiagnosticSeverity.Error, true); var location = Location.Create(tree, new TextSpan()); var diagnostic = Diagnostic.Create(descriptor, location); return new DiagnosticData(diagnostic.Id, diagnostic.Descriptor.Category, null, null, diagnostic.Severity, diagnostic.DefaultSeverity, diagnostic.Descriptor.IsEnabledByDefault, diagnostic.WarningLevel, diagnostic.Descriptor.CustomTags.AsImmutableOrEmpty(), diagnostic.Properties, document.Project.Id, GetDataLocation(document, mappedFilePath), additionalLocations: default, document.Project.Language, diagnostic.Descriptor.Title.ToString(), diagnostic.Descriptor.Description.ToString(), null, diagnostic.IsSuppressed); } static DiagnosticDataLocation GetDataLocation(Document document, string mappedFilePath) => new DiagnosticDataLocation(document.Id, originalFilePath: document.FilePath, mappedFilePath: mappedFilePath); } /// <summary> /// Synchronization context to preserve ordering of the RPC messages /// Adapted from https://dev.azure.com/devdiv/DevDiv/VS%20Cloud%20Kernel/_git/DevCore?path=%2Fsrc%2Fclr%2FMicrosoft.ServiceHub.Framework%2FServiceRpcDescriptor%2BRpcOrderPreservingSynchronizationContext.cs /// https://github.com/microsoft/vs-streamjsonrpc/issues/440 tracks exposing functionality so we don't need to copy this. /// </summary> private class RpcOrderPreservingSynchronizationContext : SynchronizationContext, IDisposable { /// <summary> /// The queue of work to execute. /// </summary> private readonly AsyncQueue<(SendOrPostCallback, object?)> _queue = new AsyncQueue<(SendOrPostCallback, object?)>(); public RpcOrderPreservingSynchronizationContext() { // Process the work in the background. this.ProcessQueueAsync().Forget(); } public override void Post(SendOrPostCallback d, object? state) => this._queue.Enqueue((d, state)); public override void Send(SendOrPostCallback d, object? state) => throw new NotSupportedException(); public override SynchronizationContext CreateCopy() => throw new NotSupportedException(); /// <summary> /// Causes this <see cref="SynchronizationContext"/> to reject all future posted work and /// releases the queue processor when it is empty. /// </summary> public void Dispose() => this._queue.Complete(); /// <summary> /// Executes queued work on the thread-pool, one at a time. /// Don't catch exceptions - let them bubble up to fail the test. /// </summary> private async Task ProcessQueueAsync() { while (!this._queue.IsCompleted) { var work = await this._queue.DequeueAsync().ConfigureAwait(false); work.Item1(work.Item2); } } } private class Callback { private readonly TaskCompletionSource<object?> _callbackCompletedTaskSource = new(); /// <summary> /// Task that can be awaited for the all callbacks to complete. /// </summary> public Task CallbackCompletedTask => _callbackCompletedTaskSource.Task; /// <summary> /// Serialized results of all publish diagnostic notifications received by this callback. /// </summary> public List<LSP.PublishDiagnosticParams> Results { get; } /// <summary> /// Lock to guard concurrent callbacks. /// </summary> private readonly object _lock = new(); /// <summary> /// The expected number of times this callback should be hit. /// Used in conjunction with <see cref="_currentNumberOfCallbacks"/> /// to determine if the callbacks are complete. /// </summary> private readonly int _expectedNumberOfCallbacks; /// <summary> /// The current number of callbacks that this callback has been hit. /// </summary> private int _currentNumberOfCallbacks; public Callback(int expectedNumberOfCallbacks) { Results = new List<LSP.PublishDiagnosticParams>(); _expectedNumberOfCallbacks = expectedNumberOfCallbacks; _currentNumberOfCallbacks = 0; if (expectedNumberOfCallbacks == 0) _callbackCompletedTaskSource.SetResult(null); } [JsonRpcMethod(LSP.Methods.TextDocumentPublishDiagnosticsName)] public Task OnDiagnosticsPublished(JToken input) { lock (_lock) { _currentNumberOfCallbacks++; Contract.ThrowIfTrue(_currentNumberOfCallbacks > _expectedNumberOfCallbacks, "received too many callbacks"); var diagnosticParams = input.ToObject<LSP.PublishDiagnosticParams>(); Results.Add(diagnosticParams); if (_currentNumberOfCallbacks == _expectedNumberOfCallbacks) _callbackCompletedTaskSource.SetResult(null); return Task.CompletedTask; } } } private class TestLanguageClient : AbstractInProcLanguageClient { public TestLanguageClient() : base(null!, null!, null, null!, null!, null!, null!, null) { } public override string Name => nameof(LspDiagnosticsTests); public override LSP.ServerCapabilities GetCapabilities(LSP.ClientCapabilities clientCapabilities) => new(); } } }
// 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.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient; using Microsoft.VisualStudio.Threading; using Moq; using Nerdbank.Streams; using Newtonsoft.Json.Linq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using StreamJsonRpc; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Roslyn.VisualStudio.Next.UnitTests.Services { [UseExportProvider] public class LspDiagnosticsTests : AbstractLanguageServerProtocolTests { [Fact] public async Task AddDiagnosticTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create a mock that returns a diagnostic for the document. SetupMockWithDiagnostics(diagnosticsMock, document.Id, await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false)); // Publish one document change diagnostic notification -> // 1. doc1 with id. // // We expect one publish diagnostic notification -> // 1. from doc1 with id. var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 1, document).ConfigureAwait(false); var result = Assert.Single(results); Assert.Equal(new Uri(document.FilePath), result.Uri); Assert.Equal("id", result.Diagnostics.Single().Code); } [Fact] public async Task NoDiagnosticsWhenInPullMode() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; workspace.SetOptions(workspace.Options.WithChangedOption( InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Pull)); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create a mock that returns a diagnostic for the document. SetupMockWithDiagnostics(diagnosticsMock, document.Id, await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false)); var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 0, document).ConfigureAwait(false); Assert.Empty(results); } [Fact] public async Task AddDiagnosticWithMappedFilesTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create two mapped diagnostics for the document. SetupMockWithDiagnostics(diagnosticsMock, document.Id, await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", document.FilePath + "m1"), ("id2", document.FilePath + "m2")).ConfigureAwait(false)); // Publish one document change diagnostic notification -> // 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2. // // We expect two publish diagnostic notifications -> // 1. from m1 with id1 (from 1 above). // 2. from m2 with id2 (from 1 above). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, expectedNumberOfCallbacks: 2, document).ConfigureAwait(false); Assert.Equal(2, results.Count); Assert.Equal(new Uri(document.FilePath + "m1"), results[0].Uri); Assert.Equal("id1", results[0].Diagnostics.Single().Code); Assert.Equal(new Uri(document.FilePath + "m2"), results[1].Uri); Assert.Equal("id2", results[1].Diagnostics.Single().Code); } [Fact] public async Task AddDiagnosticWithMappedFileToManyDocumentsTestAsync() { using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace; var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create diagnostic for the first document that has a mapped location. var mappedFilePath = documents[0].FilePath + "m1"; var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false); // Create diagnostic for the second document that maps to the same location as the first document diagnostic. var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false); SetupMockWithDiagnostics(diagnosticsMock, documents[0].Id, documentOneDiagnostic); SetupMockWithDiagnostics(diagnosticsMock, documents[1].Id, documentTwoDiagnostic); // Publish two document change diagnostic notifications -> // 1. doc1 with doc1Diagnostic = mapped file m1. // 2. doc2 with doc2Diagnostic = mapped file m1. // // We expect two publish diagnostic notifications -> // 1. from m1 with doc1Diagnostic (from 1 above). // 2. from m1 with doc1Diagnostic and doc2Diagnostic (from 2 above adding doc2Diagnostic to m1). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 2, documents[0], documents[1]).ConfigureAwait(false); Assert.Equal(2, results.Count); var expectedUri = new Uri(mappedFilePath); Assert.Equal(expectedUri, results[0].Uri); Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code); Assert.Equal(expectedUri, results[1].Uri); Assert.Equal(2, results[1].Diagnostics.Length); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic"); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic"); } [Fact] public async Task RemoveDiagnosticTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Setup the mock so the first call for a document returns a diagnostic, but the second returns empty. SetupMockDiagnosticSequence(diagnosticsMock, document.Id, await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false), ImmutableArray<DiagnosticData>.Empty); // Publish two document change diagnostic notifications -> // 1. doc1 with id. // 2. doc1 with empty. // // We expect two publish diagnostic notifications -> // 1. from doc1 with id. // 2. from doc1 with empty (from 2 above clearing out diagnostics from doc1). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 2, document, document).ConfigureAwait(false); Assert.Equal(2, results.Count); Assert.Equal(new Uri(document.FilePath), results[0].Uri); Assert.Equal("id", results[0].Diagnostics.Single().Code); Assert.Equal(new Uri(document.FilePath), results[1].Uri); Assert.True(results[1].Diagnostics.IsEmpty()); Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris()); Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics()); } [Fact] public async Task RemoveDiagnosticForMappedFilesTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); var mappedFilePathM1 = document.FilePath + "m1"; var mappedFilePathM2 = document.FilePath + "m2"; // Create two mapped diagnostics for the document on first call. // On the second call, return only the second mapped diagnostic for the document. SetupMockDiagnosticSequence(diagnosticsMock, document.Id, await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", mappedFilePathM1), ("id2", mappedFilePathM2)).ConfigureAwait(false), await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id2", mappedFilePathM2)).ConfigureAwait(false)); // Publish three document change diagnostic notifications -> // 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2. // 2. doc1 with just id2 = mapped file m2. // // We expect four publish diagnostic notifications -> // 1. from m1 with id1 (from 1 above). // 2. from m2 with id2 (from 1 above). // 3. from m1 with empty (from 2 above clearing out diagnostics for m1). // 4. from m2 with id2 (from 2 above clearing out diagnostics for m1). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, document, document).ConfigureAwait(false); var mappedFileURIM1 = new Uri(mappedFilePathM1); var mappedFileURIM2 = new Uri(mappedFilePathM2); Assert.Equal(4, results.Count); // First document update. Assert.Equal(mappedFileURIM1, results[0].Uri); Assert.Equal("id1", results[0].Diagnostics.Single().Code); Assert.Equal(mappedFileURIM2, results[1].Uri); Assert.Equal("id2", results[1].Diagnostics.Single().Code); // Second document update. Assert.Equal(mappedFileURIM1, results[2].Uri); Assert.True(results[2].Diagnostics.IsEmpty()); Assert.Equal(mappedFileURIM2, results[3].Uri); Assert.Equal("id2", results[3].Diagnostics.Single().Code); Assert.Single(testAccessor.GetFileUrisForDocument(document.Id), mappedFileURIM2); Assert.Equal("id2", testAccessor.GetDiagnosticsForUriAndDocument(document.Id, mappedFileURIM2).Single().Code); Assert.Empty(testAccessor.GetDiagnosticsForUriAndDocument(document.Id, mappedFileURIM1)); } [Fact] public async Task RemoveDiagnosticForMappedFileToManyDocumentsTestAsync() { using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace; var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create diagnostic for the first document that has a mapped location. var mappedFilePath = documents[0].FilePath + "m1"; var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false); // Create diagnostic for the second document that maps to the same location as the first document diagnostic. var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false); // On the first call for this document, return the mapped diagnostic. On the second, return nothing. SetupMockDiagnosticSequence(diagnosticsMock, documents[0].Id, documentOneDiagnostic, ImmutableArray<DiagnosticData>.Empty); // Always return the mapped diagnostic for this document. SetupMockWithDiagnostics(diagnosticsMock, documents[1].Id, documentTwoDiagnostic); // Publish three document change diagnostic notifications -> // 1. doc1 with doc1Diagnostic = mapped file path m1 // 2. doc2 with doc2Diagnostic = mapped file path m1 // 3. doc1 with empty. // // We expect three publish diagnostics -> // 1. from m1 with doc1Diagnostic (triggered by 1 above to add doc1Diagnostic). // 2. from m1 with doc1Diagnostic and doc2Diagnostic (triggered by 2 above to add doc2Diagnostic). // 3. from m1 with just doc2Diagnostic (triggered by 3 above to remove doc1Diagnostic). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 3, documents[0], documents[1], documents[0]).ConfigureAwait(false); Assert.Equal(3, results.Count); var expectedUri = new Uri(mappedFilePath); Assert.Equal(expectedUri, results[0].Uri); Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code); Assert.Equal(expectedUri, results[1].Uri); Assert.Equal(2, results[1].Diagnostics.Length); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic"); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic"); Assert.Equal(expectedUri, results[2].Uri); Assert.Equal(1, results[2].Diagnostics.Length); Assert.Contains(results[2].Diagnostics, d => d.Code == "doc2Diagnostic"); Assert.Single(testAccessor.GetFileUrisForDocument(documents[1].Id), expectedUri); Assert.Equal("doc2Diagnostic", testAccessor.GetDiagnosticsForUriAndDocument(documents[1].Id, expectedUri).Single().Code); Assert.Empty(testAccessor.GetDiagnosticsForUriAndDocument(documents[0].Id, expectedUri)); } [Fact] public async Task ClearAllDiagnosticsForMappedFilesTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); var mappedFilePathM1 = document.FilePath + "m1"; var mappedFilePathM2 = document.FilePath + "m2"; // Create two mapped diagnostics for the document on first call. // On the second call, return only empty diagnostics. SetupMockDiagnosticSequence(diagnosticsMock, document.Id, await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", mappedFilePathM1), ("id2", mappedFilePathM2)).ConfigureAwait(false), ImmutableArray<DiagnosticData>.Empty); // Publish two document change diagnostic notifications -> // 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2. // 2. doc1 with empty. // // We expect four publish diagnostic notifications - the first two are the two mapped files from 1. // The second two are the two mapped files being cleared by 2. var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, document, document).ConfigureAwait(false); var mappedFileURIM1 = new Uri(document.FilePath + "m1"); var mappedFileURIM2 = new Uri(document.FilePath + "m2"); Assert.Equal(4, results.Count); // Document's first update. Assert.Equal(mappedFileURIM1, results[0].Uri); Assert.Equal("id1", results[0].Diagnostics.Single().Code); Assert.Equal(mappedFileURIM2, results[1].Uri); Assert.Equal("id2", results[1].Diagnostics.Single().Code); // Document's second update. Assert.Equal(mappedFileURIM1, results[2].Uri); Assert.True(results[2].Diagnostics.IsEmpty()); Assert.Equal(mappedFileURIM2, results[3].Uri); Assert.True(results[3].Diagnostics.IsEmpty()); Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris()); Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics()); } [Fact] public async Task ClearAllDiagnosticsForMappedFileToManyDocumentsTestAsync() { using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace; var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create diagnostic for the first document that has a mapped location. var mappedFilePath = documents[0].FilePath + "m1"; var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false); // Create diagnostic for the second document that maps to the same location as the first document diagnostic. var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false); // On the first call for the documents, return the mapped diagnostic. On the second, return nothing. SetupMockDiagnosticSequence(diagnosticsMock, documents[0].Id, documentOneDiagnostic, ImmutableArray<DiagnosticData>.Empty); SetupMockDiagnosticSequence(diagnosticsMock, documents[1].Id, documentTwoDiagnostic, ImmutableArray<DiagnosticData>.Empty); // Publish four document change diagnostic notifications -> // 1. doc1 with doc1Diagnostic = mapped file m1. // 2. doc2 with doc2Diagnostic = mapped file m1. // 3. doc1 with empty diagnostics. // 4. doc2 with empty diagnostics. // // We expect four publish diagnostics -> // 1. from URI m1 with doc1Diagnostic (triggered by 1 above to add doc1Diagnostic). // 2. from URI m1 with doc1Diagnostic and doc2Diagnostic (triggered by 2 above to add doc2Diagnostic). // 3. from URI m1 with just doc2Diagnostic (triggered by 3 above to clear doc1 diagnostic). // 4. from URI m1 with empty (triggered by 4 above to also clear doc2 diagnostic). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, documents[0], documents[1], documents[0], documents[1]).ConfigureAwait(false); Assert.Equal(4, results.Count); var expectedUri = new Uri(mappedFilePath); Assert.Equal(expectedUri, results[0].Uri); Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code); Assert.Equal(expectedUri, results[1].Uri); Assert.Equal(2, results[1].Diagnostics.Length); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic"); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic"); Assert.Equal(expectedUri, results[2].Uri); Assert.Equal(1, results[2].Diagnostics.Length); Assert.Contains(results[2].Diagnostics, d => d.Code == "doc2Diagnostic"); Assert.Equal(expectedUri, results[3].Uri); Assert.True(results[3].Diagnostics.IsEmpty()); Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris()); Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics()); } private async Task<(VisualStudioInProcLanguageServer.TestAccessor, List<LSP.PublishDiagnosticParams>)> RunPublishDiagnosticsAsync( TestWorkspace workspace, IDiagnosticService diagnosticService, int expectedNumberOfCallbacks, params Document[] documentsToPublish) { var (clientStream, serverStream) = FullDuplexStream.CreatePair(); var languageServer = CreateLanguageServer(serverStream, serverStream, workspace, diagnosticService); // Notification target for tests to receive the notification details var callback = new Callback(expectedNumberOfCallbacks); using var jsonRpc = new JsonRpc(clientStream, clientStream, callback) { ExceptionStrategy = ExceptionProcessing.ISerializable, }; // The json rpc messages won't necessarily come back in order by default. // So use a synchronization context to preserve the original ordering. // https://github.com/microsoft/vs-streamjsonrpc/blob/bc970c61b90db5db135a1b3d1c72ef355c2112af/doc/resiliency.md#when-message-order-is-important jsonRpc.SynchronizationContext = new RpcOrderPreservingSynchronizationContext(); jsonRpc.StartListening(); // Triggers language server to send notifications. await languageServer.ProcessDiagnosticUpdatedBatchAsync( diagnosticService, documentsToPublish.SelectAsArray(d => d.Id), CancellationToken.None); // Waits for all notifications to be received. await callback.CallbackCompletedTask.ConfigureAwait(false); return (languageServer.GetTestAccessor(), callback.Results); static VisualStudioInProcLanguageServer CreateLanguageServer(Stream inputStream, Stream outputStream, TestWorkspace workspace, IDiagnosticService mockDiagnosticService) { var dispatcherFactory = workspace.ExportProvider.GetExportedValue<RequestDispatcherFactory>(); var listenerProvider = workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>(); var lspWorkspaceRegistrationService = workspace.ExportProvider.GetExportedValue<ILspWorkspaceRegistrationService>(); var capabilitiesProvider = workspace.ExportProvider.GetExportedValue<DefaultCapabilitiesProvider>(); var jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream)) { ExceptionStrategy = ExceptionProcessing.ISerializable, }; var languageServer = new VisualStudioInProcLanguageServer( dispatcherFactory, jsonRpc, capabilitiesProvider, lspWorkspaceRegistrationService, listenerProvider, NoOpLspLogger.Instance, mockDiagnosticService, clientName: null, userVisibleServerName: string.Empty, telemetryServerTypeName: string.Empty); jsonRpc.StartListening(); return languageServer; } } private void SetupMockWithDiagnostics(Mock<IDiagnosticService> diagnosticServiceMock, DocumentId documentId, ImmutableArray<DiagnosticData> diagnostics) { diagnosticServiceMock.Setup(d => d.GetPushDiagnosticsAsync( It.IsAny<Workspace>(), It.IsAny<ProjectId>(), documentId, It.IsAny<object>(), It.IsAny<bool>(), It.IsAny<Option2<DiagnosticMode>>(), It.IsAny<CancellationToken>())).Returns(new ValueTask<ImmutableArray<DiagnosticData>>(diagnostics)); } private void SetupMockDiagnosticSequence(Mock<IDiagnosticService> diagnosticServiceMock, DocumentId documentId, ImmutableArray<DiagnosticData> firstDiagnostics, ImmutableArray<DiagnosticData> secondDiagnostics) { diagnosticServiceMock.SetupSequence(d => d.GetPushDiagnosticsAsync( It.IsAny<Workspace>(), It.IsAny<ProjectId>(), documentId, It.IsAny<object>(), It.IsAny<bool>(), It.IsAny<Option2<DiagnosticMode>>(), It.IsAny<CancellationToken>())) .Returns(new ValueTask<ImmutableArray<DiagnosticData>>(firstDiagnostics)) .Returns(new ValueTask<ImmutableArray<DiagnosticData>>(secondDiagnostics)); } private async Task<ImmutableArray<DiagnosticData>> CreateMockDiagnosticDataAsync(Document document, string id) { var descriptor = new DiagnosticDescriptor(id, "", "", "", DiagnosticSeverity.Error, true); var location = Location.Create(await document.GetRequiredSyntaxTreeAsync(CancellationToken.None).ConfigureAwait(false), new TextSpan()); return ImmutableArray.Create(DiagnosticData.Create(Diagnostic.Create(descriptor, location), document)); } private async Task<ImmutableArray<DiagnosticData>> CreateMockDiagnosticDatasWithMappedLocationAsync(Document document, params (string diagnosticId, string mappedFilePath)[] diagnostics) { var tree = await document.GetRequiredSyntaxTreeAsync(CancellationToken.None).ConfigureAwait(false); return diagnostics.Select(d => CreateMockDiagnosticDataWithMappedLocation(document, tree, d.diagnosticId, d.mappedFilePath)).ToImmutableArray(); static DiagnosticData CreateMockDiagnosticDataWithMappedLocation(Document document, SyntaxTree tree, string id, string mappedFilePath) { var descriptor = new DiagnosticDescriptor(id, "", "", "", DiagnosticSeverity.Error, true); var location = Location.Create(tree, new TextSpan()); var diagnostic = Diagnostic.Create(descriptor, location); return new DiagnosticData(diagnostic.Id, diagnostic.Descriptor.Category, null, null, diagnostic.Severity, diagnostic.DefaultSeverity, diagnostic.Descriptor.IsEnabledByDefault, diagnostic.WarningLevel, diagnostic.Descriptor.CustomTags.AsImmutableOrEmpty(), diagnostic.Properties, document.Project.Id, GetDataLocation(document, mappedFilePath), additionalLocations: default, document.Project.Language, diagnostic.Descriptor.Title.ToString(), diagnostic.Descriptor.Description.ToString(), null, diagnostic.IsSuppressed); } static DiagnosticDataLocation GetDataLocation(Document document, string mappedFilePath) => new DiagnosticDataLocation(document.Id, originalFilePath: document.FilePath, mappedFilePath: mappedFilePath); } /// <summary> /// Synchronization context to preserve ordering of the RPC messages /// Adapted from https://dev.azure.com/devdiv/DevDiv/VS%20Cloud%20Kernel/_git/DevCore?path=%2Fsrc%2Fclr%2FMicrosoft.ServiceHub.Framework%2FServiceRpcDescriptor%2BRpcOrderPreservingSynchronizationContext.cs /// https://github.com/microsoft/vs-streamjsonrpc/issues/440 tracks exposing functionality so we don't need to copy this. /// </summary> private class RpcOrderPreservingSynchronizationContext : SynchronizationContext, IDisposable { /// <summary> /// The queue of work to execute. /// </summary> private readonly AsyncQueue<(SendOrPostCallback, object?)> _queue = new AsyncQueue<(SendOrPostCallback, object?)>(); public RpcOrderPreservingSynchronizationContext() { // Process the work in the background. this.ProcessQueueAsync().Forget(); } public override void Post(SendOrPostCallback d, object? state) => this._queue.Enqueue((d, state)); public override void Send(SendOrPostCallback d, object? state) => throw new NotSupportedException(); public override SynchronizationContext CreateCopy() => throw new NotSupportedException(); /// <summary> /// Causes this <see cref="SynchronizationContext"/> to reject all future posted work and /// releases the queue processor when it is empty. /// </summary> public void Dispose() => this._queue.Complete(); /// <summary> /// Executes queued work on the thread-pool, one at a time. /// Don't catch exceptions - let them bubble up to fail the test. /// </summary> private async Task ProcessQueueAsync() { while (!this._queue.IsCompleted) { var work = await this._queue.DequeueAsync().ConfigureAwait(false); work.Item1(work.Item2); } } } private class Callback { private readonly TaskCompletionSource<object?> _callbackCompletedTaskSource = new(); /// <summary> /// Task that can be awaited for the all callbacks to complete. /// </summary> public Task CallbackCompletedTask => _callbackCompletedTaskSource.Task; /// <summary> /// Serialized results of all publish diagnostic notifications received by this callback. /// </summary> public List<LSP.PublishDiagnosticParams> Results { get; } /// <summary> /// Lock to guard concurrent callbacks. /// </summary> private readonly object _lock = new(); /// <summary> /// The expected number of times this callback should be hit. /// Used in conjunction with <see cref="_currentNumberOfCallbacks"/> /// to determine if the callbacks are complete. /// </summary> private readonly int _expectedNumberOfCallbacks; /// <summary> /// The current number of callbacks that this callback has been hit. /// </summary> private int _currentNumberOfCallbacks; public Callback(int expectedNumberOfCallbacks) { Results = new List<LSP.PublishDiagnosticParams>(); _expectedNumberOfCallbacks = expectedNumberOfCallbacks; _currentNumberOfCallbacks = 0; if (expectedNumberOfCallbacks == 0) _callbackCompletedTaskSource.SetResult(null); } [JsonRpcMethod(LSP.Methods.TextDocumentPublishDiagnosticsName)] public Task OnDiagnosticsPublished(JToken input) { lock (_lock) { _currentNumberOfCallbacks++; Contract.ThrowIfTrue(_currentNumberOfCallbacks > _expectedNumberOfCallbacks, "received too many callbacks"); var diagnosticParams = input.ToObject<LSP.PublishDiagnosticParams>(); Results.Add(diagnosticParams); if (_currentNumberOfCallbacks == _expectedNumberOfCallbacks) _callbackCompletedTaskSource.SetResult(null); return Task.CompletedTask; } } } private class TestLanguageClient : AbstractInProcLanguageClient { public TestLanguageClient() : base(null!, null!, null, null!, null!, null!, null!, null) { } public override string Name => nameof(LspDiagnosticsTests); public override LSP.ServerCapabilities GetCapabilities(LSP.ClientCapabilities clientCapabilities) => new(); } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.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.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// Tracks the changes made to a project and provides the facility to get a lazily built /// compilation for that project. As the compilation is being built, the partial results are /// stored as well so that they can be used in the 'in progress' workspace snapshot. /// </summary> private partial class CompilationTracker : ICompilationTracker { private static readonly Func<ProjectState, string> s_logBuildCompilationAsync = state => string.Join(",", state.AssemblyName, state.DocumentStates.Count); public ProjectState ProjectState { get; } /// <summary> /// Access via the <see cref="ReadState"/> and <see cref="WriteState"/> methods. /// </summary> private State _stateDoNotAccessDirectly; // guarantees only one thread is building at a time private readonly SemaphoreSlim _buildLock = new(initialCount: 1); private CompilationTracker( ProjectState project, State state) { Contract.ThrowIfNull(project); this.ProjectState = project; _stateDoNotAccessDirectly = state; } /// <summary> /// Creates a tracker for the provided project. The tracker will be in the 'empty' state /// and will have no extra information beyond the project itself. /// </summary> public CompilationTracker(ProjectState project) : this(project, State.Empty) { } private State ReadState() => Volatile.Read(ref _stateDoNotAccessDirectly); private void WriteState(State state, SolutionServices solutionServices) { if (solutionServices.SupportsCachingRecoverableObjects) { // Allow the cache service to create a strong reference to the compilation. We'll get the "furthest along" compilation we have // and hold onto that. var compilationToCache = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull() ?? state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(); solutionServices.CacheService.CacheObjectIfCachingEnabledForKey(ProjectState.Id, state, compilationToCache); } Volatile.Write(ref _stateDoNotAccessDirectly, state); } public bool HasCompilation { get { var state = this.ReadState(); return state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out _) || state.DeclarationOnlyCompilation != null; } } public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { Debug.Assert(symbol.Kind == SymbolKind.Assembly || symbol.Kind == SymbolKind.NetModule || symbol.Kind == SymbolKind.DynamicType); var state = this.ReadState(); var unrootedSymbolSet = (state as FinalState)?.UnrootedSymbolSet; if (unrootedSymbolSet == null) { // this was not a tracker that has handed out a compilation (all compilations handed out must be // owned by a 'FinalState'). So this symbol could not be from us. return false; } return unrootedSymbolSet.Value.ContainsAssemblyOrModuleOrDynamic(symbol, primary); } /// <summary> /// Creates a new instance of the compilation info, retaining any already built /// compilation state as the now 'old' state /// </summary> public ICompilationTracker Fork( ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, bool clone = false, CancellationToken cancellationToken = default) { var state = ReadState(); var baseCompilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (baseCompilation != null) { // We have some pre-calculated state to incrementally update var newInProgressCompilation = clone ? baseCompilation.Clone() : baseCompilation; var intermediateProjects = state is InProgressState inProgressState ? inProgressState.IntermediateProjects : ImmutableArray.Create<(ProjectState oldState, CompilationAndGeneratorDriverTranslationAction action)>(); if (translate is not null) { // We have a translation action; are we able to merge it with the prior one? var merged = false; if (intermediateProjects.Any()) { var (priorState, priorAction) = intermediateProjects.Last(); var mergedTranslation = translate.TryMergeWithPrior(priorAction); if (mergedTranslation != null) { // We can replace the prior action with this new one intermediateProjects = intermediateProjects.SetItem(intermediateProjects.Length - 1, (oldState: priorState, mergedTranslation)); merged = true; } } if (!merged) { // Just add it to the end intermediateProjects = intermediateProjects.Add((oldState: this.ProjectState, translate)); } } var newState = State.Create(newInProgressCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects); return new CompilationTracker(newProject, newState); } var declarationOnlyCompilation = state.DeclarationOnlyCompilation; if (declarationOnlyCompilation != null) { if (translate != null) { var intermediateProjects = ImmutableArray.Create((this.ProjectState, translate)); return new CompilationTracker(newProject, new InProgressState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, compilationWithGeneratedDocuments: state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects)); } return new CompilationTracker(newProject, new LightDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, generatedDocumentsAreFinal: false)); } // We have nothing. Just make a tracker that only points to the new project. We'll have // to rebuild its compilation from scratch if anyone asks for it. return new CompilationTracker(newProject); } /// <summary> /// Creates a fork with the same final project. /// </summary> public ICompilationTracker Clone() => this.Fork(this.ProjectState, clone: true); public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken) { GetPartialCompilationState( solution, docState.Id, out var inProgressProject, out var inProgressCompilation, out var sourceGeneratedDocuments, out var generatorDriver, out var metadataReferenceToProjectId, cancellationToken); if (!inProgressCompilation.SyntaxTrees.Contains(tree)) { var existingTree = inProgressCompilation.SyntaxTrees.FirstOrDefault(t => t.FilePath == tree.FilePath); if (existingTree != null) { inProgressCompilation = inProgressCompilation.ReplaceSyntaxTree(existingTree, tree); inProgressProject = inProgressProject.UpdateDocument(docState, textChanged: false, recalculateDependentVersions: false); } else { inProgressCompilation = inProgressCompilation.AddSyntaxTrees(tree); Debug.Assert(!inProgressProject.DocumentStates.Contains(docState.Id)); inProgressProject = inProgressProject.AddDocuments(ImmutableArray.Create(docState)); } } // The user is asking for an in progress snap. We don't want to create it and then // have the compilation immediately disappear. So we force it to stay around with a ConstantValueSource. // As a policy, all partial-state projects are said to have incomplete references, since the state has no guarantees. var finalState = FinalState.Create( new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), inProgressCompilation, hasSuccessfullyLoaded: false, sourceGeneratedDocuments, generatorDriver, inProgressCompilation, this.ProjectState.Id, metadataReferenceToProjectId); return new CompilationTracker(inProgressProject, finalState); } /// <summary> /// Tries to get the latest snapshot of the compilation without waiting for it to be /// fully built. This method takes advantage of the progress side-effect produced during /// <see cref="BuildCompilationInfoAsync(SolutionState, CancellationToken)"/>. /// It will either return the already built compilation, any /// in-progress compilation or any known old compilation in that order of preference. /// The compilation state that is returned will have a compilation that is retained so /// that it cannot disappear. /// </summary> /// <param name="inProgressCompilation">The compilation to return. Contains any source generated documents that were available already added.</param> private void GetPartialCompilationState( SolutionState solution, DocumentId id, out ProjectState inProgressProject, out Compilation inProgressCompilation, out TextDocumentStates<SourceGeneratedDocumentState> sourceGeneratedDocuments, out GeneratorDriver? generatorDriver, out Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId, CancellationToken cancellationToken) { var state = ReadState(); var compilationWithoutGeneratedDocuments = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // check whether we can bail out quickly for typing case var inProgressState = state as InProgressState; sourceGeneratedDocuments = state.GeneratedDocuments; generatorDriver = state.GeneratorDriver; // all changes left for this document is modifying the given document. // we can use current state as it is since we will replace the document with latest document anyway. if (inProgressState != null && compilationWithoutGeneratedDocuments != null && inProgressState.IntermediateProjects.All(t => IsTouchDocumentActionForDocument(t.action, id))) { inProgressProject = ProjectState; // We'll add in whatever generated documents we do have; these may be from a prior run prior to some changes // being made to the project, but it's the best we have so we'll use it. inProgressCompilation = compilationWithoutGeneratedDocuments.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // This is likely a bug. It seems possible to pass out a partial compilation state that we don't // properly record assembly symbols for. metadataReferenceToProjectId = null; SolutionLogger.UseExistingPartialProjectState(); return; } inProgressProject = inProgressState != null ? inProgressState.IntermediateProjects.First().oldState : this.ProjectState; // if we already have a final compilation we are done. if (compilationWithoutGeneratedDocuments != null && state is FinalState finalState) { var finalCompilation = finalState.FinalCompilationWithGeneratedDocuments.GetValueOrNull(cancellationToken); if (finalCompilation != null) { inProgressCompilation = finalCompilation; // This should hopefully be safe to return as null. Because we already reached the 'FinalState' // before, we should have already recorded the assembly symbols for it. So not recording them // again is likely ok (as long as compilations continue to return the same IAssemblySymbols for // the same references across source edits). metadataReferenceToProjectId = null; SolutionLogger.UseExistingFullProjectState(); return; } } // 1) if we have an in-progress compilation use it. // 2) If we don't, then create a simple empty compilation/project. // 3) then, make sure that all it's p2p refs and whatnot are correct. if (compilationWithoutGeneratedDocuments == null) { inProgressProject = inProgressProject.RemoveAllDocuments(); inProgressCompilation = CreateEmptyCompilation(); } else { inProgressCompilation = compilationWithoutGeneratedDocuments; } inProgressCompilation = inProgressCompilation.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // Now add in back a consistent set of project references. For project references // try to get either a CompilationReference or a SkeletonReference. This ensures // that the in-progress project only reports a reference to another project if it // could actually get a reference to that project's metadata. var metadataReferences = new List<MetadataReference>(); var newProjectReferences = new List<ProjectReference>(); metadataReferences.AddRange(this.ProjectState.MetadataReferences); metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); if (referencedProject != null) { if (referencedProject.IsSubmission) { var previousScriptCompilation = solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).WaitAndGetResult(cancellationToken); // previous submission project must support compilation: RoslynDebug.Assert(previousScriptCompilation != null); inProgressCompilation = inProgressCompilation.WithScriptCompilationInfo(inProgressCompilation.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousScriptCompilation)); } else { // get the latest metadata for the partial compilation of the referenced project. var metadata = solution.GetPartialMetadataReference(projectReference, this.ProjectState); if (metadata == null) { // if we failed to get the metadata, check to see if we previously had existing metadata and reuse it instead. var inProgressCompilationNotRef = inProgressCompilation; metadata = inProgressCompilationNotRef.ExternalReferences.FirstOrDefault( r => solution.GetProjectState(inProgressCompilationNotRef.GetAssemblyOrModuleSymbol(r) as IAssemblySymbol)?.Id == projectReference.ProjectId); } if (metadata != null) { newProjectReferences.Add(projectReference); metadataReferences.Add(metadata); metadataReferenceToProjectId.Add(metadata, projectReference.ProjectId); } } } } inProgressProject = inProgressProject.WithProjectReferences(newProjectReferences); if (!Enumerable.SequenceEqual(inProgressCompilation.ExternalReferences, metadataReferences)) { inProgressCompilation = inProgressCompilation.WithReferences(metadataReferences); } SolutionLogger.CreatePartialProjectState(); } private static bool IsTouchDocumentActionForDocument(CompilationAndGeneratorDriverTranslationAction action, DocumentId id) => action is CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction touchDocumentAction && touchDocumentAction.DocumentId == id; /// <summary> /// Gets the final compilation if it is available. /// </summary> public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) { var state = ReadState(); if (state.FinalCompilationWithGeneratedDocuments != null && state.FinalCompilationWithGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue) { compilation = compilationOpt.Value; return true; } compilation = null; return false; } public Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken) { if (this.TryGetCompilation(out var compilation)) { // PERF: This is a hot code path and Task<TResult> isn't cheap, // so cache the completed tasks to reduce allocations. We also // need to avoid keeping a strong reference to the Compilation, // so use a ConditionalWeakTable. return SpecializedTasks.FromResult(compilation); } else { return GetCompilationSlowAsync(solution, cancellationToken); } } private async Task<Compilation> GetCompilationSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.Compilation; } private async Task<Compilation> GetOrBuildDeclarationCompilationAsync(SolutionServices solutionServices, CancellationToken cancellationToken) { try { cancellationToken.ThrowIfCancellationRequested(); using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { var state = ReadState(); // we are already in the final stage. just return it. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { return compilation; } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation == null) { // let's see whether we have declaration only compilation if (state.DeclarationOnlyCompilation != null) { // okay, move to full declaration state. do this so that declaration only compilation never // realize symbols. var declarationOnlyCompilation = state.DeclarationOnlyCompilation.Clone(); WriteState(new FullDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.GeneratedDocumentsAreFinal), solutionServices); return declarationOnlyCompilation; } // We've got nothing. Build it from scratch :( return await BuildDeclarationCompilationFromScratchAsync(solutionServices, cancellationToken).ConfigureAwait(false); } if (state is FullDeclarationState or FinalState) { // we have full declaration, just use it. return compilation; } (compilation, _, _) = await BuildDeclarationCompilationFromInProgressAsync(solutionServices, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false); // We must have an in progress compilation. Build off of that. return compilation; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<CompilationInfo> GetOrBuildCompilationInfoAsync( SolutionState solution, bool lockGate, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_Project_CompilationTracker_BuildCompilationAsync, s_logBuildCompilationAsync, ProjectState, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // Try to get the built compilation. If it exists, then we can just return that. var finalCompilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (finalCompilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return new CompilationInfo(finalCompilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments); } // Otherwise, we actually have to build it. Ensure that only one thread is trying to // build this compilation at a time. if (lockGate) { using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } else { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Builds the compilation matching the project state. In the process of building, also /// produce in progress snapshots that can be accessed from other threads. /// </summary> private Task<CompilationInfo> BuildCompilationInfoAsync( SolutionState solution, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // if we already have a compilation, we must be already done! This can happen if two // threads were waiting to build, and we came in after the other succeeded. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return Task.FromResult(new CompilationInfo(compilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments)); } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // If we have already reached FinalState in the past but the compilation was garbage collected, we still have the generated documents // so we can pass those to FinalizeCompilationAsync to avoid the recomputation. This is necessary for correctness as otherwise // we'd be reparsing trees which could result in generated documents changing identity. var authoritativeGeneratedDocuments = state.GeneratedDocumentsAreFinal ? state.GeneratedDocuments : (TextDocumentStates<SourceGeneratedDocumentState>?)null; var nonAuthoritativeGeneratedDocuments = state.GeneratedDocuments; var generatorDriver = state.GeneratorDriver; if (compilation == null) { // this can happen if compilation is already kicked out from the cache. // check whether the state we have support declaration only compilation if (state.DeclarationOnlyCompilation != null) { // we have declaration only compilation. build final one from it. return FinalizeCompilationAsync(solution, state.DeclarationOnlyCompilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken); } // We've got nothing. Build it from scratch :( return BuildCompilationInfoFromScratchAsync(solution, cancellationToken); } if (state is FullDeclarationState or FinalState) { // We have a declaration compilation, use it to reconstruct the final compilation return FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken); } else { // We must have an in progress compilation. Build off of that. return BuildFinalStateFromInProgressStateAsync(solution, (InProgressState)state, compilation, cancellationToken); } } private async Task<CompilationInfo> BuildCompilationInfoFromScratchAsync( SolutionState solution, CancellationToken cancellationToken) { try { var compilation = await BuildDeclarationCompilationFromScratchAsync(solution.Services, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: TextDocumentStates<SourceGeneratedDocumentState>.Empty, compilationWithStaleGeneratedTrees: null, generatorDriver: null, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Avoid calling " + nameof(Compilation.AddSyntaxTrees) + " in a loop due to allocation overhead.")] private async Task<Compilation> BuildDeclarationCompilationFromScratchAsync( SolutionServices solutionServices, CancellationToken cancellationToken) { try { var compilation = CreateEmptyCompilation(); var trees = ArrayBuilder<SyntaxTree>.GetInstance(ProjectState.DocumentStates.Count); foreach (var documentState in ProjectState.DocumentStates.GetStatesInCompilationOrder()) { cancellationToken.ThrowIfCancellationRequested(); // Include the tree even if the content of the document failed to load. trees.Add(await documentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } compilation = compilation.AddSyntaxTrees(trees); trees.Free(); WriteState(new FullDeclarationState(compilation, TextDocumentStates<SourceGeneratedDocumentState>.Empty, generatorDriver: null, generatedDocumentsAreFinal: false), solutionServices); return compilation; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private Compilation CreateEmptyCompilation() { var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); if (this.ProjectState.IsSubmission) { return compilationFactory.CreateSubmissionCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!, this.ProjectState.HostObjectType); } else { return compilationFactory.CreateCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!); } } private async Task<CompilationInfo> BuildFinalStateFromInProgressStateAsync( SolutionState solution, InProgressState state, Compilation inProgressCompilation, CancellationToken cancellationToken) { try { var (compilationWithoutGenerators, compilationWithGenerators, generatorDriver) = await BuildDeclarationCompilationFromInProgressAsync(solution.Services, state, inProgressCompilation, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilationWithoutGenerators, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: state.GeneratedDocuments, compilationWithGenerators, generatorDriver, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<(Compilation compilationWithoutGenerators, Compilation? compilationWithGenerators, GeneratorDriver? generatorDriver)> BuildDeclarationCompilationFromInProgressAsync( SolutionServices solutionServices, InProgressState state, Compilation compilationWithoutGenerators, CancellationToken cancellationToken) { try { var compilationWithGenerators = state.CompilationWithGeneratedDocuments; var generatorDriver = state.GeneratorDriver; // If compilationWithGenerators is the same as compilationWithoutGenerators, then it means a prior run of generators // didn't produce any files. In that case, we'll just make compilationWithGenerators null so we avoid doing any // transformations of it multiple times. Otherwise the transformations below and in FinalizeCompilationAsync will try // to update both at once, which is functionally fine but just unnecessary work. This function is always allowed to return // null for compilationWithGenerators in the end, so there's no harm there. if (compilationWithGenerators == compilationWithoutGenerators) { compilationWithGenerators = null; } var intermediateProjects = state.IntermediateProjects; while (intermediateProjects.Length > 0) { cancellationToken.ThrowIfCancellationRequested(); // We have a list of transformations to get to our final compilation; take the first transformation and apply it. var intermediateProject = intermediateProjects[0]; compilationWithoutGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithoutGenerators, cancellationToken).ConfigureAwait(false); if (compilationWithGenerators != null) { // Also transform the compilation that has generated files; we won't do that though if the transformation either would cause problems with // the generated documents, or if don't have any source generators in the first place. if (intermediateProject.action.CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput && intermediateProject.oldState.SourceGenerators.Any()) { compilationWithGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithGenerators, cancellationToken).ConfigureAwait(false); } else { compilationWithGenerators = null; } } if (generatorDriver != null) { generatorDriver = intermediateProject.action.TransformGeneratorDriver(generatorDriver); } // We have updated state, so store this new result; this allows us to drop the intermediate state we already processed // even if we were to get cancelled at a later point. intermediateProjects = intermediateProjects.RemoveAt(0); this.WriteState(State.Create(compilationWithoutGenerators, state.GeneratedDocuments, generatorDriver, compilationWithGenerators, intermediateProjects), solutionServices); } return (compilationWithoutGenerators, compilationWithGenerators, generatorDriver); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private readonly struct CompilationInfo { public Compilation Compilation { get; } public bool HasSuccessfullyLoaded { get; } public TextDocumentStates<SourceGeneratedDocumentState> GeneratedDocuments { get; } public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments) { Compilation = compilation; HasSuccessfullyLoaded = hasSuccessfullyLoaded; GeneratedDocuments = generatedDocuments; } } /// <summary> /// Add all appropriate references to the compilation and set it as our final compilation /// state. /// </summary> /// <param name="authoritativeGeneratedDocuments">The generated documents that can be used since they are already /// known to be correct for the given state. This would be non-null in cases where we had computed everything and /// ran generators, but then the compilation was garbage collected and are re-creating a compilation but we /// still had the prior generated result available.</param> /// <param name="nonAuthoritativeGeneratedDocuments">The generated documents from a previous pass which may /// or may not be correct for the current compilation. These states may be used to access cached results, if /// and when applicable for the current compilation.</param> /// <param name="compilationWithStaleGeneratedTrees">The compilation from a prior run that contains generated trees, which /// match the states included in <paramref name="nonAuthoritativeGeneratedDocuments"/>. If a generator run here produces /// the same set of generated documents as are in <paramref name="nonAuthoritativeGeneratedDocuments"/>, and we don't need to make any other /// changes to references, we can then use this compilation instead of re-adding source generated files again to the /// <paramref name="compilationWithoutGenerators"/>.</param> /// <param name="generatorDriver">The generator driver that can be reused for this finalization.</param> private async Task<CompilationInfo> FinalizeCompilationAsync( SolutionState solution, Compilation compilationWithoutGenerators, TextDocumentStates<SourceGeneratedDocumentState>? authoritativeGeneratedDocuments, TextDocumentStates<SourceGeneratedDocumentState> nonAuthoritativeGeneratedDocuments, Compilation? compilationWithStaleGeneratedTrees, GeneratorDriver? generatorDriver, CancellationToken cancellationToken) { try { // if HasAllInformation is false, then this project is always not completed. var hasSuccessfullyLoaded = this.ProjectState.HasAllInformation; var newReferences = new List<MetadataReference>(); var metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); newReferences.AddRange(this.ProjectState.MetadataReferences); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); // Even though we're creating a final compilation (vs. an in progress compilation), // it's possible that the target project has been removed. if (referencedProject != null) { // If both projects are submissions, we'll count this as a previous submission link // instead of a regular metadata reference if (referencedProject.IsSubmission) { // if the referenced project is a submission project must be a submission as well: Debug.Assert(this.ProjectState.IsSubmission); // We now need to (potentially) update the prior submission compilation. That Compilation is held in the // ScriptCompilationInfo that we need to replace as a unit. var previousSubmissionCompilation = await solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).ConfigureAwait(false); if (compilationWithoutGenerators.ScriptCompilationInfo!.PreviousScriptCompilation != previousSubmissionCompilation) { compilationWithoutGenerators = compilationWithoutGenerators.WithScriptCompilationInfo( compilationWithoutGenerators.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithScriptCompilationInfo( compilationWithStaleGeneratedTrees.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); } } else { var metadataReference = await solution.GetMetadataReferenceAsync( projectReference, this.ProjectState, cancellationToken).ConfigureAwait(false); // A reference can fail to be created if a skeleton assembly could not be constructed. if (metadataReference != null) { newReferences.Add(metadataReference); metadataReferenceToProjectId.Add(metadataReference, projectReference.ProjectId); } else { hasSuccessfullyLoaded = false; } } } } // Now that we know the set of references this compilation should have, update them if they're not already. // Generators cannot add references, so we can use the same set of references both for the compilation // that doesn't have generated files, and the one we're trying to reuse that has generated files. // Since we updated both of these compilations together in response to edits, we only have to check one // for a potential mismatch. if (!Enumerable.SequenceEqual(compilationWithoutGenerators.ExternalReferences, newReferences)) { compilationWithoutGenerators = compilationWithoutGenerators.WithReferences(newReferences); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithReferences(newReferences); } // We will finalize the compilation by adding full contents here. // TODO: allow finalize compilation to incrementally update a prior version // https://github.com/dotnet/roslyn/issues/46418 Compilation compilationWithGenerators; TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments; if (authoritativeGeneratedDocuments.HasValue) { generatedDocuments = authoritativeGeneratedDocuments.Value; compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } else { using var generatedDocumentsBuilder = new TemporaryArray<SourceGeneratedDocumentState>(); if (ProjectState.SourceGenerators.Any()) { // If we don't already have a generator driver, we'll have to create one from scratch if (generatorDriver == null) { var additionalTexts = this.ProjectState.AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText); var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); generatorDriver = compilationFactory.CreateGeneratorDriver( this.ProjectState.ParseOptions!, ProjectState.SourceGenerators, this.ProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider, additionalTexts); } generatorDriver = generatorDriver.RunGenerators(compilationWithoutGenerators, cancellationToken); var runResult = generatorDriver.GetRunResult(); // We may be able to reuse compilationWithStaleGeneratedTrees if the generated trees are identical. We will assign null // to compilationWithStaleGeneratedTrees if we at any point realize it can't be used. We'll first check the count of trees // if that changed then we absolutely can't reuse it. But if the counts match, we'll then see if each generated tree // content is identical to the prior generation run; if we find a match each time, then the set of the generated trees // and the prior generated trees are identical. if (compilationWithStaleGeneratedTrees != null) { if (nonAuthoritativeGeneratedDocuments.Count != runResult.Results.Sum(r => r.GeneratedSources.Length)) { compilationWithStaleGeneratedTrees = null; } } foreach (var generatorResult in runResult.Results) { foreach (var generatedSource in generatorResult.GeneratedSources) { var existing = FindExistingGeneratedDocumentState( nonAuthoritativeGeneratedDocuments, generatorResult.Generator, generatedSource.HintName); if (existing != null) { var newDocument = existing.WithUpdatedGeneratedContent( generatedSource.SourceText, this.ProjectState.ParseOptions!); generatedDocumentsBuilder.Add(newDocument); if (newDocument != existing) compilationWithStaleGeneratedTrees = null; } else { // NOTE: the use of generatedSource.SyntaxTree to fetch the path and options is OK, // since the tree is a lazy tree and that won't trigger the parse. var identity = SourceGeneratedDocumentIdentity.Generate( ProjectState.Id, generatedSource.HintName, generatorResult.Generator, generatedSource.SyntaxTree.FilePath); generatedDocumentsBuilder.Add( SourceGeneratedDocumentState.Create( identity, generatedSource.SourceText, generatedSource.SyntaxTree.Options, this.ProjectState.LanguageServices, solution.Services)); // The count of trees was the same, but something didn't match up. Since we're here, at least one tree // was added, and an equal number must have been removed. Rather than trying to incrementally update // this compilation, we'll just toss this and re-add all the trees. compilationWithStaleGeneratedTrees = null; } } } } // If we didn't null out this compilation, it means we can actually use it if (compilationWithStaleGeneratedTrees != null) { generatedDocuments = nonAuthoritativeGeneratedDocuments; compilationWithGenerators = compilationWithStaleGeneratedTrees; } else { generatedDocuments = new TextDocumentStates<SourceGeneratedDocumentState>(generatedDocumentsBuilder.ToImmutableAndClear()); compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } } var finalState = FinalState.Create( State.CreateValueSource(compilationWithGenerators, solution.Services), State.CreateValueSource(compilationWithoutGenerators, solution.Services), compilationWithoutGenerators, hasSuccessfullyLoaded, generatedDocuments, generatorDriver, compilationWithGenerators, this.ProjectState.Id, metadataReferenceToProjectId); this.WriteState(finalState, solution.Services); return new CompilationInfo(compilationWithGenerators, hasSuccessfullyLoaded, generatedDocuments); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } // Local functions static SourceGeneratedDocumentState? FindExistingGeneratedDocumentState( TextDocumentStates<SourceGeneratedDocumentState> states, ISourceGenerator generator, string hintName) { var generatorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator); var generatorTypeName = SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator); foreach (var (_, state) in states.States) { if (state.SourceGeneratorAssemblyName != generatorAssemblyName) continue; if (state.SourceGeneratorTypeName != generatorTypeName) continue; if (state.HintName != hintName) continue; return state; } return null; } } public async Task<MetadataReference> GetMetadataReferenceAsync( SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken) { try { // if we already have the compilation and its right kind then use it. if (this.ProjectState.LanguageServices == fromProject.LanguageServices && this.TryGetCompilation(out var compilation)) { return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } // If same language then we can wrap the other project's compilation into a compilation reference if (this.ProjectState.LanguageServices == fromProject.LanguageServices) { // otherwise, base it off the compilation by building it first. compilation = await this.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } else { // otherwise get a metadata only image reference that is built by emitting the metadata from the referenced project's compilation and re-importing it. return await this.GetMetadataOnlyImageReferenceAsync(solution, projectReference, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempts to get (without waiting) a metadata reference to a possibly in progress /// compilation. Only actual compilation references are returned. Could potentially /// return null if nothing can be provided. /// </summary> public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference) { var state = ReadState(); // get compilation in any state it happens to be in right now. if (state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue && ProjectState.LanguageServices == fromProject.LanguageServices) { // if we have a compilation and its the correct language, use a simple compilation reference return compilationOpt.Value.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } return null; } /// <summary> /// Gets a metadata reference to the metadata-only-image corresponding to the compilation. /// </summary> private async Task<MetadataReference> GetMetadataOnlyImageReferenceAsync( SolutionState solution, ProjectReference projectReference, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_SkeletonAssembly_GetMetadataOnlyImage, cancellationToken)) { var version = await this.GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false); // get or build compilation up to declaration state. this compilation will be used to provide live xml doc comment var declarationCompilation = await this.GetOrBuildDeclarationCompilationAsync(solution.Services, cancellationToken: cancellationToken).ConfigureAwait(false); solution.Workspace.LogTestMessage($"Looking for a cached skeleton assembly for {projectReference.ProjectId} before taking the lock..."); if (!MetadataOnlyReference.TryGetReference(solution, projectReference, declarationCompilation, version, out var reference)) { // using async build lock so we don't get multiple consumers attempting to build metadata-only images for the same compilation. using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { solution.Workspace.LogTestMessage($"Build lock taken for {ProjectState.Id}..."); // okay, we still don't have one. bring the compilation to final state since we are going to use it to create skeleton assembly var compilationInfo = await this.GetOrBuildCompilationInfoAsync(solution, lockGate: false, cancellationToken: cancellationToken).ConfigureAwait(false); reference = MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilationInfo.Compilation, version, cancellationToken); } } else { solution.Workspace.LogTestMessage($"Reusing the already cached skeleton assembly for {projectReference.ProjectId}"); } return reference; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// check whether the compilation contains any declaration symbol from syntax trees with /// given name /// </summary> public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken) { // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. var state = this.ReadState(); return state.DeclarationOnlyCompilation == null ? (bool?)null : state.DeclarationOnlyCompilation.ContainsSymbolsWithName(name, filter, cancellationToken); } /// <summary> /// check whether the compilation contains any declaration symbol from syntax trees with given name /// </summary> public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. var state = this.ReadState(); return state.DeclarationOnlyCompilation == null ? (bool?)null : state.DeclarationOnlyCompilation.ContainsSymbolsWithName(predicate, filter, cancellationToken); } /// <summary> /// get all syntax trees that contain declaration node with the given name /// </summary> public IEnumerable<SyntaxTree>? GetSyntaxTreesWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { var state = this.ReadState(); if (state.DeclarationOnlyCompilation == null) { return null; } // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. // use cloned compilation since this will cause symbols to be created. var clone = state.DeclarationOnlyCompilation.Clone(); return clone.GetSymbolsWithName(predicate, filter, cancellationToken).SelectMany(s => s.DeclaringSyntaxReferences.Select(r => r.SyntaxTree)); } public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken) { var state = this.ReadState(); if (state.HasSuccessfullyLoaded.HasValue) { return state.HasSuccessfullyLoaded.Value ? SpecializedTasks.True : SpecializedTasks.False; } else { return HasSuccessfullyLoadedSlowAsync(solution, cancellationToken); } } private async Task<bool> HasSuccessfullyLoadedSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.HasSuccessfullyLoaded; } public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken) { // If we don't have any generators, then we know we have no generated files, so we can skip the computation entirely. if (!this.ProjectState.SourceGenerators.Any()) { return TextDocumentStates<SourceGeneratedDocumentState>.Empty; } var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.GeneratedDocuments; } public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { var state = ReadState(); // If we are in FinalState, then we have correctly ran generators and then know the final contents of the // Compilation. The GeneratedDocuments can be filled for intermediate states, but those aren't guaranteed to be // correct and can be re-ran later. return state is FinalState finalState ? finalState.GeneratedDocuments.GetState(documentId) : null; } #region Versions // Dependent Versions are stored on compilation tracker so they are more likely to survive when unrelated solution branching occurs. private AsyncLazy<VersionStamp>? _lazyDependentVersion; private AsyncLazy<VersionStamp>? _lazyDependentSemanticVersion; public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var projVersion = projectState.Version; var docVersion = await projectState.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false); var version = docVersion.GetNewerVersion(projVersion); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentSemanticVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentSemanticVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentSemanticVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentSemanticVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var version = await projectState.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentSemanticVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } #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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// Tracks the changes made to a project and provides the facility to get a lazily built /// compilation for that project. As the compilation is being built, the partial results are /// stored as well so that they can be used in the 'in progress' workspace snapshot. /// </summary> private partial class CompilationTracker : ICompilationTracker { private static readonly Func<ProjectState, string> s_logBuildCompilationAsync = state => string.Join(",", state.AssemblyName, state.DocumentStates.Count); public ProjectState ProjectState { get; } /// <summary> /// Access via the <see cref="ReadState"/> and <see cref="WriteState"/> methods. /// </summary> private State _stateDoNotAccessDirectly; // guarantees only one thread is building at a time private readonly SemaphoreSlim _buildLock = new(initialCount: 1); private CompilationTracker( ProjectState project, State state) { Contract.ThrowIfNull(project); this.ProjectState = project; _stateDoNotAccessDirectly = state; } /// <summary> /// Creates a tracker for the provided project. The tracker will be in the 'empty' state /// and will have no extra information beyond the project itself. /// </summary> public CompilationTracker(ProjectState project) : this(project, State.Empty) { } private State ReadState() => Volatile.Read(ref _stateDoNotAccessDirectly); private void WriteState(State state, SolutionServices solutionServices) { if (solutionServices.SupportsCachingRecoverableObjects) { // Allow the cache service to create a strong reference to the compilation. We'll get the "furthest along" compilation we have // and hold onto that. var compilationToCache = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull() ?? state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(); solutionServices.CacheService.CacheObjectIfCachingEnabledForKey(ProjectState.Id, state, compilationToCache); } Volatile.Write(ref _stateDoNotAccessDirectly, state); } public bool HasCompilation { get { var state = this.ReadState(); return state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out _) || state.DeclarationOnlyCompilation != null; } } public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { Debug.Assert(symbol.Kind == SymbolKind.Assembly || symbol.Kind == SymbolKind.NetModule || symbol.Kind == SymbolKind.DynamicType); var state = this.ReadState(); var unrootedSymbolSet = (state as FinalState)?.UnrootedSymbolSet; if (unrootedSymbolSet == null) { // this was not a tracker that has handed out a compilation (all compilations handed out must be // owned by a 'FinalState'). So this symbol could not be from us. return false; } return unrootedSymbolSet.Value.ContainsAssemblyOrModuleOrDynamic(symbol, primary); } /// <summary> /// Creates a new instance of the compilation info, retaining any already built /// compilation state as the now 'old' state /// </summary> public ICompilationTracker Fork( ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, bool clone = false, CancellationToken cancellationToken = default) { var state = ReadState(); var baseCompilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (baseCompilation != null) { // We have some pre-calculated state to incrementally update var newInProgressCompilation = clone ? baseCompilation.Clone() : baseCompilation; var intermediateProjects = state is InProgressState inProgressState ? inProgressState.IntermediateProjects : ImmutableArray.Create<(ProjectState oldState, CompilationAndGeneratorDriverTranslationAction action)>(); if (translate is not null) { // We have a translation action; are we able to merge it with the prior one? var merged = false; if (intermediateProjects.Any()) { var (priorState, priorAction) = intermediateProjects.Last(); var mergedTranslation = translate.TryMergeWithPrior(priorAction); if (mergedTranslation != null) { // We can replace the prior action with this new one intermediateProjects = intermediateProjects.SetItem(intermediateProjects.Length - 1, (oldState: priorState, mergedTranslation)); merged = true; } } if (!merged) { // Just add it to the end intermediateProjects = intermediateProjects.Add((oldState: this.ProjectState, translate)); } } var newState = State.Create(newInProgressCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects); return new CompilationTracker(newProject, newState); } var declarationOnlyCompilation = state.DeclarationOnlyCompilation; if (declarationOnlyCompilation != null) { if (translate != null) { var intermediateProjects = ImmutableArray.Create((this.ProjectState, translate)); return new CompilationTracker(newProject, new InProgressState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, compilationWithGeneratedDocuments: state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects)); } return new CompilationTracker(newProject, new LightDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, generatedDocumentsAreFinal: false)); } // We have nothing. Just make a tracker that only points to the new project. We'll have // to rebuild its compilation from scratch if anyone asks for it. return new CompilationTracker(newProject); } /// <summary> /// Creates a fork with the same final project. /// </summary> public ICompilationTracker Clone() => this.Fork(this.ProjectState, clone: true); public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken) { GetPartialCompilationState( solution, docState.Id, out var inProgressProject, out var inProgressCompilation, out var sourceGeneratedDocuments, out var generatorDriver, out var metadataReferenceToProjectId, cancellationToken); if (!inProgressCompilation.SyntaxTrees.Contains(tree)) { var existingTree = inProgressCompilation.SyntaxTrees.FirstOrDefault(t => t.FilePath == tree.FilePath); if (existingTree != null) { inProgressCompilation = inProgressCompilation.ReplaceSyntaxTree(existingTree, tree); inProgressProject = inProgressProject.UpdateDocument(docState, textChanged: false, recalculateDependentVersions: false); } else { inProgressCompilation = inProgressCompilation.AddSyntaxTrees(tree); Debug.Assert(!inProgressProject.DocumentStates.Contains(docState.Id)); inProgressProject = inProgressProject.AddDocuments(ImmutableArray.Create(docState)); } } // The user is asking for an in progress snap. We don't want to create it and then // have the compilation immediately disappear. So we force it to stay around with a ConstantValueSource. // As a policy, all partial-state projects are said to have incomplete references, since the state has no guarantees. var finalState = FinalState.Create( new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), inProgressCompilation, hasSuccessfullyLoaded: false, sourceGeneratedDocuments, generatorDriver, inProgressCompilation, this.ProjectState.Id, metadataReferenceToProjectId); return new CompilationTracker(inProgressProject, finalState); } /// <summary> /// Tries to get the latest snapshot of the compilation without waiting for it to be /// fully built. This method takes advantage of the progress side-effect produced during /// <see cref="BuildCompilationInfoAsync(SolutionState, CancellationToken)"/>. /// It will either return the already built compilation, any /// in-progress compilation or any known old compilation in that order of preference. /// The compilation state that is returned will have a compilation that is retained so /// that it cannot disappear. /// </summary> /// <param name="inProgressCompilation">The compilation to return. Contains any source generated documents that were available already added.</param> private void GetPartialCompilationState( SolutionState solution, DocumentId id, out ProjectState inProgressProject, out Compilation inProgressCompilation, out TextDocumentStates<SourceGeneratedDocumentState> sourceGeneratedDocuments, out GeneratorDriver? generatorDriver, out Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId, CancellationToken cancellationToken) { var state = ReadState(); var compilationWithoutGeneratedDocuments = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // check whether we can bail out quickly for typing case var inProgressState = state as InProgressState; sourceGeneratedDocuments = state.GeneratedDocuments; generatorDriver = state.GeneratorDriver; // all changes left for this document is modifying the given document. // we can use current state as it is since we will replace the document with latest document anyway. if (inProgressState != null && compilationWithoutGeneratedDocuments != null && inProgressState.IntermediateProjects.All(t => IsTouchDocumentActionForDocument(t.action, id))) { inProgressProject = ProjectState; // We'll add in whatever generated documents we do have; these may be from a prior run prior to some changes // being made to the project, but it's the best we have so we'll use it. inProgressCompilation = compilationWithoutGeneratedDocuments.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // This is likely a bug. It seems possible to pass out a partial compilation state that we don't // properly record assembly symbols for. metadataReferenceToProjectId = null; SolutionLogger.UseExistingPartialProjectState(); return; } inProgressProject = inProgressState != null ? inProgressState.IntermediateProjects.First().oldState : this.ProjectState; // if we already have a final compilation we are done. if (compilationWithoutGeneratedDocuments != null && state is FinalState finalState) { var finalCompilation = finalState.FinalCompilationWithGeneratedDocuments.GetValueOrNull(cancellationToken); if (finalCompilation != null) { inProgressCompilation = finalCompilation; // This should hopefully be safe to return as null. Because we already reached the 'FinalState' // before, we should have already recorded the assembly symbols for it. So not recording them // again is likely ok (as long as compilations continue to return the same IAssemblySymbols for // the same references across source edits). metadataReferenceToProjectId = null; SolutionLogger.UseExistingFullProjectState(); return; } } // 1) if we have an in-progress compilation use it. // 2) If we don't, then create a simple empty compilation/project. // 3) then, make sure that all it's p2p refs and whatnot are correct. if (compilationWithoutGeneratedDocuments == null) { inProgressProject = inProgressProject.RemoveAllDocuments(); inProgressCompilation = CreateEmptyCompilation(); } else { inProgressCompilation = compilationWithoutGeneratedDocuments; } inProgressCompilation = inProgressCompilation.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // Now add in back a consistent set of project references. For project references // try to get either a CompilationReference or a SkeletonReference. This ensures // that the in-progress project only reports a reference to another project if it // could actually get a reference to that project's metadata. var metadataReferences = new List<MetadataReference>(); var newProjectReferences = new List<ProjectReference>(); metadataReferences.AddRange(this.ProjectState.MetadataReferences); metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); if (referencedProject != null) { if (referencedProject.IsSubmission) { var previousScriptCompilation = solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).WaitAndGetResult(cancellationToken); // previous submission project must support compilation: RoslynDebug.Assert(previousScriptCompilation != null); inProgressCompilation = inProgressCompilation.WithScriptCompilationInfo(inProgressCompilation.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousScriptCompilation)); } else { // get the latest metadata for the partial compilation of the referenced project. var metadata = solution.GetPartialMetadataReference(projectReference, this.ProjectState); if (metadata == null) { // if we failed to get the metadata, check to see if we previously had existing metadata and reuse it instead. var inProgressCompilationNotRef = inProgressCompilation; metadata = inProgressCompilationNotRef.ExternalReferences.FirstOrDefault( r => solution.GetProjectState(inProgressCompilationNotRef.GetAssemblyOrModuleSymbol(r) as IAssemblySymbol)?.Id == projectReference.ProjectId); } if (metadata != null) { newProjectReferences.Add(projectReference); metadataReferences.Add(metadata); metadataReferenceToProjectId.Add(metadata, projectReference.ProjectId); } } } } inProgressProject = inProgressProject.WithProjectReferences(newProjectReferences); if (!Enumerable.SequenceEqual(inProgressCompilation.ExternalReferences, metadataReferences)) { inProgressCompilation = inProgressCompilation.WithReferences(metadataReferences); } SolutionLogger.CreatePartialProjectState(); } private static bool IsTouchDocumentActionForDocument(CompilationAndGeneratorDriverTranslationAction action, DocumentId id) => action is CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction touchDocumentAction && touchDocumentAction.DocumentId == id; /// <summary> /// Gets the final compilation if it is available. /// </summary> public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) { var state = ReadState(); if (state.FinalCompilationWithGeneratedDocuments != null && state.FinalCompilationWithGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue) { compilation = compilationOpt.Value; return true; } compilation = null; return false; } public Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken) { if (this.TryGetCompilation(out var compilation)) { // PERF: This is a hot code path and Task<TResult> isn't cheap, // so cache the completed tasks to reduce allocations. We also // need to avoid keeping a strong reference to the Compilation, // so use a ConditionalWeakTable. return SpecializedTasks.FromResult(compilation); } else { return GetCompilationSlowAsync(solution, cancellationToken); } } private async Task<Compilation> GetCompilationSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.Compilation; } private async Task<Compilation> GetOrBuildDeclarationCompilationAsync(SolutionServices solutionServices, CancellationToken cancellationToken) { try { cancellationToken.ThrowIfCancellationRequested(); using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { var state = ReadState(); // we are already in the final stage. just return it. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { return compilation; } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation == null) { // let's see whether we have declaration only compilation if (state.DeclarationOnlyCompilation != null) { // okay, move to full declaration state. do this so that declaration only compilation never // realize symbols. var declarationOnlyCompilation = state.DeclarationOnlyCompilation.Clone(); WriteState(new FullDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.GeneratedDocumentsAreFinal), solutionServices); return declarationOnlyCompilation; } // We've got nothing. Build it from scratch :( return await BuildDeclarationCompilationFromScratchAsync(solutionServices, cancellationToken).ConfigureAwait(false); } if (state is FullDeclarationState or FinalState) { // we have full declaration, just use it. return compilation; } (compilation, _, _) = await BuildDeclarationCompilationFromInProgressAsync(solutionServices, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false); // We must have an in progress compilation. Build off of that. return compilation; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<CompilationInfo> GetOrBuildCompilationInfoAsync( SolutionState solution, bool lockGate, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_Project_CompilationTracker_BuildCompilationAsync, s_logBuildCompilationAsync, ProjectState, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // Try to get the built compilation. If it exists, then we can just return that. var finalCompilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (finalCompilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return new CompilationInfo(finalCompilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments); } // Otherwise, we actually have to build it. Ensure that only one thread is trying to // build this compilation at a time. if (lockGate) { using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } else { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Builds the compilation matching the project state. In the process of building, also /// produce in progress snapshots that can be accessed from other threads. /// </summary> private Task<CompilationInfo> BuildCompilationInfoAsync( SolutionState solution, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // if we already have a compilation, we must be already done! This can happen if two // threads were waiting to build, and we came in after the other succeeded. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return Task.FromResult(new CompilationInfo(compilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments)); } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // If we have already reached FinalState in the past but the compilation was garbage collected, we still have the generated documents // so we can pass those to FinalizeCompilationAsync to avoid the recomputation. This is necessary for correctness as otherwise // we'd be reparsing trees which could result in generated documents changing identity. var authoritativeGeneratedDocuments = state.GeneratedDocumentsAreFinal ? state.GeneratedDocuments : (TextDocumentStates<SourceGeneratedDocumentState>?)null; var nonAuthoritativeGeneratedDocuments = state.GeneratedDocuments; var generatorDriver = state.GeneratorDriver; if (compilation == null) { // this can happen if compilation is already kicked out from the cache. // check whether the state we have support declaration only compilation if (state.DeclarationOnlyCompilation != null) { // we have declaration only compilation. build final one from it. return FinalizeCompilationAsync(solution, state.DeclarationOnlyCompilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken); } // We've got nothing. Build it from scratch :( return BuildCompilationInfoFromScratchAsync(solution, cancellationToken); } if (state is FullDeclarationState or FinalState) { // We have a declaration compilation, use it to reconstruct the final compilation return FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken); } else { // We must have an in progress compilation. Build off of that. return BuildFinalStateFromInProgressStateAsync(solution, (InProgressState)state, compilation, cancellationToken); } } private async Task<CompilationInfo> BuildCompilationInfoFromScratchAsync( SolutionState solution, CancellationToken cancellationToken) { try { var compilation = await BuildDeclarationCompilationFromScratchAsync(solution.Services, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: TextDocumentStates<SourceGeneratedDocumentState>.Empty, compilationWithStaleGeneratedTrees: null, generatorDriver: null, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Avoid calling " + nameof(Compilation.AddSyntaxTrees) + " in a loop due to allocation overhead.")] private async Task<Compilation> BuildDeclarationCompilationFromScratchAsync( SolutionServices solutionServices, CancellationToken cancellationToken) { try { var compilation = CreateEmptyCompilation(); var trees = ArrayBuilder<SyntaxTree>.GetInstance(ProjectState.DocumentStates.Count); foreach (var documentState in ProjectState.DocumentStates.GetStatesInCompilationOrder()) { cancellationToken.ThrowIfCancellationRequested(); // Include the tree even if the content of the document failed to load. trees.Add(await documentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } compilation = compilation.AddSyntaxTrees(trees); trees.Free(); WriteState(new FullDeclarationState(compilation, TextDocumentStates<SourceGeneratedDocumentState>.Empty, generatorDriver: null, generatedDocumentsAreFinal: false), solutionServices); return compilation; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private Compilation CreateEmptyCompilation() { var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); if (this.ProjectState.IsSubmission) { return compilationFactory.CreateSubmissionCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!, this.ProjectState.HostObjectType); } else { return compilationFactory.CreateCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!); } } private async Task<CompilationInfo> BuildFinalStateFromInProgressStateAsync( SolutionState solution, InProgressState state, Compilation inProgressCompilation, CancellationToken cancellationToken) { try { var (compilationWithoutGenerators, compilationWithGenerators, generatorDriver) = await BuildDeclarationCompilationFromInProgressAsync(solution.Services, state, inProgressCompilation, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilationWithoutGenerators, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: state.GeneratedDocuments, compilationWithGenerators, generatorDriver, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<(Compilation compilationWithoutGenerators, Compilation? compilationWithGenerators, GeneratorDriver? generatorDriver)> BuildDeclarationCompilationFromInProgressAsync( SolutionServices solutionServices, InProgressState state, Compilation compilationWithoutGenerators, CancellationToken cancellationToken) { try { var compilationWithGenerators = state.CompilationWithGeneratedDocuments; var generatorDriver = state.GeneratorDriver; // If compilationWithGenerators is the same as compilationWithoutGenerators, then it means a prior run of generators // didn't produce any files. In that case, we'll just make compilationWithGenerators null so we avoid doing any // transformations of it multiple times. Otherwise the transformations below and in FinalizeCompilationAsync will try // to update both at once, which is functionally fine but just unnecessary work. This function is always allowed to return // null for compilationWithGenerators in the end, so there's no harm there. if (compilationWithGenerators == compilationWithoutGenerators) { compilationWithGenerators = null; } var intermediateProjects = state.IntermediateProjects; while (intermediateProjects.Length > 0) { cancellationToken.ThrowIfCancellationRequested(); // We have a list of transformations to get to our final compilation; take the first transformation and apply it. var intermediateProject = intermediateProjects[0]; compilationWithoutGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithoutGenerators, cancellationToken).ConfigureAwait(false); if (compilationWithGenerators != null) { // Also transform the compilation that has generated files; we won't do that though if the transformation either would cause problems with // the generated documents, or if don't have any source generators in the first place. if (intermediateProject.action.CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput && intermediateProject.oldState.SourceGenerators.Any()) { compilationWithGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithGenerators, cancellationToken).ConfigureAwait(false); } else { compilationWithGenerators = null; } } if (generatorDriver != null) { generatorDriver = intermediateProject.action.TransformGeneratorDriver(generatorDriver); } // We have updated state, so store this new result; this allows us to drop the intermediate state we already processed // even if we were to get cancelled at a later point. intermediateProjects = intermediateProjects.RemoveAt(0); this.WriteState(State.Create(compilationWithoutGenerators, state.GeneratedDocuments, generatorDriver, compilationWithGenerators, intermediateProjects), solutionServices); } return (compilationWithoutGenerators, compilationWithGenerators, generatorDriver); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private readonly struct CompilationInfo { public Compilation Compilation { get; } public bool HasSuccessfullyLoaded { get; } public TextDocumentStates<SourceGeneratedDocumentState> GeneratedDocuments { get; } public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments) { Compilation = compilation; HasSuccessfullyLoaded = hasSuccessfullyLoaded; GeneratedDocuments = generatedDocuments; } } /// <summary> /// Add all appropriate references to the compilation and set it as our final compilation /// state. /// </summary> /// <param name="authoritativeGeneratedDocuments">The generated documents that can be used since they are already /// known to be correct for the given state. This would be non-null in cases where we had computed everything and /// ran generators, but then the compilation was garbage collected and are re-creating a compilation but we /// still had the prior generated result available.</param> /// <param name="nonAuthoritativeGeneratedDocuments">The generated documents from a previous pass which may /// or may not be correct for the current compilation. These states may be used to access cached results, if /// and when applicable for the current compilation.</param> /// <param name="compilationWithStaleGeneratedTrees">The compilation from a prior run that contains generated trees, which /// match the states included in <paramref name="nonAuthoritativeGeneratedDocuments"/>. If a generator run here produces /// the same set of generated documents as are in <paramref name="nonAuthoritativeGeneratedDocuments"/>, and we don't need to make any other /// changes to references, we can then use this compilation instead of re-adding source generated files again to the /// <paramref name="compilationWithoutGenerators"/>.</param> /// <param name="generatorDriver">The generator driver that can be reused for this finalization.</param> private async Task<CompilationInfo> FinalizeCompilationAsync( SolutionState solution, Compilation compilationWithoutGenerators, TextDocumentStates<SourceGeneratedDocumentState>? authoritativeGeneratedDocuments, TextDocumentStates<SourceGeneratedDocumentState> nonAuthoritativeGeneratedDocuments, Compilation? compilationWithStaleGeneratedTrees, GeneratorDriver? generatorDriver, CancellationToken cancellationToken) { try { // if HasAllInformation is false, then this project is always not completed. var hasSuccessfullyLoaded = this.ProjectState.HasAllInformation; var newReferences = new List<MetadataReference>(); var metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); newReferences.AddRange(this.ProjectState.MetadataReferences); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); // Even though we're creating a final compilation (vs. an in progress compilation), // it's possible that the target project has been removed. if (referencedProject != null) { // If both projects are submissions, we'll count this as a previous submission link // instead of a regular metadata reference if (referencedProject.IsSubmission) { // if the referenced project is a submission project must be a submission as well: Debug.Assert(this.ProjectState.IsSubmission); // We now need to (potentially) update the prior submission compilation. That Compilation is held in the // ScriptCompilationInfo that we need to replace as a unit. var previousSubmissionCompilation = await solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).ConfigureAwait(false); if (compilationWithoutGenerators.ScriptCompilationInfo!.PreviousScriptCompilation != previousSubmissionCompilation) { compilationWithoutGenerators = compilationWithoutGenerators.WithScriptCompilationInfo( compilationWithoutGenerators.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithScriptCompilationInfo( compilationWithStaleGeneratedTrees.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); } } else { var metadataReference = await solution.GetMetadataReferenceAsync( projectReference, this.ProjectState, cancellationToken).ConfigureAwait(false); // A reference can fail to be created if a skeleton assembly could not be constructed. if (metadataReference != null) { newReferences.Add(metadataReference); metadataReferenceToProjectId.Add(metadataReference, projectReference.ProjectId); } else { hasSuccessfullyLoaded = false; } } } } // Now that we know the set of references this compilation should have, update them if they're not already. // Generators cannot add references, so we can use the same set of references both for the compilation // that doesn't have generated files, and the one we're trying to reuse that has generated files. // Since we updated both of these compilations together in response to edits, we only have to check one // for a potential mismatch. if (!Enumerable.SequenceEqual(compilationWithoutGenerators.ExternalReferences, newReferences)) { compilationWithoutGenerators = compilationWithoutGenerators.WithReferences(newReferences); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithReferences(newReferences); } // We will finalize the compilation by adding full contents here. // TODO: allow finalize compilation to incrementally update a prior version // https://github.com/dotnet/roslyn/issues/46418 Compilation compilationWithGenerators; TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments; if (authoritativeGeneratedDocuments.HasValue) { generatedDocuments = authoritativeGeneratedDocuments.Value; compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } else { using var generatedDocumentsBuilder = new TemporaryArray<SourceGeneratedDocumentState>(); if (ProjectState.SourceGenerators.Any()) { // If we don't already have a generator driver, we'll have to create one from scratch if (generatorDriver == null) { var additionalTexts = this.ProjectState.AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText); var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); generatorDriver = compilationFactory.CreateGeneratorDriver( this.ProjectState.ParseOptions!, ProjectState.SourceGenerators, this.ProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider, additionalTexts); } generatorDriver = generatorDriver.RunGenerators(compilationWithoutGenerators, cancellationToken); var runResult = generatorDriver.GetRunResult(); // We may be able to reuse compilationWithStaleGeneratedTrees if the generated trees are identical. We will assign null // to compilationWithStaleGeneratedTrees if we at any point realize it can't be used. We'll first check the count of trees // if that changed then we absolutely can't reuse it. But if the counts match, we'll then see if each generated tree // content is identical to the prior generation run; if we find a match each time, then the set of the generated trees // and the prior generated trees are identical. if (compilationWithStaleGeneratedTrees != null) { if (nonAuthoritativeGeneratedDocuments.Count != runResult.Results.Sum(r => r.GeneratedSources.Length)) { compilationWithStaleGeneratedTrees = null; } } foreach (var generatorResult in runResult.Results) { foreach (var generatedSource in generatorResult.GeneratedSources) { var existing = FindExistingGeneratedDocumentState( nonAuthoritativeGeneratedDocuments, generatorResult.Generator, generatedSource.HintName); if (existing != null) { var newDocument = existing.WithUpdatedGeneratedContent( generatedSource.SourceText, this.ProjectState.ParseOptions!); generatedDocumentsBuilder.Add(newDocument); if (newDocument != existing) compilationWithStaleGeneratedTrees = null; } else { // NOTE: the use of generatedSource.SyntaxTree to fetch the path and options is OK, // since the tree is a lazy tree and that won't trigger the parse. var identity = SourceGeneratedDocumentIdentity.Generate( ProjectState.Id, generatedSource.HintName, generatorResult.Generator, generatedSource.SyntaxTree.FilePath); generatedDocumentsBuilder.Add( SourceGeneratedDocumentState.Create( identity, generatedSource.SourceText, generatedSource.SyntaxTree.Options, this.ProjectState.LanguageServices, solution.Services)); // The count of trees was the same, but something didn't match up. Since we're here, at least one tree // was added, and an equal number must have been removed. Rather than trying to incrementally update // this compilation, we'll just toss this and re-add all the trees. compilationWithStaleGeneratedTrees = null; } } } } // If we didn't null out this compilation, it means we can actually use it if (compilationWithStaleGeneratedTrees != null) { generatedDocuments = nonAuthoritativeGeneratedDocuments; compilationWithGenerators = compilationWithStaleGeneratedTrees; } else { generatedDocuments = new TextDocumentStates<SourceGeneratedDocumentState>(generatedDocumentsBuilder.ToImmutableAndClear()); compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } } var finalState = FinalState.Create( State.CreateValueSource(compilationWithGenerators, solution.Services), State.CreateValueSource(compilationWithoutGenerators, solution.Services), compilationWithoutGenerators, hasSuccessfullyLoaded, generatedDocuments, generatorDriver, compilationWithGenerators, this.ProjectState.Id, metadataReferenceToProjectId); this.WriteState(finalState, solution.Services); return new CompilationInfo(compilationWithGenerators, hasSuccessfullyLoaded, generatedDocuments); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } // Local functions static SourceGeneratedDocumentState? FindExistingGeneratedDocumentState( TextDocumentStates<SourceGeneratedDocumentState> states, ISourceGenerator generator, string hintName) { var generatorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator); var generatorTypeName = SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator); foreach (var (_, state) in states.States) { if (state.SourceGeneratorAssemblyName != generatorAssemblyName) continue; if (state.SourceGeneratorTypeName != generatorTypeName) continue; if (state.HintName != hintName) continue; return state; } return null; } } public async Task<MetadataReference> GetMetadataReferenceAsync( SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken) { try { // if we already have the compilation and its right kind then use it. if (this.ProjectState.LanguageServices == fromProject.LanguageServices && this.TryGetCompilation(out var compilation)) { return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } // If same language then we can wrap the other project's compilation into a compilation reference if (this.ProjectState.LanguageServices == fromProject.LanguageServices) { // otherwise, base it off the compilation by building it first. compilation = await this.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } else { // otherwise get a metadata only image reference that is built by emitting the metadata from the referenced project's compilation and re-importing it. return await this.GetMetadataOnlyImageReferenceAsync(solution, projectReference, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempts to get (without waiting) a metadata reference to a possibly in progress /// compilation. Only actual compilation references are returned. Could potentially /// return null if nothing can be provided. /// </summary> public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference) { var state = ReadState(); // get compilation in any state it happens to be in right now. if (state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue && ProjectState.LanguageServices == fromProject.LanguageServices) { // if we have a compilation and its the correct language, use a simple compilation reference return compilationOpt.Value.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } return null; } /// <summary> /// Gets a metadata reference to the metadata-only-image corresponding to the compilation. /// </summary> private async Task<MetadataReference> GetMetadataOnlyImageReferenceAsync( SolutionState solution, ProjectReference projectReference, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_SkeletonAssembly_GetMetadataOnlyImage, cancellationToken)) { var version = await this.GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false); // get or build compilation up to declaration state. this compilation will be used to provide live xml doc comment var declarationCompilation = await this.GetOrBuildDeclarationCompilationAsync(solution.Services, cancellationToken: cancellationToken).ConfigureAwait(false); solution.Workspace.LogTestMessage($"Looking for a cached skeleton assembly for {projectReference.ProjectId} before taking the lock..."); if (!MetadataOnlyReference.TryGetReference(solution, projectReference, declarationCompilation, version, out var reference)) { // using async build lock so we don't get multiple consumers attempting to build metadata-only images for the same compilation. using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { solution.Workspace.LogTestMessage($"Build lock taken for {ProjectState.Id}..."); // okay, we still don't have one. bring the compilation to final state since we are going to use it to create skeleton assembly var compilationInfo = await this.GetOrBuildCompilationInfoAsync(solution, lockGate: false, cancellationToken: cancellationToken).ConfigureAwait(false); reference = MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilationInfo.Compilation, version, cancellationToken); } } else { solution.Workspace.LogTestMessage($"Reusing the already cached skeleton assembly for {projectReference.ProjectId}"); } return reference; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// check whether the compilation contains any declaration symbol from syntax trees with /// given name /// </summary> public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken) { // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. var state = this.ReadState(); return state.DeclarationOnlyCompilation == null ? (bool?)null : state.DeclarationOnlyCompilation.ContainsSymbolsWithName(name, filter, cancellationToken); } /// <summary> /// check whether the compilation contains any declaration symbol from syntax trees with given name /// </summary> public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. var state = this.ReadState(); return state.DeclarationOnlyCompilation == null ? (bool?)null : state.DeclarationOnlyCompilation.ContainsSymbolsWithName(predicate, filter, cancellationToken); } /// <summary> /// get all syntax trees that contain declaration node with the given name /// </summary> public IEnumerable<SyntaxTree>? GetSyntaxTreesWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { var state = this.ReadState(); if (state.DeclarationOnlyCompilation == null) { return null; } // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. // use cloned compilation since this will cause symbols to be created. var clone = state.DeclarationOnlyCompilation.Clone(); return clone.GetSymbolsWithName(predicate, filter, cancellationToken).SelectMany(s => s.DeclaringSyntaxReferences.Select(r => r.SyntaxTree)); } public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken) { var state = this.ReadState(); if (state.HasSuccessfullyLoaded.HasValue) { return state.HasSuccessfullyLoaded.Value ? SpecializedTasks.True : SpecializedTasks.False; } else { return HasSuccessfullyLoadedSlowAsync(solution, cancellationToken); } } private async Task<bool> HasSuccessfullyLoadedSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.HasSuccessfullyLoaded; } public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken) { // If we don't have any generators, then we know we have no generated files, so we can skip the computation entirely. if (!this.ProjectState.SourceGenerators.Any()) { return TextDocumentStates<SourceGeneratedDocumentState>.Empty; } var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.GeneratedDocuments; } public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { var state = ReadState(); // If we are in FinalState, then we have correctly ran generators and then know the final contents of the // Compilation. The GeneratedDocuments can be filled for intermediate states, but those aren't guaranteed to be // correct and can be re-ran later. return state is FinalState finalState ? finalState.GeneratedDocuments.GetState(documentId) : null; } #region Versions // Dependent Versions are stored on compilation tracker so they are more likely to survive when unrelated solution branching occurs. private AsyncLazy<VersionStamp>? _lazyDependentVersion; private AsyncLazy<VersionStamp>? _lazyDependentSemanticVersion; public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var projVersion = projectState.Version; var docVersion = await projectState.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false); var version = docVersion.GetNewerVersion(projVersion); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentSemanticVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentSemanticVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentSemanticVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentSemanticVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var version = await projectState.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentSemanticVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } #endregion } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/VisualStudio/Core/Test/CodeModel/CSharp/CodeVariableTests.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.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeVariableTests Inherits AbstractCodeVariableTests #Region "GetStartPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_Field() Dim code = <Code> class C { int $$goo; } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=9, absoluteOffset:=19, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=15, lineLength:=12))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_EnumMember() Dim code = <Code> enum E { $$Goo } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=14, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=14, lineLength:=7))) End Sub #End Region #Region "GetEndPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_Field() Dim code = <Code> class C { int $$goo; } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=12, absoluteOffset:=22, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=13, absoluteOffset:=23, lineLength:=12))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_EnumMember() Dim code = <Code> enum E { $$Goo } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=17, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=17, lineLength:=7))) End Sub #End Region #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> class C { int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> class C { private int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> class C { protected int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess4() Dim code = <Code> class C { protected internal int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess5() Dim code = <Code> class C { internal int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess6() Dim code = <Code> class C { public int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess7() Dim code = <Code> enum E { $$Goo } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Attributes tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes1() Dim code = <Code> class C { int $$Goo; } </Code> TestAttributes(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes2() Dim code = <Code> using System; class C { [Serializable] int $$Goo; } </Code> TestAttributes(code, IsElement("Serializable")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes3() Dim code = <Code>using System; class C { [Serializable] [CLSCompliant(true)] int $$Goo; } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes4() Dim code = <Code>using System; class C { [Serializable, CLSCompliant(true)] int $$Goo; } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> using System; class C { int $$F; } </Code> Dim expected = <Code> using System; class C { [Serializable()] int F; } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> using System; class C { [Serializable] int $$F; } </Code> Dim expected = <Code> using System; class C { [Serializable] [CLSCompliant(true)] int F; } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> using System; class C { /// &lt;summary&gt;&lt;/summary&gt; int $$F; } </Code> Dim expected = <Code> using System; class C { /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] int F; } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function #End Region #Region "ConstKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind1() Dim code = <Code> enum E { $$Goo } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind2() Dim code = <Code> class C { int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind3() Dim code = <Code> class C { const int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind4() Dim code = <Code> class C { readonly int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind5() Dim code = <Code> class C { readonly const int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst Or EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Sub #End Region #Region "FullName tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName1() Dim code = <Code> enum E { $$Goo = 1, Bar } </Code> TestFullName(code, "E.Goo") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName2() Dim code = <Code> enum E { Goo = 1, $$Bar } </Code> TestFullName(code, "E.Bar") End Sub #End Region #Region "InitExpression tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression1() Dim code = <Code> class C { int $$i = 42; } </Code> TestInitExpression(code, "42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression2() Dim code = <Code> class C { const int $$i = 19 + 23; } </Code> TestInitExpression(code, "19 + 23") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression3() Dim code = <Code> enum E { $$i = 19 + 23 } </Code> TestInitExpression(code, "19 + 23") End Sub #End Region #Region "IsConstant tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant1() Dim code = <Code> enum E { $$Goo } </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant2() Dim code = <Code> class C { const int $$x = 0; } </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant3() Dim code = <Code> class C { readonly int $$x = 0; } </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant4() Dim code = <Code> class C { int $$x = 0; } </Code> TestIsConstant(code, False) End Sub #End Region #Region "IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared1() Dim code = <Code> class C { int $$x; } </Code> TestIsShared(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared2() Dim code = <Code> class C { static int $$x; } </Code> TestIsShared(code, True) End Sub #End Region #Region "Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName1() Dim code = <Code> enum E { $$Goo = 1, Bar } </Code> TestName(code, "Goo") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName2() Dim code = <Code> enum E { Goo = 1, $$Bar } </Code> TestName(code, "Bar") End Sub #End Region #Region "Prototype tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullName() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "N.C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpression1() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "x = 0") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpression2() Dim code = <Code> namespace N { enum E { A$$ = 42 } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "A = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpressionAndType1() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "int x = 0") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpressionAndType2() Dim code = <Code> namespace N { enum E { A$$ = 42 } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "N.E A = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassNameInitExpressionAndType() Dim code = <Code> namespace N { enum E { A$$ = 42 } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType Or EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "N.E E.A = 42") End Sub #End Region #Region "Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType1() Dim code = <Code> class C { int $$i; } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "int", .AsFullName = "System.Int32", .CodeTypeFullName = "System.Int32", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt }) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType2() Dim code = <Code> class C { int i, $$j; } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "int", .AsFullName = "System.Int32", .CodeTypeFullName = "System.Int32", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt }) End Sub <WorkItem(888785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/888785")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestArrayTypeName() Dim code = <Code> class C { int[] $$array; } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "int[]", .AsFullName = "System.Int32[]", .CodeTypeFullName = "System.Int32[]", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefArray }) End Sub #End Region #Region "Set Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess1() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess2() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess3() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { public int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess2() As Task Dim code = <Code> class C { public int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess3() As Task Dim code = <Code> class C { private int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess4() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess5() As Task Dim code = <Code> class C { public int $$i; } </Code> Dim expected = <Code> class C { protected internal int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess6() As Task Dim code = <Code> class C { #region Goo int x; #endregion int $$i; } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion public int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess7() As Task Dim code = <Code> class C { #region Goo int x; #endregion public int $$i; } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion protected internal int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess8() As Task Dim code = <Code> class C { #region Goo int x; #endregion public int $$i; } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess9() As Task Dim code = <Code> class C { #region Goo int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo public int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess10() As Task Dim code = <Code> class C { #region Goo public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess11() As Task Dim code = <Code> class C { #region Goo public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo protected internal int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess12() As Task Dim code = <Code> class C { #region Goo [Goo] public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo [Goo] protected internal int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess13() As Task Dim code = <Code> class C { #region Goo // Comment comment comment public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo // Comment comment comment protected internal int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess14() As Task Dim code = <Code><![CDATA[ class C { #region Goo /// <summary> /// Comment comment comment /// </summary> public int $$x; #endregion } ]]></Code> Dim expected = <Code><![CDATA[ class C { #region Goo /// <summary> /// Comment comment comment /// </summary> protected internal int x; #endregion } ]]></Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function #End Region #Region "Set ConstKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind1() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind2() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind3() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone, ThrowsArgumentException(Of EnvDTE80.vsCMConstKind)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind4() As Task Dim code = <Code> class C { int $$x; } </Code> Dim expected = <Code> class C { int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind5() As Task Dim code = <Code> class C { int $$x; } </Code> Dim expected = <Code> class C { const int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind6() As Task Dim code = <Code> class C { const int $$x; } </Code> Dim expected = <Code> class C { int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind7() As Task Dim code = <Code> class C { int $$x; } </Code> Dim expected = <Code> class C { readonly int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind8() As Task Dim code = <Code> class C { readonly int $$x; } </Code> Dim expected = <Code> class C { int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent1() As Task Dim code = <Code> class C { volatile int $$x; } </Code> Dim expected = <Code> class C { volatile const int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent2() As Task Dim code = <Code> class C { volatile int $$x; } </Code> Dim expected = <Code> class C { volatile readonly int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent3() As Task Dim code = <Code> class C { volatile readonly int $$x; } </Code> Dim expected = <Code> class C { volatile const int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent4() As Task Dim code = <Code> class C { volatile readonly int $$x; } </Code> Dim expected = <Code> class C { volatile int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function #End Region #Region "Set InitExpression tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { int i = 42; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression2() As Task Dim code = <Code> class C { int $$i = 42; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetInitExpression(code, expected, Nothing) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression3() As Task Dim code = <Code> class C { int $$i, j; } </Code> Dim expected = <Code> class C { int i = 42, j; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression4() As Task Dim code = <Code> class C { int i, $$j; } </Code> Dim expected = <Code> class C { int i, j = 42; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression5() As Task Dim code = <Code> class C { const int $$i = 0; } </Code> Dim expected = <Code> class C { const int i = 42; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression6() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo = 42 } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression7() As Task Dim code = <Code> enum E { $$Goo = 42 } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetInitExpression(code, expected, Nothing) End Function #End Region #Region "Set IsConstant tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant1() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant2() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetIsConstant(code, expected, False, ThrowsCOMException(Of Boolean)(E_FAIL)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant3() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { const int i; } </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant4() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant5() As Task Dim code = <Code> class C { const int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant6() As Task Dim code = <Code> class C { const int $$i; } </Code> Dim expected = <Code> class C { const int i; } </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant7() As Task Dim code = <Code> class C { readonly int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant8() As Task Dim code = <Code> class C { readonly int $$i; } </Code> Dim expected = <Code> class C { readonly int i; } </Code> Await TestSetIsConstant(code, expected, True) End Function #End Region #Region "Set IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { static int i; } </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared2() As Task Dim code = <Code> class C { static int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsShared(code, expected, False) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> class C { int $$Goo; } </Code> Dim expected = <Code> class C { int Bar; } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName2() As Task Dim code = <Code> class C { #region Goo int $$Goo; #endregion } </Code> Dim expected = <Code> class C { #region Goo int Bar; #endregion } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region #Region "Set Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { double i; } </Code> Await TestSetTypeProp(code, expected, "double") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType2() As Task Dim code = <Code> class C { int i, $$j; } </Code> Dim expected = <Code> class C { double i, j; } </Code> Await TestSetTypeProp(code, expected, "double") End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> class S { int $$x; } </Code> TestPropertyDescriptors(Of EnvDTE80.CodeVariable2)(code) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp 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.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeVariableTests Inherits AbstractCodeVariableTests #Region "GetStartPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_Field() Dim code = <Code> class C { int $$goo; } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=9, absoluteOffset:=19, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=15, lineLength:=12))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_EnumMember() Dim code = <Code> enum E { $$Goo } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=14, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=14, lineLength:=7))) End Sub #End Region #Region "GetEndPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_Field() Dim code = <Code> class C { int $$goo; } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=12, absoluteOffset:=22, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=13, absoluteOffset:=23, lineLength:=12))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_EnumMember() Dim code = <Code> enum E { $$Goo } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=17, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=17, lineLength:=7))) End Sub #End Region #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> class C { int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> class C { private int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> class C { protected int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess4() Dim code = <Code> class C { protected internal int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess5() Dim code = <Code> class C { internal int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess6() Dim code = <Code> class C { public int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess7() Dim code = <Code> enum E { $$Goo } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Attributes tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes1() Dim code = <Code> class C { int $$Goo; } </Code> TestAttributes(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes2() Dim code = <Code> using System; class C { [Serializable] int $$Goo; } </Code> TestAttributes(code, IsElement("Serializable")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes3() Dim code = <Code>using System; class C { [Serializable] [CLSCompliant(true)] int $$Goo; } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes4() Dim code = <Code>using System; class C { [Serializable, CLSCompliant(true)] int $$Goo; } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> using System; class C { int $$F; } </Code> Dim expected = <Code> using System; class C { [Serializable()] int F; } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> using System; class C { [Serializable] int $$F; } </Code> Dim expected = <Code> using System; class C { [Serializable] [CLSCompliant(true)] int F; } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> using System; class C { /// &lt;summary&gt;&lt;/summary&gt; int $$F; } </Code> Dim expected = <Code> using System; class C { /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] int F; } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function #End Region #Region "ConstKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind1() Dim code = <Code> enum E { $$Goo } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind2() Dim code = <Code> class C { int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind3() Dim code = <Code> class C { const int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind4() Dim code = <Code> class C { readonly int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind5() Dim code = <Code> class C { readonly const int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst Or EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Sub #End Region #Region "FullName tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName1() Dim code = <Code> enum E { $$Goo = 1, Bar } </Code> TestFullName(code, "E.Goo") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName2() Dim code = <Code> enum E { Goo = 1, $$Bar } </Code> TestFullName(code, "E.Bar") End Sub #End Region #Region "InitExpression tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression1() Dim code = <Code> class C { int $$i = 42; } </Code> TestInitExpression(code, "42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression2() Dim code = <Code> class C { const int $$i = 19 + 23; } </Code> TestInitExpression(code, "19 + 23") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression3() Dim code = <Code> enum E { $$i = 19 + 23 } </Code> TestInitExpression(code, "19 + 23") End Sub #End Region #Region "IsConstant tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant1() Dim code = <Code> enum E { $$Goo } </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant2() Dim code = <Code> class C { const int $$x = 0; } </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant3() Dim code = <Code> class C { readonly int $$x = 0; } </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant4() Dim code = <Code> class C { int $$x = 0; } </Code> TestIsConstant(code, False) End Sub #End Region #Region "IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared1() Dim code = <Code> class C { int $$x; } </Code> TestIsShared(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared2() Dim code = <Code> class C { static int $$x; } </Code> TestIsShared(code, True) End Sub #End Region #Region "Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName1() Dim code = <Code> enum E { $$Goo = 1, Bar } </Code> TestName(code, "Goo") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName2() Dim code = <Code> enum E { Goo = 1, $$Bar } </Code> TestName(code, "Bar") End Sub #End Region #Region "Prototype tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullName() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "N.C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpression1() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "x = 0") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpression2() Dim code = <Code> namespace N { enum E { A$$ = 42 } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "A = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpressionAndType1() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "int x = 0") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpressionAndType2() Dim code = <Code> namespace N { enum E { A$$ = 42 } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "N.E A = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassNameInitExpressionAndType() Dim code = <Code> namespace N { enum E { A$$ = 42 } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType Or EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "N.E E.A = 42") End Sub #End Region #Region "Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType1() Dim code = <Code> class C { int $$i; } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "int", .AsFullName = "System.Int32", .CodeTypeFullName = "System.Int32", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt }) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType2() Dim code = <Code> class C { int i, $$j; } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "int", .AsFullName = "System.Int32", .CodeTypeFullName = "System.Int32", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt }) End Sub <WorkItem(888785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/888785")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestArrayTypeName() Dim code = <Code> class C { int[] $$array; } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "int[]", .AsFullName = "System.Int32[]", .CodeTypeFullName = "System.Int32[]", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefArray }) End Sub #End Region #Region "Set Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess1() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess2() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess3() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { public int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess2() As Task Dim code = <Code> class C { public int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess3() As Task Dim code = <Code> class C { private int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess4() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess5() As Task Dim code = <Code> class C { public int $$i; } </Code> Dim expected = <Code> class C { protected internal int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess6() As Task Dim code = <Code> class C { #region Goo int x; #endregion int $$i; } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion public int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess7() As Task Dim code = <Code> class C { #region Goo int x; #endregion public int $$i; } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion protected internal int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess8() As Task Dim code = <Code> class C { #region Goo int x; #endregion public int $$i; } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess9() As Task Dim code = <Code> class C { #region Goo int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo public int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess10() As Task Dim code = <Code> class C { #region Goo public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess11() As Task Dim code = <Code> class C { #region Goo public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo protected internal int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess12() As Task Dim code = <Code> class C { #region Goo [Goo] public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo [Goo] protected internal int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess13() As Task Dim code = <Code> class C { #region Goo // Comment comment comment public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo // Comment comment comment protected internal int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess14() As Task Dim code = <Code><![CDATA[ class C { #region Goo /// <summary> /// Comment comment comment /// </summary> public int $$x; #endregion } ]]></Code> Dim expected = <Code><![CDATA[ class C { #region Goo /// <summary> /// Comment comment comment /// </summary> protected internal int x; #endregion } ]]></Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function #End Region #Region "Set ConstKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind1() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind2() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind3() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone, ThrowsArgumentException(Of EnvDTE80.vsCMConstKind)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind4() As Task Dim code = <Code> class C { int $$x; } </Code> Dim expected = <Code> class C { int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind5() As Task Dim code = <Code> class C { int $$x; } </Code> Dim expected = <Code> class C { const int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind6() As Task Dim code = <Code> class C { const int $$x; } </Code> Dim expected = <Code> class C { int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind7() As Task Dim code = <Code> class C { int $$x; } </Code> Dim expected = <Code> class C { readonly int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind8() As Task Dim code = <Code> class C { readonly int $$x; } </Code> Dim expected = <Code> class C { int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent1() As Task Dim code = <Code> class C { volatile int $$x; } </Code> Dim expected = <Code> class C { volatile const int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent2() As Task Dim code = <Code> class C { volatile int $$x; } </Code> Dim expected = <Code> class C { volatile readonly int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent3() As Task Dim code = <Code> class C { volatile readonly int $$x; } </Code> Dim expected = <Code> class C { volatile const int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent4() As Task Dim code = <Code> class C { volatile readonly int $$x; } </Code> Dim expected = <Code> class C { volatile int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function #End Region #Region "Set InitExpression tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { int i = 42; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression2() As Task Dim code = <Code> class C { int $$i = 42; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetInitExpression(code, expected, Nothing) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression3() As Task Dim code = <Code> class C { int $$i, j; } </Code> Dim expected = <Code> class C { int i = 42, j; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression4() As Task Dim code = <Code> class C { int i, $$j; } </Code> Dim expected = <Code> class C { int i, j = 42; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression5() As Task Dim code = <Code> class C { const int $$i = 0; } </Code> Dim expected = <Code> class C { const int i = 42; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression6() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo = 42 } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression7() As Task Dim code = <Code> enum E { $$Goo = 42 } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetInitExpression(code, expected, Nothing) End Function #End Region #Region "Set IsConstant tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant1() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant2() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetIsConstant(code, expected, False, ThrowsCOMException(Of Boolean)(E_FAIL)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant3() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { const int i; } </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant4() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant5() As Task Dim code = <Code> class C { const int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant6() As Task Dim code = <Code> class C { const int $$i; } </Code> Dim expected = <Code> class C { const int i; } </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant7() As Task Dim code = <Code> class C { readonly int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant8() As Task Dim code = <Code> class C { readonly int $$i; } </Code> Dim expected = <Code> class C { readonly int i; } </Code> Await TestSetIsConstant(code, expected, True) End Function #End Region #Region "Set IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { static int i; } </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared2() As Task Dim code = <Code> class C { static int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsShared(code, expected, False) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> class C { int $$Goo; } </Code> Dim expected = <Code> class C { int Bar; } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName2() As Task Dim code = <Code> class C { #region Goo int $$Goo; #endregion } </Code> Dim expected = <Code> class C { #region Goo int Bar; #endregion } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region #Region "Set Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { double i; } </Code> Await TestSetTypeProp(code, expected, "double") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType2() As Task Dim code = <Code> class C { int i, $$j; } </Code> Dim expected = <Code> class C { double i, j; } </Code> Await TestSetTypeProp(code, expected, "double") End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> class S { int $$x; } </Code> TestPropertyDescriptors(Of EnvDTE80.CodeVariable2)(code) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/EditorFeatures/CSharpTest/CodeActions/Preview/PreviewTests.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings { public partial class PreviewTests : AbstractCSharpCodeActionTest { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeaturesWpf .AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService)) .AddParts( typeof(MockDiagnosticUpdateSourceRegistrationService), typeof(MockPreviewPaneService)); private const string AddedDocumentName = "AddedDocument"; private const string AddedDocumentText = "class C1 {}"; private static string s_removedMetadataReferenceDisplayName = ""; private const string AddedProjectName = "AddedProject"; private static readonly ProjectId s_addedProjectId = ProjectId.CreateNewId(); private const string ChangedDocumentText = "class C {}"; protected override TestComposition GetComposition() => s_composition; protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new MyCodeRefactoringProvider(); private class MyCodeRefactoringProvider : CodeRefactoringProvider { public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var codeAction = new MyCodeAction(context.Document); context.RegisterRefactoring(codeAction, context.Span); return Task.CompletedTask; } private class MyCodeAction : CodeAction { private readonly Document _oldDocument; public MyCodeAction(Document document) => _oldDocument = document; public override string Title { get { return "Title"; } } protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) { var solution = _oldDocument.Project.Solution; // Add a document - This will result in IWpfTextView previews. solution = solution.AddDocument(DocumentId.CreateNewId(_oldDocument.Project.Id, AddedDocumentName), AddedDocumentName, AddedDocumentText); // Remove a reference - This will result in a string preview. var removedReference = _oldDocument.Project.MetadataReferences[_oldDocument.Project.MetadataReferences.Count - 1]; s_removedMetadataReferenceDisplayName = removedReference.Display; solution = solution.RemoveMetadataReference(_oldDocument.Project.Id, removedReference); // Add a project - This will result in a string preview. solution = solution.AddProject(ProjectInfo.Create(s_addedProjectId, VersionStamp.Create(), AddedProjectName, AddedProjectName, LanguageNames.CSharp)); // Change a document - This will result in IWpfTextView previews. solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, CSharpSyntaxTree.ParseText(ChangedDocumentText, cancellationToken: cancellationToken).GetRoot(cancellationToken)); return Task.FromResult(solution); } } } private void GetMainDocumentAndPreviews(TestParameters parameters, TestWorkspace workspace, out Document document, out SolutionPreviewResult previews) { document = GetDocument(workspace); var provider = CreateCodeRefactoringProvider(workspace, parameters); var span = document.GetSyntaxRootAsync().Result.Span; var refactorings = new List<CodeAction>(); var context = new CodeRefactoringContext(document, span, refactorings.Add, CancellationToken.None); provider.ComputeRefactoringsAsync(context).Wait(); var action = refactorings.Single(); var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); previews = editHandler.GetPreviews(workspace, action.GetPreviewOperationsAsync(CancellationToken.None).Result, CancellationToken.None); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/14421")] public async Task TestPickTheRightPreview_NoPreference() { var parameters = new TestParameters(); using var workspace = CreateWorkspaceFromOptions("class D {}", parameters); GetMainDocumentAndPreviews(parameters, workspace, out var document, out var previews); // The changed document comes first. var previewObjects = await previews.GetPreviewsAsync(); var preview = previewObjects[0]; Assert.NotNull(preview); Assert.True(preview is DifferenceViewerPreview); var diffView = preview as DifferenceViewerPreview; var text = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString(); Assert.Equal(ChangedDocumentText, text); diffView.Dispose(); // Then comes the removed metadata reference. preview = previewObjects[1]; Assert.NotNull(preview); Assert.True(preview is string); text = preview as string; Assert.Contains(s_removedMetadataReferenceDisplayName, text, StringComparison.Ordinal); // And finally the added project. preview = previewObjects[2]; Assert.NotNull(preview); Assert.True(preview is string); text = preview as string; Assert.Contains(AddedProjectName, text, StringComparison.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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings { public partial class PreviewTests : AbstractCSharpCodeActionTest { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeaturesWpf .AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService)) .AddParts( typeof(MockDiagnosticUpdateSourceRegistrationService), typeof(MockPreviewPaneService)); private const string AddedDocumentName = "AddedDocument"; private const string AddedDocumentText = "class C1 {}"; private static string s_removedMetadataReferenceDisplayName = ""; private const string AddedProjectName = "AddedProject"; private static readonly ProjectId s_addedProjectId = ProjectId.CreateNewId(); private const string ChangedDocumentText = "class C {}"; protected override TestComposition GetComposition() => s_composition; protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new MyCodeRefactoringProvider(); private class MyCodeRefactoringProvider : CodeRefactoringProvider { public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var codeAction = new MyCodeAction(context.Document); context.RegisterRefactoring(codeAction, context.Span); return Task.CompletedTask; } private class MyCodeAction : CodeAction { private readonly Document _oldDocument; public MyCodeAction(Document document) => _oldDocument = document; public override string Title { get { return "Title"; } } protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) { var solution = _oldDocument.Project.Solution; // Add a document - This will result in IWpfTextView previews. solution = solution.AddDocument(DocumentId.CreateNewId(_oldDocument.Project.Id, AddedDocumentName), AddedDocumentName, AddedDocumentText); // Remove a reference - This will result in a string preview. var removedReference = _oldDocument.Project.MetadataReferences[_oldDocument.Project.MetadataReferences.Count - 1]; s_removedMetadataReferenceDisplayName = removedReference.Display; solution = solution.RemoveMetadataReference(_oldDocument.Project.Id, removedReference); // Add a project - This will result in a string preview. solution = solution.AddProject(ProjectInfo.Create(s_addedProjectId, VersionStamp.Create(), AddedProjectName, AddedProjectName, LanguageNames.CSharp)); // Change a document - This will result in IWpfTextView previews. solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, CSharpSyntaxTree.ParseText(ChangedDocumentText, cancellationToken: cancellationToken).GetRoot(cancellationToken)); return Task.FromResult(solution); } } } private void GetMainDocumentAndPreviews(TestParameters parameters, TestWorkspace workspace, out Document document, out SolutionPreviewResult previews) { document = GetDocument(workspace); var provider = CreateCodeRefactoringProvider(workspace, parameters); var span = document.GetSyntaxRootAsync().Result.Span; var refactorings = new List<CodeAction>(); var context = new CodeRefactoringContext(document, span, refactorings.Add, CancellationToken.None); provider.ComputeRefactoringsAsync(context).Wait(); var action = refactorings.Single(); var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); previews = editHandler.GetPreviews(workspace, action.GetPreviewOperationsAsync(CancellationToken.None).Result, CancellationToken.None); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/14421")] public async Task TestPickTheRightPreview_NoPreference() { var parameters = new TestParameters(); using var workspace = CreateWorkspaceFromOptions("class D {}", parameters); GetMainDocumentAndPreviews(parameters, workspace, out var document, out var previews); // The changed document comes first. var previewObjects = await previews.GetPreviewsAsync(); var preview = previewObjects[0]; Assert.NotNull(preview); Assert.True(preview is DifferenceViewerPreview); var diffView = preview as DifferenceViewerPreview; var text = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString(); Assert.Equal(ChangedDocumentText, text); diffView.Dispose(); // Then comes the removed metadata reference. preview = previewObjects[1]; Assert.NotNull(preview); Assert.True(preview is string); text = preview as string; Assert.Contains(s_removedMetadataReferenceDisplayName, text, StringComparison.Ordinal); // And finally the added project. preview = previewObjects[2]; Assert.NotNull(preview); Assert.True(preview is string); text = preview as string; Assert.Contains(AddedProjectName, text, StringComparison.Ordinal); } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.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.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts #If CODE_STYLE Then Imports Microsoft.CodeAnalysis.Internal.Editing #Else Imports Microsoft.CodeAnalysis.Editing #End If Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSyntaxFacts Inherits AbstractSyntaxFacts Implements ISyntaxFacts Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts Protected Sub New() End Sub Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive Get Return False End Get End Property Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer Get Return CaseInsensitiveComparison.Comparer End Get End Property Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker Get Return SyntaxFactory.ElasticMarker End Get End Property Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed Get Return SyntaxFactory.ElasticCarriageReturnLineFeed End Get End Property Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds Protected Overrides ReadOnly Property DocumentationCommentService As IDocumentationCommentService Get Return VisualBasicDocumentationCommentService.Instance End Get End Property Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer Return False End Function Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression Return False End Function Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration Return False End Function Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord Return False End Function Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct Return False End Function Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken Return SyntaxFactory.ParseToken(text, startStatement:=True) End Function Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia Return SyntaxFactory.ParseLeadingTrivia(text) End Function Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier) Dim needsEscaping = keywordKind <> SyntaxKind.None Return If(needsEscaping, "[" & identifier & "]", identifier) End Function Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return False End Function Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse (IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) End Function Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword Return token.IsContextualKeyword() End Function Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword Return token.IsReservedKeyword() End Function Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword Return token.IsPreprocessorKeyword() End Function Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken) End Function Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace If token.Kind = SyntaxKind.CloseBraceToken Then Dim tuples = token.Parent.GetBraces() openBrace = tuples.openBrace Return openBrace.Kind = SyntaxKind.OpenBraceToken End If Return False End Function Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral If syntaxTree Is Nothing Then Return False End If Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken) End Function Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective Return TypeOf node Is DirectiveTriviaSyntax End Function Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo Select Case node.Kind Case SyntaxKind.ExternalSourceDirectiveTrivia info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False) Return True Case SyntaxKind.EndExternalSourceDirectiveTrivia info = New ExternalSourceInfo(Nothing, True) Return True End Select Return False End Function Public Function IsObjectCreationExpressionType(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsObjectCreationExpressionType Return node.IsParentKind(SyntaxKind.ObjectCreationExpression) AndAlso DirectCast(node.Parent, ObjectCreationExpressionSyntax).Type Is node End Function Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression ' VB doesn't support declaration expressions Return False End Function Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName Return node.IsParentKind(SyntaxKind.Attribute) AndAlso DirectCast(node.Parent, AttributeSyntax).Name Is node End Function Public Function IsRightSideOfQualifiedName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRightSideOfQualifiedName Dim vbNode = TryCast(node, SimpleNameSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsRightSideOfQualifiedName() End Function Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression Dim vbNode = TryCast(node, ExpressionSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName() End Function Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax) Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node End Function Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax)) End Function Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression() End Function Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax) expression = conditionalAccess.Expression operatorToken = conditionalAccess.QuestionMarkToken whenNotNull = conditionalAccess.WhenNotNull End Sub Public Function IsAnonymousFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunction Return TypeOf node Is LambdaExpressionSyntax End Function Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument Dim arg = TryCast(node, SimpleArgumentSyntax) Return arg?.NameColonEquals IsNot Nothing End Function Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node) End Function Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter Return TryCast(node, ParameterSyntax)?.Identifier?.Identifier End Function Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter Return TryCast(node, ParameterSyntax)?.Default End Function Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList Return node.GetParameterList() End Function Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList Return node.IsKind(SyntaxKind.ParameterList) End Function Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember Return HasIncompleteParentMember(node) End Function Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName Dim vbGenericName = TryCast(genericName, GenericNameSyntax) Return If(vbGenericName IsNot Nothing, vbGenericName.Identifier, Nothing) End Function Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node End Function Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment Return False End Function Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement Return False End Function Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement Return TypeOf node Is StatementSyntax End Function Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement Return TypeOf node Is ExecutableStatementSyntax End Function Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody Return TypeOf node Is MethodBlockBaseSyntax End Function Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement Return TryCast(node, ReturnStatementSyntax)?.Expression End Function Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsThisConstructorInitializer() End If Return False End Function Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsBaseConstructorInitializer() End If Return False End Function Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword Select Case token.Kind() Case _ SyntaxKind.JoinKeyword, SyntaxKind.IntoKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword, SyntaxKind.ByKeyword, SyntaxKind.OrderKeyword, SyntaxKind.WhereKeyword, SyntaxKind.OnKeyword, SyntaxKind.FromKeyword, SyntaxKind.WhileKeyword, SyntaxKind.SelectKeyword Return TypeOf token.Parent Is QueryClauseSyntax Case SyntaxKind.GroupKeyword Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation)) Case SyntaxKind.EqualsKeyword Return TypeOf token.Parent Is JoinConditionSyntax Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword Return TypeOf token.Parent Is OrderingSyntax Case SyntaxKind.InKeyword Return TypeOf token.Parent Is CollectionRangeVariableSyntax Case Else Return False End Select End Function Public Function IsThrowExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowExpression ' VB does not support throw expressions currently. Return False End Function Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None End Function Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType = type End Function Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType type = GetPredefinedType(token) Return type <> PredefinedType.None End Function Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType Select Case token.Kind Case SyntaxKind.BooleanKeyword Return PredefinedType.Boolean Case SyntaxKind.ByteKeyword Return PredefinedType.Byte Case SyntaxKind.SByteKeyword Return PredefinedType.SByte Case SyntaxKind.IntegerKeyword Return PredefinedType.Int32 Case SyntaxKind.UIntegerKeyword Return PredefinedType.UInt32 Case SyntaxKind.ShortKeyword Return PredefinedType.Int16 Case SyntaxKind.UShortKeyword Return PredefinedType.UInt16 Case SyntaxKind.LongKeyword Return PredefinedType.Int64 Case SyntaxKind.ULongKeyword Return PredefinedType.UInt64 Case SyntaxKind.SingleKeyword Return PredefinedType.Single Case SyntaxKind.DoubleKeyword Return PredefinedType.Double Case SyntaxKind.DecimalKeyword Return PredefinedType.Decimal Case SyntaxKind.StringKeyword Return PredefinedType.String Case SyntaxKind.CharKeyword Return PredefinedType.Char Case SyntaxKind.ObjectKeyword Return PredefinedType.Object Case SyntaxKind.DateKeyword Return PredefinedType.DateTime Case Else Return PredefinedType.None End Select End Function Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None End Function Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op End Function Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator op = GetPredefinedOperator(token) Return op <> PredefinedOperator.None End Function Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator Select Case token.Kind Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken Return PredefinedOperator.Addition Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken Return PredefinedOperator.Subtraction Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword Return PredefinedOperator.BitwiseAnd Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword Return PredefinedOperator.BitwiseOr Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken Return PredefinedOperator.Concatenate Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken Return PredefinedOperator.Division Case SyntaxKind.EqualsToken Return PredefinedOperator.Equality Case SyntaxKind.XorKeyword Return PredefinedOperator.ExclusiveOr Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken Return PredefinedOperator.Exponent Case SyntaxKind.GreaterThanToken Return PredefinedOperator.GreaterThan Case SyntaxKind.GreaterThanEqualsToken Return PredefinedOperator.GreaterThanOrEqual Case SyntaxKind.LessThanGreaterThanToken Return PredefinedOperator.Inequality Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken Return PredefinedOperator.IntegerDivision Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken Return PredefinedOperator.LeftShift Case SyntaxKind.LessThanToken Return PredefinedOperator.LessThan Case SyntaxKind.LessThanEqualsToken Return PredefinedOperator.LessThanOrEqual Case SyntaxKind.LikeKeyword Return PredefinedOperator.Like Case SyntaxKind.NotKeyword Return PredefinedOperator.Complement Case SyntaxKind.ModKeyword Return PredefinedOperator.Modulus Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken Return PredefinedOperator.Multiplication Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken Return PredefinedOperator.RightShift Case Else Return PredefinedOperator.None End Select End Function Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText Return SyntaxFacts.GetText(CType(kind, SyntaxKind)) End Function Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter Return SyntaxFacts.IsIdentifierPartCharacter(c) End Function Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter Return SyntaxFacts.IsIdentifierStartCharacter(c) End Function Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter Return c = "["c OrElse c = "]"c End Function Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier Dim token = SyntaxFactory.ParseToken(identifier) ' TODO: There is no way to get the diagnostics to see if any are actually errors? Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length End Function Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]" End Function Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter Return c = "%"c OrElse c = "&"c OrElse c = "@"c OrElse c = "!"c OrElse c = "#"c OrElse c = "$"c End Function Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence Return False ' VB does not support identifiers with escaped unicode characters End Function Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral Select Case token.Kind() Case _ SyntaxKind.IntegerLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.FloatingLiteralToken, SyntaxKind.DateLiteralToken, SyntaxKind.StringLiteralToken, SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.TrueKeyword, SyntaxKind.FalseKeyword, SyntaxKind.NothingKeyword Return True End Select Return False End Function Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken) End Function Public Function IsNumericLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNumericLiteralExpression Return If(node Is Nothing, False, node.IsKind(SyntaxKind.NumericLiteralExpression)) End Function Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken Return Me.IsWord(token) OrElse Me.IsLiteral(token) OrElse Me.IsOperator(token) End Function Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression Return False End Function Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName Dim simpleName = TryCast(node, SimpleNameSyntax) If simpleName IsNot Nothing Then name = simpleName.Identifier.ValueText arity = simpleName.Arity End If End Sub Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric Return name.IsKind(SyntaxKind.GenericName) End Function Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget) End Function Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding ' Member bindings are a C# concept. Return Nothing End Function Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression ' Member bindings are a C# concept. Return Nothing End Function Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression Dim invocation = TryCast(node, InvocationExpressionSyntax) If invocation IsNot Nothing Then expression = invocation?.Expression argumentList = invocation?.ArgumentList Return End If If node.Kind() = SyntaxKind.DictionaryAccessExpression Then GetPartsOfMemberAccessExpression(node, expression, argumentList) Return End If Return End Sub Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation Return TryCast(node, InterpolationSyntax)?.Expression End Function Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext Return SyntaxFacts.IsInNamespaceOrTypeContext(node) End Function Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing End Function Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext Return node.IsInStaticContext() End Function Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument Return TryCast(node, ArgumentSyntax).GetArgumentExpression() End Function Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument ' TODO(cyrusn): Consider the method this argument is passed to, to determine this. Return RefKind.None End Function Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument Return TypeOf node Is ArgumentSyntax End Function Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument Dim argument = TryCast(node, ArgumentSyntax) Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted End Function Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext Return node.IsInConstantContext() End Function Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock) End Function Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext Return False End Function Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute Return DirectCast(node, AttributeSyntax).Name End Function Public Function GetExpressionOfParenthesizedExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfParenthesizedExpression Return DirectCast(node, ParenthesizedExpressionSyntax).Expression End Function Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier Dim identifierName = TryCast(node, IdentifierNameSyntax) Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute) End Function Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration If root Is Nothing Then Throw New ArgumentNullException(NameOf(root)) End If If position < 0 OrElse position > root.Span.End Then Throw New ArgumentOutOfRangeException(NameOf(position)) End If Return root. FindToken(position). GetAncestors(Of SyntaxNode)(). FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax) End Function Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration If node Is Nothing Then Throw New ArgumentNullException(NameOf(node)) End If Dim parent = node.Parent While node IsNot Nothing If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then Return node End If node = node.Parent End While Return Nothing End Function Public Function FindTokenOnLeftOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnLeftOfPosition Return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function FindTokenOnRightOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnRightOfPosition Return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim unused As SyntaxNode = Nothing Return IsMemberInitializerNamedAssignmentIdentifier(node, unused) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier( node As SyntaxNode, ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim identifier = TryCast(node, IdentifierNameSyntax) If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then ' .parent is the NamedField. ' .parent.parent is the ObjectInitializer. ' .parent.parent.parent will be the ObjectCreationExpression. initializedInstance = identifier.Parent.Parent.Parent Return True End If Return False End Function Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern Return False End Function Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause Return False End Function Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression ' VB doesn't have a specialized node for element access. Instead, it just uses an ' invocation expression or dictionary access expression. Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression End Function Public Sub GetPartsOfParenthesizedExpression( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax) openParen = parenthesizedExpression.OpenParenToken expression = parenthesizedExpression.Expression closeParen = parenthesizedExpression.CloseParenToken End Sub Public Function IsTypeNamedVarInVariableOrFieldDeclaration(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedVarInVariableOrFieldDeclaration Return False End Function Public Function IsTypeNamedDynamic(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedDynamic Return False End Function Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef Return False End Function Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration Contract.ThrowIfNull(root, NameOf(root)) Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position)) Dim [end] = root.FullSpan.End If [end] = 0 Then ' empty file Return Nothing End If ' make sure position doesn't touch end of root position = Math.Min(position, [end] - 1) Dim node = root.FindToken(position).Parent While node IsNot Nothing If useFullSpan OrElse node.Span.Contains(position) Then If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return node End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return node End If If TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax OrElse TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is FieldDeclarationSyntax Then Return node End If End If node = node.Parent End While Return Nothing End Function Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember ' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and ' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things ' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level ' members. If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return True End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return True End If If TypeOf node Is DeclareStatementSyntax Then Return True End If Return TypeOf node Is ConstructorBlockSyntax OrElse TypeOf node Is MethodBlockSyntax OrElse TypeOf node Is OperatorBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is EnumMemberDeclarationSyntax OrElse TypeOf node Is FieldDeclarationSyntax End Function Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding Dim member = GetContainingMemberDeclaration(node, node.SpanStart) If member Is Nothing Then Return Nothing End If ' TODO: currently we only support method for now Dim method = TryCast(member, MethodBlockBaseSyntax) If method IsNot Nothing Then If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then Return Nothing End If ' We don't want to include the BlockStatement or any trailing trivia up to and including its statement ' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up ' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start ' of the EndBlockStatements leading trivia. Dim firstStatement = method.Statements.FirstOrDefault() Dim spanStart = If(firstStatement IsNot Nothing, firstStatement.FullSpan.Start, method.EndBlockStatement.FullSpan.Start) Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart) End If Return Nothing End Function Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody Dim method = TryCast(node, MethodBlockBaseSyntax) If method IsNot Nothing Then Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span) End If Dim [event] = TryCast(node, EventBlockSyntax) If [event] IsNot Nothing Then Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span) End If Dim [property] = TryCast(node, PropertyBlockSyntax) If [property] IsNot Nothing Then Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span) End If Dim field = TryCast(node, FieldDeclarationSyntax) If field IsNot Nothing Then Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span) End If Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax) If [enum] IsNot Nothing Then Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span) End If Dim propStatement = TryCast(node, PropertyStatementSyntax) If propStatement IsNot Nothing Then Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span) End If Return False End Function Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean If innerSpan.IsEmpty Then Return outerSpan.Contains(innerSpan.Start) End If Return outerSpan.Contains(innerSpan) End Function Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=True, methodLevel:=True) Return list End Function Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=False, methodLevel:=True) Return list End Function Public Function IsClassDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsClassDeclaration Return node.IsKind(SyntaxKind.ClassBlock) End Function Public Function IsNamespaceDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamespaceDeclaration Return node.IsKind(SyntaxKind.NamespaceBlock) End Function Public Function GetNameOfNamespaceDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfNamespaceDeclaration If IsNamespaceDeclaration(node) Then Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name End If Return Nothing End Function Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration Return DirectCast(typeDeclaration, TypeBlockSyntax).Members End Function Public Function GetMembersOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfNamespaceDeclaration Return DirectCast(namespaceDeclaration, NamespaceBlockSyntax).Members End Function Public Function GetMembersOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Members End Function Public Function GetImportsOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfNamespaceDeclaration 'Visual Basic doesn't have namespaced imports Return Nothing End Function Public Function GetImportsOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Imports End Function Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers Return TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax End Function Private Const s_dotToken As String = "." Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName If node Is Nothing Then Return String.Empty End If Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder ' member keyword (if any) Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then Dim keywordToken = memberDeclaration.GetMemberKeywordToken() If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then builder.Append(keywordToken.Text) builder.Append(" "c) End If End If Dim names = ArrayBuilder(Of String).GetInstance() ' containing type(s) Dim parent = node.Parent While TypeOf parent Is TypeBlockSyntax names.Push(GetName(parent, options, containsGlobalKeyword:=False)) parent = parent.Parent End While If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then ' containing namespace(s) in source (if any) Dim containsGlobalKeyword As Boolean = False While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock names.Push(GetName(parent, options, containsGlobalKeyword)) parent = parent.Parent End While ' root namespace (if any) If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then builder.Append(rootNamespace) builder.Append(s_dotToken) End If End If While Not names.IsEmpty() Dim name = names.Pop() If name IsNot Nothing Then builder.Append(name) builder.Append(s_dotToken) End If End While names.Free() ' name (include generic type parameters) builder.Append(GetName(node, options, containsGlobalKeyword:=False)) ' parameter list (if any) If (options And DisplayNameOptions.IncludeParameters) <> 0 Then builder.Append(memberDeclaration.GetParameterList()) End If ' As clause (if any) If (options And DisplayNameOptions.IncludeType) <> 0 Then Dim asClause = memberDeclaration.GetAsClause() If asClause IsNot Nothing Then builder.Append(" "c) builder.Append(asClause) End If End If Return pooled.ToStringAndFree() End Function Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String Const missingTokenPlaceholder As String = "?" Select Case node.Kind() Case SyntaxKind.CompilationUnit Return Nothing Case SyntaxKind.IdentifierName Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text) Case SyntaxKind.IncompleteMember Return missingTokenPlaceholder Case SyntaxKind.NamespaceBlock Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name If nameSyntax.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return Nothing Else Return GetName(nameSyntax, options, containsGlobalKeyword) End If Case SyntaxKind.QualifiedName Dim qualified = CType(node, QualifiedNameSyntax) If qualified.Left.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified Else Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword) End If End Select Dim name As String = Nothing Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If memberDeclaration IsNot Nothing Then Dim nameToken = memberDeclaration.GetNameToken() If nameToken <> Nothing Then name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text) If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder builder.Append(name) AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()) name = pooled.ToStringAndFree() End If End If End If Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString()) Return name End Function Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax) If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then builder.Append("(Of ") builder.Append(typeParameterList.Parameters(0).Identifier.Text) For i = 1 To typeParameterList.Parameters.Count - 1 builder.Append(", ") builder.Append(typeParameterList.Parameters(i).Identifier.Text) Next builder.Append(")"c) End If End Sub Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean) Debug.Assert(topLevel OrElse methodLevel) For Each member In node.GetMembers() If IsTopLevelNodeWithMembers(member) Then If topLevel Then list.Add(member) End If AppendMembers(member, list, topLevel, methodLevel) Continue For End If If methodLevel AndAlso IsMethodLevelMember(member) Then list.Add(member) End If Next End Sub Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent Dim node = token.Parent While node IsNot Nothing Dim parent = node.Parent ' If this node is on the left side of a member access expression, don't ascend ' further or we'll end up binding to something else. Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then If memberAccess.Expression Is node Then Exit While End If End If ' If this node is on the left side of a qualified name, don't ascend ' further or we'll end up binding to something else. Dim qualifiedName = TryCast(parent, QualifiedNameSyntax) If qualifiedName IsNot Nothing Then If qualifiedName.Left Is node Then Exit While End If End If ' If this node is the type of an object creation expression, return the ' object creation expression. Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax) If objectCreation IsNot Nothing Then If objectCreation.Type Is node Then node = parent Exit While End If End If ' The inside of an interpolated string is treated as its own token so we ' need to force navigation to the parent expression syntax. If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then node = parent Exit While End If ' If this node is not parented by a name, we're done. Dim name = TryCast(parent, NameSyntax) If name Is Nothing Then Exit While End If node = parent End While Return node End Function Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors Dim compilationUnit = TryCast(root, CompilationUnitSyntax) If compilationUnit Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If Dim constructors = New List(Of SyntaxNode)() AppendConstructors(compilationUnit.Members, constructors, cancellationToken) Return constructors End Function Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken) For Each member As StatementSyntax In members cancellationToken.ThrowIfCancellationRequested() Dim constructor = TryCast(member, ConstructorBlockSyntax) If constructor IsNot Nothing Then constructors.Add(constructor) Continue For End If Dim [namespace] = TryCast(member, NamespaceBlockSyntax) If [namespace] IsNot Nothing Then AppendConstructors([namespace].Members, constructors, cancellationToken) End If Dim [class] = TryCast(member, ClassBlockSyntax) If [class] IsNot Nothing Then AppendConstructors([class].Members, constructors, cancellationToken) End If Dim [struct] = TryCast(member, StructureBlockSyntax) If [struct] IsNot Nothing Then AppendConstructors([struct].Members, constructors, cancellationToken) End If Next End Sub Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition Dim trivia = tree.FindTriviaToLeft(position, cancellationToken) If trivia.Kind = SyntaxKind.DisabledTextTrivia Then Return trivia.FullSpan End If Return Nothing End Function Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument If TryCast(argument, ArgumentSyntax)?.IsNamed Then Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText End If Return String.Empty End Function Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument ' All argument types are ArgumentSyntax in VB. Return GetNameForArgument(argument) End Function Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot() End Function Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Right, TryCast(node, MemberAccessExpressionSyntax)?.Name) End Function Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Left, TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)) End Function Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing End Function Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement End Function Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement End Function Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement End Function Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment Return TryCast(node, AssignmentStatementSyntax)?.Right End Function Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator Return node.IsKind(SyntaxKind.InferredFieldInitializer) End Function Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression Return False End Function Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression Return False End Function Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value End Function Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse token.Kind = SyntaxKind.FloatingLiteralToken OrElse token.Kind = SyntaxKind.IntegerLiteralToken End Function Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral ' VB does not have verbatim strings Return False End Function Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression Return GetArgumentsOfArgumentList(TryCast(node, InvocationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression Return GetArgumentsOfArgumentList(TryCast(node, ObjectCreationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList Dim arguments = TryCast(node, ArgumentListSyntax)?.Arguments Return If(arguments.HasValue, arguments.Value, Nothing) End Function Public Function GetArgumentListOfInvocationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfInvocationExpression Return DirectCast(node, InvocationExpressionSyntax).ArgumentList End Function Public Function GetArgumentListOfObjectCreationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfObjectCreationExpression Return DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList End Function Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine Return node.ConvertToSingleLine(useElasticTrivia) End Function Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return node.IsKind(SyntaxKind.DocumentationCommentTrivia) End Function Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport Return node.IsKind(SyntaxKind.ImportsStatement) End Function Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword) End Function Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword) End Function Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean If node.IsKind(SyntaxKind.Attribute) Then Dim attributeNode = CType(node, AttributeSyntax) If attributeNode.Target IsNot Nothing Then Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget) End If End If Return False End Function Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration ' From the Visual Basic language spec: ' NamespaceMemberDeclaration := ' NamespaceDeclaration | ' TypeDeclaration ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration ' ClassMemberDeclaration ::= ' NonModuleDeclaration | ' EventMemberDeclaration | ' VariableMemberDeclaration | ' ConstantMemberDeclaration | ' MethodMemberDeclaration | ' PropertyMemberDeclaration | ' ConstructorMemberDeclaration | ' OperatorDeclaration Select Case node.Kind() ' Because fields declarations can define multiple symbols "Public a, b As Integer" ' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. Case SyntaxKind.VariableDeclarator If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then Return True End If Return False Case SyntaxKind.NamespaceStatement, SyntaxKind.NamespaceBlock, SyntaxKind.ModuleStatement, SyntaxKind.ModuleBlock, SyntaxKind.EnumStatement, SyntaxKind.EnumBlock, SyntaxKind.StructureStatement, SyntaxKind.StructureBlock, SyntaxKind.InterfaceStatement, SyntaxKind.InterfaceBlock, SyntaxKind.ClassStatement, SyntaxKind.ClassBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.EventStatement, SyntaxKind.EventBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.FieldDeclaration, SyntaxKind.SubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.FunctionBlock, SyntaxKind.PropertyStatement, SyntaxKind.PropertyBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.SubNewStatement, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorStatement, SyntaxKind.OperatorBlock Return True End Select Return False End Function ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock, SyntaxKind.ModuleBlock, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return True End Select Return False End Function Public Function GetObjectCreationInitializer(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationInitializer Return DirectCast(node, ObjectCreationExpressionSyntax).Initializer End Function Public Function GetObjectCreationType(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationType Return DirectCast(node, ObjectCreationExpressionSyntax).Type End Function Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement Return node.IsKind(SyntaxKind.SimpleAssignmentStatement) End Function Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement ' VB only has assignment statements, so this can just delegate to that helper GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right) End Sub Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement Dim assignment = DirectCast(statement, AssignmentStatementSyntax) left = assignment.Left operatorToken = assignment.OperatorToken right = assignment.Right End Sub Public Function GetNameOfMemberAccessExpression(memberAccessExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberAccessExpression Return DirectCast(memberAccessExpression, MemberAccessExpressionSyntax).Name End Function Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName Return DirectCast(node, SimpleNameSyntax).Identifier End Function Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier End Function Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter Return DirectCast(node, ParameterSyntax).Identifier.Identifier End Function Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier End Function Public Function IsLocalFunctionStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunctionStatement ' VB does not have local functions Return False End Function Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators. Contains(DirectCast(declarator, VariableDeclaratorSyntax)) End Function Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(token1, token2) End Function Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(node1, node2) End Function Public Function IsExpressionOfInvocationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfInvocationExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, InvocationExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfAwaitExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfAwaitExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, AwaitExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfMemberAccessExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, MemberAccessExpressionSyntax)?.Expression Is node End Function Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression Return DirectCast(node, AwaitExpressionSyntax).Expression End Function Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node End Function Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement Return DirectCast(node, ExpressionStatementSyntax).Expression End Function Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression Return TypeOf node Is BinaryExpressionSyntax End Function Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression Return node.IsKind(SyntaxKind.TypeOfIsExpression) End Function Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax) left = binaryExpression.Left operatorToken = binaryExpression.OperatorToken right = binaryExpression.Right End Sub Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax) condition = conditionalExpression.Condition whenTrue = conditionalExpression.WhenTrue whenFalse = conditionalExpression.WhenFalse End Sub Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node) End Function Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression Dim tupleExpr = DirectCast(node, TupleExpressionSyntax) openParen = tupleExpr.OpenParenToken arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax)) closeParen = tupleExpr.CloseParenToken End Sub Public Function GetOperandOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetOperandOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).Operand End Function Public Function GetOperatorTokenOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetOperatorTokenOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).OperatorToken End Function Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax) expression = memberAccess.Expression operatorToken = memberAccess.OperatorToken name = memberAccess.Name End Sub Public Function GetNextExecutableStatement(statement As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNextExecutableStatement Return DirectCast(statement, StatementSyntax).GetNextStatement()?.FirstAncestorOrSelf(Of ExecutableStatementSyntax) End Function Public Overrides Function IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Overrides Function IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have multi-line comments. Return False End Function Public Overrides Function IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Overrides Function IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have multi-line comments. Return False End Function Public Overrides Function IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have shebang directives. Return False End Function Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind()) End Function Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic Return trivia.IsElastic() End Function Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes) End Function Public Function IsOnTypeHeader( root As SyntaxNode, position As Integer, fullHeader As Boolean, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnTypeHeader Dim typeBlock = TryGetAncestorForLocation(Of TypeBlockSyntax)(root, position) If typeBlock Is Nothing Then Return Nothing End If Dim typeStatement = typeBlock.BlockStatement typeDeclaration = typeStatement Dim lastToken = If(typeStatement.TypeParameterList?.GetLastToken(), typeStatement.Identifier) If fullHeader Then lastToken = If(typeBlock.Implements.LastOrDefault()?.GetLastToken(), If(typeBlock.Inherits.LastOrDefault()?.GetLastToken(), lastToken)) End If Return IsOnHeader(root, position, typeBlock, lastToken) End Function Public Function IsOnPropertyDeclarationHeader(root As SyntaxNode, position As Integer, ByRef propertyDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnPropertyDeclarationHeader Dim node = TryGetAncestorForLocation(Of PropertyStatementSyntax)(root, position) propertyDeclaration = node If propertyDeclaration Is Nothing Then Return False End If If node.AsClause IsNot Nothing Then Return IsOnHeader(root, position, node, node.AsClause) End If Return IsOnHeader(root, position, node, node.Identifier) End Function Public Function IsOnParameterHeader(root As SyntaxNode, position As Integer, ByRef parameter As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnParameterHeader Dim node = TryGetAncestorForLocation(Of ParameterSyntax)(root, position) parameter = node If parameter Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnMethodHeader(root As SyntaxNode, position As Integer, ByRef method As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnMethodHeader Dim node = TryGetAncestorForLocation(Of MethodStatementSyntax)(root, position) method = node If method Is Nothing Then Return False End If If node.HasReturnType() Then Return IsOnHeader(root, position, method, node.GetReturnType()) End If If node.ParameterList IsNot Nothing Then Return IsOnHeader(root, position, method, node.ParameterList) End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnLocalFunctionHeader(root As SyntaxNode, position As Integer, ByRef localFunction As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalFunctionHeader ' No local functions in VisualBasic Return False End Function Public Function IsOnLocalDeclarationHeader(root As SyntaxNode, position As Integer, ByRef localDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalDeclarationHeader Dim node = TryGetAncestorForLocation(Of LocalDeclarationStatementSyntax)(root, position) localDeclaration = node If localDeclaration Is Nothing Then Return False End If Dim initializersExpressions = node.Declarators. Where(Function(d) d.Initializer IsNot Nothing). SelectAsArray(Function(initialized) initialized.Initializer.Value) Return IsOnHeader(root, position, node, node, initializersExpressions) End Function Public Function IsOnIfStatementHeader(root As SyntaxNode, position As Integer, ByRef ifStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnIfStatementHeader ifStatement = Nothing Dim multipleLineNode = TryGetAncestorForLocation(Of MultiLineIfBlockSyntax)(root, position) If multipleLineNode IsNot Nothing Then ifStatement = multipleLineNode Return IsOnHeader(root, position, multipleLineNode.IfStatement, multipleLineNode.IfStatement) End If Dim singleLineNode = TryGetAncestorForLocation(Of SingleLineIfStatementSyntax)(root, position) If singleLineNode IsNot Nothing Then ifStatement = singleLineNode Return IsOnHeader(root, position, singleLineNode, singleLineNode.Condition) End If Return False End Function Public Function IsOnWhileStatementHeader(root As SyntaxNode, position As Integer, ByRef whileStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnWhileStatementHeader whileStatement = Nothing Dim whileBlock = TryGetAncestorForLocation(Of WhileBlockSyntax)(root, position) If whileBlock IsNot Nothing Then whileStatement = whileBlock Return IsOnHeader(root, position, whileBlock.WhileStatement, whileBlock.WhileStatement) End If Return False End Function Public Function IsOnForeachHeader(root As SyntaxNode, position As Integer, ByRef foreachStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnForeachHeader Dim node = TryGetAncestorForLocation(Of ForEachBlockSyntax)(root, position) foreachStatement = node If foreachStatement Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node.ForEachStatement) End Function Public Function IsBetweenTypeMembers(sourceText As SourceText, root As SyntaxNode, position As Integer, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBetweenTypeMembers Dim token = root.FindToken(position) Dim typeDecl = token.GetAncestor(Of TypeBlockSyntax) typeDeclaration = typeDecl If typeDecl IsNot Nothing Then Dim start = If(typeDecl.Implements.LastOrDefault()?.Span.End, If(typeDecl.Inherits.LastOrDefault()?.Span.End, typeDecl.BlockStatement.Span.End)) If position >= start AndAlso position <= typeDecl.EndBlockStatement.Span.Start Then Dim line = sourceText.Lines.GetLineFromPosition(position) If Not line.IsEmptyOrWhitespace() Then Return False End If Dim member = typeDecl.Members.FirstOrDefault(Function(d) d.FullSpan.Contains(position)) If member Is Nothing Then ' There are no members, Or we're after the last member. Return True Else ' We're within a member. Make sure we're in the leading whitespace of ' the member. If position < member.SpanStart Then For Each trivia In member.GetLeadingTrivia() If Not trivia.IsWhitespaceOrEndOfLine() Then Return False End If If trivia.FullSpan.Contains(position) Then Return True End If Next End If End If End If End If Return False End Function Private Function ISyntaxFacts_GetFileBanner(root As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner Return GetFileBanner(root) End Function Private Function ISyntaxFacts_GetFileBanner(firstToken As SyntaxToken) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner Return GetFileBanner(firstToken) End Function Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean Return token.ContainsInterleavedDirective(span, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(node, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(nodes, cancellationToken) End Function Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia End Function Private Function ISyntaxFacts_GetBannerText(documentationCommentTriviaSyntax As SyntaxNode, maxBannerLength As Integer, cancellationToken As CancellationToken) As String Implements ISyntaxFacts.GetBannerText Return GetBannerText(documentationCommentTriviaSyntax, maxBannerLength, cancellationToken) End Function Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers Return node.GetModifiers() End Function Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers Return node.WithModifiers(modifiers) End Function Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression Return TypeOf node Is LiteralExpressionSyntax End Function Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators End Function Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Initializer End Function Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator Dim declarator = DirectCast(node, VariableDeclaratorSyntax) Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type End Function Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause Return DirectCast(node, EqualsValueSyntax).Value End Function Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock ' VB has no equivalent of curly braces. Return False End Function Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock Return node.IsExecutableBlock() End Function Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements Return node.GetExecutableBlockStatements() End Function Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock Return nodes.FindInnermostCommonExecutableBlock() End Function Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer Return IsExecutableBlock(node) End Function Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements Return GetExecutableBlockStatements(node) End Function Private Function ISyntaxFacts_GetLeadingBlankLines(node As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetLeadingBlankLines Return MyBase.GetLeadingBlankLines(node) End Function Private Function ISyntaxFacts_GetNodeWithoutLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As TSyntaxNode Implements ISyntaxFacts.GetNodeWithoutLeadingBlankLines Return MyBase.GetNodeWithoutLeadingBlankLines(node) End Function Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression Return node.Kind = SyntaxKind.CTypeExpression End Function Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression Return node.Kind = SyntaxKind.DirectCastExpression End Function Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression Dim cast = DirectCast(node, DirectCastExpressionSyntax) type = cast.Type expression = cast.Expression End Sub Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation Throw New NotImplementedException() End Function Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride If token.Kind() = SyntaxKind.OverridesKeyword Then Dim parent = token.Parent Select Case parent.Kind() Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(parent, MethodStatementSyntax) Return method.Identifier Case SyntaxKind.PropertyStatement Dim [property] = DirectCast(parent, PropertyStatementSyntax) Return [property].Identifier End Select End If Return Nothing End Function Public Shadows Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.SpansPreprocessorDirective Return MyBase.SpansPreprocessorDirective(nodes) End Function Public Shadows Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean Return MyBase.SpansPreprocessorDirective(tokens) End Function Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression Dim invocation = DirectCast(node, InvocationExpressionSyntax) expression = invocation.Expression argumentList = invocation.ArgumentList End Sub Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression ' Does not exist in VB. Return False End Function Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists Return node.GetAttributeLists() End Function Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective Dim importStatement = TryCast(node, ImportsStatementSyntax) If (importStatement IsNot Nothing) Then For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then Return True End If End If Next End If Return False End Function Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax Dim xmlElement = TryCast(node, XmlElementSyntax) If xmlElement IsNot Nothing Then Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax) Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName End If Return False End Function Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return documentationCommentTrivia.Content End If Return Nothing End Function Public Overrides Function CanHaveAccessibility(declaration As SyntaxNode) As Boolean Implements ISyntaxFacts.CanHaveAccessibility Select Case declaration.Kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement, SyntaxKind.StructureBlock, SyntaxKind.StructureStatement, SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement, SyntaxKind.EnumBlock, SyntaxKind.EnumStatement, SyntaxKind.ModuleBlock, SyntaxKind.ModuleStatement, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.FieldDeclaration, SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubStatement, SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement, SyntaxKind.EventBlock, SyntaxKind.EventStatement, SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return True Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement ' Shared constructor cannot have modifiers in VB. ' Module constructors are implicitly Shared and can't have accessibility modifier. Return Not declaration.GetModifiers().Any(SyntaxKind.SharedKeyword) AndAlso Not declaration.Parent.IsKind(SyntaxKind.ModuleBlock) Case SyntaxKind.ModifiedIdentifier Return If(IsChildOf(declaration, SyntaxKind.VariableDeclarator), CanHaveAccessibility(declaration.Parent), False) Case SyntaxKind.VariableDeclarator Return If(IsChildOfVariableDeclaration(declaration), CanHaveAccessibility(declaration.Parent), False) Case Else Return False End Select End Function Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind) End Function Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement) End Function Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Implements ISyntaxFacts.GetAccessibility If Not CanHaveAccessibility(declaration) Then Return Accessibility.NotApplicable End If Dim tokens = GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return acc End Function Public Overrides Function GetModifierTokens(declaration As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifierTokens Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).Modifiers Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).Modifiers Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).Modifiers Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Modifiers Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).Modifiers Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.Modifiers Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).Modifiers Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Modifiers Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Modifiers Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Modifiers Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).Modifiers Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Modifiers Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Modifiers Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).Modifiers Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Modifiers Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Modifiers Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.LocalDeclarationStatement Return DirectCast(declaration, LocalDeclarationStatementSyntax).Modifiers Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return GetModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).Modifiers Case Else Return Nothing End Select End Function Public Overrides Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean) Implements ISyntaxFacts.GetAccessibilityAndModifiers accessibility = Accessibility.NotApplicable modifiers = DeclarationModifiers.None isDefault = False For Each token In modifierTokens Select Case token.Kind Case SyntaxKind.DefaultKeyword isDefault = True Case SyntaxKind.PublicKeyword accessibility = Accessibility.Public Case SyntaxKind.PrivateKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Private End If Case SyntaxKind.FriendKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedOrFriend Else accessibility = Accessibility.Friend End If Case SyntaxKind.ProtectedKeyword If accessibility = Accessibility.Friend Then accessibility = Accessibility.ProtectedOrFriend ElseIf accessibility = Accessibility.Private Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Protected End If Case SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword modifiers = modifiers Or DeclarationModifiers.Abstract Case SyntaxKind.ShadowsKeyword modifiers = modifiers Or DeclarationModifiers.[New] Case SyntaxKind.OverridesKeyword modifiers = modifiers Or DeclarationModifiers.Override Case SyntaxKind.OverridableKeyword modifiers = modifiers Or DeclarationModifiers.Virtual Case SyntaxKind.SharedKeyword modifiers = modifiers Or DeclarationModifiers.Static Case SyntaxKind.AsyncKeyword modifiers = modifiers Or DeclarationModifiers.Async Case SyntaxKind.ConstKeyword modifiers = modifiers Or DeclarationModifiers.Const Case SyntaxKind.ReadOnlyKeyword modifiers = modifiers Or DeclarationModifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword modifiers = modifiers Or DeclarationModifiers.WriteOnly Case SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword modifiers = modifiers Or DeclarationModifiers.Sealed Case SyntaxKind.WithEventsKeyword modifiers = modifiers Or DeclarationModifiers.WithEvents Case SyntaxKind.PartialKeyword modifiers = modifiers Or DeclarationModifiers.Partial End Select Next End Sub Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Implements ISyntaxFacts.GetDeclarationKind Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DeclarationKind.CompilationUnit Case SyntaxKind.NamespaceBlock Return DeclarationKind.Namespace Case SyntaxKind.ImportsStatement Return DeclarationKind.NamespaceImport Case SyntaxKind.ClassBlock Return DeclarationKind.Class Case SyntaxKind.StructureBlock Return DeclarationKind.Struct Case SyntaxKind.InterfaceBlock Return DeclarationKind.Interface Case SyntaxKind.EnumBlock Return DeclarationKind.Enum Case SyntaxKind.EnumMemberDeclaration Return DeclarationKind.EnumMember Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationKind.Delegate Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DeclarationKind.Method Case SyntaxKind.FunctionStatement If Not IsChildOf(declaration, SyntaxKind.FunctionBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.SubStatement If Not IsChildOf(declaration, SyntaxKind.SubBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.ConstructorBlock Return DeclarationKind.Constructor Case SyntaxKind.PropertyBlock If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If End If Case SyntaxKind.OperatorBlock Return DeclarationKind.Operator Case SyntaxKind.OperatorStatement If Not IsChildOf(declaration, SyntaxKind.OperatorBlock) Then Return DeclarationKind.Operator End If Case SyntaxKind.EventBlock Return DeclarationKind.CustomEvent Case SyntaxKind.EventStatement If Not IsChildOf(declaration, SyntaxKind.EventBlock) Then Return DeclarationKind.Event End If Case SyntaxKind.Parameter Return DeclarationKind.Parameter Case SyntaxKind.FieldDeclaration Return DeclarationKind.Field Case SyntaxKind.LocalDeclarationStatement If GetDeclarationCount(declaration) = 1 Then Return DeclarationKind.Variable End If Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then If IsChildOf(declaration.Parent, SyntaxKind.FieldDeclaration) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Field ElseIf IsChildOf(declaration.Parent, SyntaxKind.LocalDeclarationStatement) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Variable End If End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list Is Nothing OrElse list.Attributes.Count > 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.GetAccessorBlock Return DeclarationKind.GetAccessor Case SyntaxKind.SetAccessorBlock Return DeclarationKind.SetAccessor Case SyntaxKind.AddHandlerAccessorBlock Return DeclarationKind.AddAccessor Case SyntaxKind.RemoveHandlerAccessorBlock Return DeclarationKind.RemoveAccessor Case SyntaxKind.RaiseEventAccessorBlock Return DeclarationKind.RaiseAccessor End Select Return DeclarationKind.None End Function Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer Dim count As Integer = 0 For i = 0 To nodes.Count - 1 count = count + GetDeclarationCount(nodes(i)) Next Return count End Function Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Select Case node.Kind Case SyntaxKind.FieldDeclaration Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Count Case SyntaxKind.AttributesStatement Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Return DirectCast(node, AttributeListSyntax).Attributes.Count Case SyntaxKind.ImportsStatement Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count End Select Return 1 End Function Private Shared Function IsIndexer(declaration As SyntaxNode) As Boolean Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim p = DirectCast(declaration, PropertyBlockSyntax).PropertyStatement Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then Dim p = DirectCast(declaration, PropertyStatementSyntax) Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) End If End Select Return False End Function Public Function IsImplicitObjectCreation(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsImplicitObjectCreation Return False End Function Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern Return False End Function Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression Return False End Function Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern Return False End Function Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern Return False End Function Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern Return False End Function Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern Return False End Function Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern Return False End Function Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern Return False End Function Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern Return False End Function Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern Return False End Function Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern Return False End Function Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern Return False End Function Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern Return False End Function Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern Return False End Function Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression Throw ExceptionUtilities.Unreachable End Sub Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern Throw ExceptionUtilities.Unreachable End Function Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern Throw New NotImplementedException() End Sub Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern Throw New NotImplementedException() End Sub Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern Throw New NotImplementedException() End Function Public Function GetExpressionOfThrowExpression(throwExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression ' ThrowExpression doesn't exist in VB Throw New NotImplementedException() End Function Public Function IsThrowStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowStatement Return node.IsKind(SyntaxKind.ThrowStatement) End Function Public Function IsLocalFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunction Return False End Function Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax) stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken contents = interpolatedStringExpressionSyntax.Contents stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken End Sub Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression Return False 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.Collections.Immutable Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts #If CODE_STYLE Then Imports Microsoft.CodeAnalysis.Internal.Editing #Else Imports Microsoft.CodeAnalysis.Editing #End If Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSyntaxFacts Inherits AbstractSyntaxFacts Implements ISyntaxFacts Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts Protected Sub New() End Sub Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive Get Return False End Get End Property Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer Get Return CaseInsensitiveComparison.Comparer End Get End Property Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker Get Return SyntaxFactory.ElasticMarker End Get End Property Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed Get Return SyntaxFactory.ElasticCarriageReturnLineFeed End Get End Property Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds Protected Overrides ReadOnly Property DocumentationCommentService As IDocumentationCommentService Get Return VisualBasicDocumentationCommentService.Instance End Get End Property Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer Return False End Function Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression Return False End Function Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration Return False End Function Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord Return False End Function Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct Return False End Function Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken Return SyntaxFactory.ParseToken(text, startStatement:=True) End Function Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia Return SyntaxFactory.ParseLeadingTrivia(text) End Function Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier) Dim needsEscaping = keywordKind <> SyntaxKind.None Return If(needsEscaping, "[" & identifier & "]", identifier) End Function Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return False End Function Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse (IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) End Function Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword Return token.IsContextualKeyword() End Function Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword Return token.IsReservedKeyword() End Function Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword Return token.IsPreprocessorKeyword() End Function Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken) End Function Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace If token.Kind = SyntaxKind.CloseBraceToken Then Dim tuples = token.Parent.GetBraces() openBrace = tuples.openBrace Return openBrace.Kind = SyntaxKind.OpenBraceToken End If Return False End Function Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral If syntaxTree Is Nothing Then Return False End If Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken) End Function Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective Return TypeOf node Is DirectiveTriviaSyntax End Function Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo Select Case node.Kind Case SyntaxKind.ExternalSourceDirectiveTrivia info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False) Return True Case SyntaxKind.EndExternalSourceDirectiveTrivia info = New ExternalSourceInfo(Nothing, True) Return True End Select Return False End Function Public Function IsObjectCreationExpressionType(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsObjectCreationExpressionType Return node.IsParentKind(SyntaxKind.ObjectCreationExpression) AndAlso DirectCast(node.Parent, ObjectCreationExpressionSyntax).Type Is node End Function Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression ' VB doesn't support declaration expressions Return False End Function Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName Return node.IsParentKind(SyntaxKind.Attribute) AndAlso DirectCast(node.Parent, AttributeSyntax).Name Is node End Function Public Function IsRightSideOfQualifiedName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRightSideOfQualifiedName Dim vbNode = TryCast(node, SimpleNameSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsRightSideOfQualifiedName() End Function Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression Dim vbNode = TryCast(node, ExpressionSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName() End Function Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax) Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node End Function Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax)) End Function Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression() End Function Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax) expression = conditionalAccess.Expression operatorToken = conditionalAccess.QuestionMarkToken whenNotNull = conditionalAccess.WhenNotNull End Sub Public Function IsAnonymousFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunction Return TypeOf node Is LambdaExpressionSyntax End Function Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument Dim arg = TryCast(node, SimpleArgumentSyntax) Return arg?.NameColonEquals IsNot Nothing End Function Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node) End Function Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter Return TryCast(node, ParameterSyntax)?.Identifier?.Identifier End Function Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter Return TryCast(node, ParameterSyntax)?.Default End Function Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList Return node.GetParameterList() End Function Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList Return node.IsKind(SyntaxKind.ParameterList) End Function Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember Return HasIncompleteParentMember(node) End Function Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName Dim vbGenericName = TryCast(genericName, GenericNameSyntax) Return If(vbGenericName IsNot Nothing, vbGenericName.Identifier, Nothing) End Function Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node End Function Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment Return False End Function Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement Return False End Function Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement Return TypeOf node Is StatementSyntax End Function Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement Return TypeOf node Is ExecutableStatementSyntax End Function Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody Return TypeOf node Is MethodBlockBaseSyntax End Function Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement Return TryCast(node, ReturnStatementSyntax)?.Expression End Function Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsThisConstructorInitializer() End If Return False End Function Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsBaseConstructorInitializer() End If Return False End Function Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword Select Case token.Kind() Case _ SyntaxKind.JoinKeyword, SyntaxKind.IntoKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword, SyntaxKind.ByKeyword, SyntaxKind.OrderKeyword, SyntaxKind.WhereKeyword, SyntaxKind.OnKeyword, SyntaxKind.FromKeyword, SyntaxKind.WhileKeyword, SyntaxKind.SelectKeyword Return TypeOf token.Parent Is QueryClauseSyntax Case SyntaxKind.GroupKeyword Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation)) Case SyntaxKind.EqualsKeyword Return TypeOf token.Parent Is JoinConditionSyntax Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword Return TypeOf token.Parent Is OrderingSyntax Case SyntaxKind.InKeyword Return TypeOf token.Parent Is CollectionRangeVariableSyntax Case Else Return False End Select End Function Public Function IsThrowExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowExpression ' VB does not support throw expressions currently. Return False End Function Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None End Function Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType = type End Function Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType type = GetPredefinedType(token) Return type <> PredefinedType.None End Function Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType Select Case token.Kind Case SyntaxKind.BooleanKeyword Return PredefinedType.Boolean Case SyntaxKind.ByteKeyword Return PredefinedType.Byte Case SyntaxKind.SByteKeyword Return PredefinedType.SByte Case SyntaxKind.IntegerKeyword Return PredefinedType.Int32 Case SyntaxKind.UIntegerKeyword Return PredefinedType.UInt32 Case SyntaxKind.ShortKeyword Return PredefinedType.Int16 Case SyntaxKind.UShortKeyword Return PredefinedType.UInt16 Case SyntaxKind.LongKeyword Return PredefinedType.Int64 Case SyntaxKind.ULongKeyword Return PredefinedType.UInt64 Case SyntaxKind.SingleKeyword Return PredefinedType.Single Case SyntaxKind.DoubleKeyword Return PredefinedType.Double Case SyntaxKind.DecimalKeyword Return PredefinedType.Decimal Case SyntaxKind.StringKeyword Return PredefinedType.String Case SyntaxKind.CharKeyword Return PredefinedType.Char Case SyntaxKind.ObjectKeyword Return PredefinedType.Object Case SyntaxKind.DateKeyword Return PredefinedType.DateTime Case Else Return PredefinedType.None End Select End Function Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None End Function Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op End Function Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator op = GetPredefinedOperator(token) Return op <> PredefinedOperator.None End Function Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator Select Case token.Kind Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken Return PredefinedOperator.Addition Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken Return PredefinedOperator.Subtraction Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword Return PredefinedOperator.BitwiseAnd Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword Return PredefinedOperator.BitwiseOr Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken Return PredefinedOperator.Concatenate Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken Return PredefinedOperator.Division Case SyntaxKind.EqualsToken Return PredefinedOperator.Equality Case SyntaxKind.XorKeyword Return PredefinedOperator.ExclusiveOr Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken Return PredefinedOperator.Exponent Case SyntaxKind.GreaterThanToken Return PredefinedOperator.GreaterThan Case SyntaxKind.GreaterThanEqualsToken Return PredefinedOperator.GreaterThanOrEqual Case SyntaxKind.LessThanGreaterThanToken Return PredefinedOperator.Inequality Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken Return PredefinedOperator.IntegerDivision Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken Return PredefinedOperator.LeftShift Case SyntaxKind.LessThanToken Return PredefinedOperator.LessThan Case SyntaxKind.LessThanEqualsToken Return PredefinedOperator.LessThanOrEqual Case SyntaxKind.LikeKeyword Return PredefinedOperator.Like Case SyntaxKind.NotKeyword Return PredefinedOperator.Complement Case SyntaxKind.ModKeyword Return PredefinedOperator.Modulus Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken Return PredefinedOperator.Multiplication Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken Return PredefinedOperator.RightShift Case Else Return PredefinedOperator.None End Select End Function Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText Return SyntaxFacts.GetText(CType(kind, SyntaxKind)) End Function Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter Return SyntaxFacts.IsIdentifierPartCharacter(c) End Function Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter Return SyntaxFacts.IsIdentifierStartCharacter(c) End Function Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter Return c = "["c OrElse c = "]"c End Function Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier Dim token = SyntaxFactory.ParseToken(identifier) ' TODO: There is no way to get the diagnostics to see if any are actually errors? Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length End Function Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]" End Function Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter Return c = "%"c OrElse c = "&"c OrElse c = "@"c OrElse c = "!"c OrElse c = "#"c OrElse c = "$"c End Function Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence Return False ' VB does not support identifiers with escaped unicode characters End Function Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral Select Case token.Kind() Case _ SyntaxKind.IntegerLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.FloatingLiteralToken, SyntaxKind.DateLiteralToken, SyntaxKind.StringLiteralToken, SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.TrueKeyword, SyntaxKind.FalseKeyword, SyntaxKind.NothingKeyword Return True End Select Return False End Function Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken) End Function Public Function IsNumericLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNumericLiteralExpression Return If(node Is Nothing, False, node.IsKind(SyntaxKind.NumericLiteralExpression)) End Function Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken Return Me.IsWord(token) OrElse Me.IsLiteral(token) OrElse Me.IsOperator(token) End Function Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression Return False End Function Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName Dim simpleName = TryCast(node, SimpleNameSyntax) If simpleName IsNot Nothing Then name = simpleName.Identifier.ValueText arity = simpleName.Arity End If End Sub Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric Return name.IsKind(SyntaxKind.GenericName) End Function Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget) End Function Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding ' Member bindings are a C# concept. Return Nothing End Function Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression ' Member bindings are a C# concept. Return Nothing End Function Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression Dim invocation = TryCast(node, InvocationExpressionSyntax) If invocation IsNot Nothing Then expression = invocation?.Expression argumentList = invocation?.ArgumentList Return End If If node.Kind() = SyntaxKind.DictionaryAccessExpression Then GetPartsOfMemberAccessExpression(node, expression, argumentList) Return End If Return End Sub Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation Return TryCast(node, InterpolationSyntax)?.Expression End Function Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext Return SyntaxFacts.IsInNamespaceOrTypeContext(node) End Function Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing End Function Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext Return node.IsInStaticContext() End Function Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument Return TryCast(node, ArgumentSyntax).GetArgumentExpression() End Function Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument ' TODO(cyrusn): Consider the method this argument is passed to, to determine this. Return RefKind.None End Function Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument Return TypeOf node Is ArgumentSyntax End Function Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument Dim argument = TryCast(node, ArgumentSyntax) Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted End Function Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext Return node.IsInConstantContext() End Function Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock) End Function Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext Return False End Function Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute Return DirectCast(node, AttributeSyntax).Name End Function Public Function GetExpressionOfParenthesizedExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfParenthesizedExpression Return DirectCast(node, ParenthesizedExpressionSyntax).Expression End Function Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier Dim identifierName = TryCast(node, IdentifierNameSyntax) Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute) End Function Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration If root Is Nothing Then Throw New ArgumentNullException(NameOf(root)) End If If position < 0 OrElse position > root.Span.End Then Throw New ArgumentOutOfRangeException(NameOf(position)) End If Return root. FindToken(position). GetAncestors(Of SyntaxNode)(). FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax) End Function Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration If node Is Nothing Then Throw New ArgumentNullException(NameOf(node)) End If Dim parent = node.Parent While node IsNot Nothing If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then Return node End If node = node.Parent End While Return Nothing End Function Public Function FindTokenOnLeftOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnLeftOfPosition Return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function FindTokenOnRightOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnRightOfPosition Return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim unused As SyntaxNode = Nothing Return IsMemberInitializerNamedAssignmentIdentifier(node, unused) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier( node As SyntaxNode, ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim identifier = TryCast(node, IdentifierNameSyntax) If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then ' .parent is the NamedField. ' .parent.parent is the ObjectInitializer. ' .parent.parent.parent will be the ObjectCreationExpression. initializedInstance = identifier.Parent.Parent.Parent Return True End If Return False End Function Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern Return False End Function Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause Return False End Function Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression ' VB doesn't have a specialized node for element access. Instead, it just uses an ' invocation expression or dictionary access expression. Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression End Function Public Sub GetPartsOfParenthesizedExpression( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax) openParen = parenthesizedExpression.OpenParenToken expression = parenthesizedExpression.Expression closeParen = parenthesizedExpression.CloseParenToken End Sub Public Function IsTypeNamedVarInVariableOrFieldDeclaration(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedVarInVariableOrFieldDeclaration Return False End Function Public Function IsTypeNamedDynamic(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedDynamic Return False End Function Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef Return False End Function Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration Contract.ThrowIfNull(root, NameOf(root)) Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position)) Dim [end] = root.FullSpan.End If [end] = 0 Then ' empty file Return Nothing End If ' make sure position doesn't touch end of root position = Math.Min(position, [end] - 1) Dim node = root.FindToken(position).Parent While node IsNot Nothing If useFullSpan OrElse node.Span.Contains(position) Then If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return node End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return node End If If TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax OrElse TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is FieldDeclarationSyntax Then Return node End If End If node = node.Parent End While Return Nothing End Function Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember ' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and ' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things ' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level ' members. If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return True End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return True End If If TypeOf node Is DeclareStatementSyntax Then Return True End If Return TypeOf node Is ConstructorBlockSyntax OrElse TypeOf node Is MethodBlockSyntax OrElse TypeOf node Is OperatorBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is EnumMemberDeclarationSyntax OrElse TypeOf node Is FieldDeclarationSyntax End Function Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding Dim member = GetContainingMemberDeclaration(node, node.SpanStart) If member Is Nothing Then Return Nothing End If ' TODO: currently we only support method for now Dim method = TryCast(member, MethodBlockBaseSyntax) If method IsNot Nothing Then If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then Return Nothing End If ' We don't want to include the BlockStatement or any trailing trivia up to and including its statement ' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up ' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start ' of the EndBlockStatements leading trivia. Dim firstStatement = method.Statements.FirstOrDefault() Dim spanStart = If(firstStatement IsNot Nothing, firstStatement.FullSpan.Start, method.EndBlockStatement.FullSpan.Start) Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart) End If Return Nothing End Function Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody Dim method = TryCast(node, MethodBlockBaseSyntax) If method IsNot Nothing Then Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span) End If Dim [event] = TryCast(node, EventBlockSyntax) If [event] IsNot Nothing Then Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span) End If Dim [property] = TryCast(node, PropertyBlockSyntax) If [property] IsNot Nothing Then Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span) End If Dim field = TryCast(node, FieldDeclarationSyntax) If field IsNot Nothing Then Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span) End If Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax) If [enum] IsNot Nothing Then Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span) End If Dim propStatement = TryCast(node, PropertyStatementSyntax) If propStatement IsNot Nothing Then Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span) End If Return False End Function Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean If innerSpan.IsEmpty Then Return outerSpan.Contains(innerSpan.Start) End If Return outerSpan.Contains(innerSpan) End Function Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=True, methodLevel:=True) Return list End Function Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=False, methodLevel:=True) Return list End Function Public Function IsClassDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsClassDeclaration Return node.IsKind(SyntaxKind.ClassBlock) End Function Public Function IsNamespaceDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamespaceDeclaration Return node.IsKind(SyntaxKind.NamespaceBlock) End Function Public Function GetNameOfNamespaceDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfNamespaceDeclaration If IsNamespaceDeclaration(node) Then Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name End If Return Nothing End Function Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration Return DirectCast(typeDeclaration, TypeBlockSyntax).Members End Function Public Function GetMembersOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfNamespaceDeclaration Return DirectCast(namespaceDeclaration, NamespaceBlockSyntax).Members End Function Public Function GetMembersOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Members End Function Public Function GetImportsOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfNamespaceDeclaration 'Visual Basic doesn't have namespaced imports Return Nothing End Function Public Function GetImportsOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Imports End Function Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers Return TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax End Function Private Const s_dotToken As String = "." Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName If node Is Nothing Then Return String.Empty End If Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder ' member keyword (if any) Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then Dim keywordToken = memberDeclaration.GetMemberKeywordToken() If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then builder.Append(keywordToken.Text) builder.Append(" "c) End If End If Dim names = ArrayBuilder(Of String).GetInstance() ' containing type(s) Dim parent = node.Parent While TypeOf parent Is TypeBlockSyntax names.Push(GetName(parent, options, containsGlobalKeyword:=False)) parent = parent.Parent End While If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then ' containing namespace(s) in source (if any) Dim containsGlobalKeyword As Boolean = False While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock names.Push(GetName(parent, options, containsGlobalKeyword)) parent = parent.Parent End While ' root namespace (if any) If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then builder.Append(rootNamespace) builder.Append(s_dotToken) End If End If While Not names.IsEmpty() Dim name = names.Pop() If name IsNot Nothing Then builder.Append(name) builder.Append(s_dotToken) End If End While names.Free() ' name (include generic type parameters) builder.Append(GetName(node, options, containsGlobalKeyword:=False)) ' parameter list (if any) If (options And DisplayNameOptions.IncludeParameters) <> 0 Then builder.Append(memberDeclaration.GetParameterList()) End If ' As clause (if any) If (options And DisplayNameOptions.IncludeType) <> 0 Then Dim asClause = memberDeclaration.GetAsClause() If asClause IsNot Nothing Then builder.Append(" "c) builder.Append(asClause) End If End If Return pooled.ToStringAndFree() End Function Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String Const missingTokenPlaceholder As String = "?" Select Case node.Kind() Case SyntaxKind.CompilationUnit Return Nothing Case SyntaxKind.IdentifierName Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text) Case SyntaxKind.IncompleteMember Return missingTokenPlaceholder Case SyntaxKind.NamespaceBlock Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name If nameSyntax.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return Nothing Else Return GetName(nameSyntax, options, containsGlobalKeyword) End If Case SyntaxKind.QualifiedName Dim qualified = CType(node, QualifiedNameSyntax) If qualified.Left.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified Else Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword) End If End Select Dim name As String = Nothing Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If memberDeclaration IsNot Nothing Then Dim nameToken = memberDeclaration.GetNameToken() If nameToken <> Nothing Then name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text) If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder builder.Append(name) AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()) name = pooled.ToStringAndFree() End If End If End If Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString()) Return name End Function Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax) If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then builder.Append("(Of ") builder.Append(typeParameterList.Parameters(0).Identifier.Text) For i = 1 To typeParameterList.Parameters.Count - 1 builder.Append(", ") builder.Append(typeParameterList.Parameters(i).Identifier.Text) Next builder.Append(")"c) End If End Sub Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean) Debug.Assert(topLevel OrElse methodLevel) For Each member In node.GetMembers() If IsTopLevelNodeWithMembers(member) Then If topLevel Then list.Add(member) End If AppendMembers(member, list, topLevel, methodLevel) Continue For End If If methodLevel AndAlso IsMethodLevelMember(member) Then list.Add(member) End If Next End Sub Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent Dim node = token.Parent While node IsNot Nothing Dim parent = node.Parent ' If this node is on the left side of a member access expression, don't ascend ' further or we'll end up binding to something else. Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then If memberAccess.Expression Is node Then Exit While End If End If ' If this node is on the left side of a qualified name, don't ascend ' further or we'll end up binding to something else. Dim qualifiedName = TryCast(parent, QualifiedNameSyntax) If qualifiedName IsNot Nothing Then If qualifiedName.Left Is node Then Exit While End If End If ' If this node is the type of an object creation expression, return the ' object creation expression. Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax) If objectCreation IsNot Nothing Then If objectCreation.Type Is node Then node = parent Exit While End If End If ' The inside of an interpolated string is treated as its own token so we ' need to force navigation to the parent expression syntax. If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then node = parent Exit While End If ' If this node is not parented by a name, we're done. Dim name = TryCast(parent, NameSyntax) If name Is Nothing Then Exit While End If node = parent End While Return node End Function Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors Dim compilationUnit = TryCast(root, CompilationUnitSyntax) If compilationUnit Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If Dim constructors = New List(Of SyntaxNode)() AppendConstructors(compilationUnit.Members, constructors, cancellationToken) Return constructors End Function Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken) For Each member As StatementSyntax In members cancellationToken.ThrowIfCancellationRequested() Dim constructor = TryCast(member, ConstructorBlockSyntax) If constructor IsNot Nothing Then constructors.Add(constructor) Continue For End If Dim [namespace] = TryCast(member, NamespaceBlockSyntax) If [namespace] IsNot Nothing Then AppendConstructors([namespace].Members, constructors, cancellationToken) End If Dim [class] = TryCast(member, ClassBlockSyntax) If [class] IsNot Nothing Then AppendConstructors([class].Members, constructors, cancellationToken) End If Dim [struct] = TryCast(member, StructureBlockSyntax) If [struct] IsNot Nothing Then AppendConstructors([struct].Members, constructors, cancellationToken) End If Next End Sub Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition Dim trivia = tree.FindTriviaToLeft(position, cancellationToken) If trivia.Kind = SyntaxKind.DisabledTextTrivia Then Return trivia.FullSpan End If Return Nothing End Function Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument If TryCast(argument, ArgumentSyntax)?.IsNamed Then Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText End If Return String.Empty End Function Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument ' All argument types are ArgumentSyntax in VB. Return GetNameForArgument(argument) End Function Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot() End Function Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Right, TryCast(node, MemberAccessExpressionSyntax)?.Name) End Function Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Left, TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)) End Function Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing End Function Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement End Function Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement End Function Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement End Function Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment Return TryCast(node, AssignmentStatementSyntax)?.Right End Function Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator Return node.IsKind(SyntaxKind.InferredFieldInitializer) End Function Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression Return False End Function Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression Return False End Function Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value End Function Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse token.Kind = SyntaxKind.FloatingLiteralToken OrElse token.Kind = SyntaxKind.IntegerLiteralToken End Function Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral ' VB does not have verbatim strings Return False End Function Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression Return GetArgumentsOfArgumentList(TryCast(node, InvocationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression Return GetArgumentsOfArgumentList(TryCast(node, ObjectCreationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList Dim arguments = TryCast(node, ArgumentListSyntax)?.Arguments Return If(arguments.HasValue, arguments.Value, Nothing) End Function Public Function GetArgumentListOfInvocationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfInvocationExpression Return DirectCast(node, InvocationExpressionSyntax).ArgumentList End Function Public Function GetArgumentListOfObjectCreationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfObjectCreationExpression Return DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList End Function Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine Return node.ConvertToSingleLine(useElasticTrivia) End Function Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return node.IsKind(SyntaxKind.DocumentationCommentTrivia) End Function Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport Return node.IsKind(SyntaxKind.ImportsStatement) End Function Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword) End Function Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword) End Function Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean If node.IsKind(SyntaxKind.Attribute) Then Dim attributeNode = CType(node, AttributeSyntax) If attributeNode.Target IsNot Nothing Then Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget) End If End If Return False End Function Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration ' From the Visual Basic language spec: ' NamespaceMemberDeclaration := ' NamespaceDeclaration | ' TypeDeclaration ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration ' ClassMemberDeclaration ::= ' NonModuleDeclaration | ' EventMemberDeclaration | ' VariableMemberDeclaration | ' ConstantMemberDeclaration | ' MethodMemberDeclaration | ' PropertyMemberDeclaration | ' ConstructorMemberDeclaration | ' OperatorDeclaration Select Case node.Kind() ' Because fields declarations can define multiple symbols "Public a, b As Integer" ' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. Case SyntaxKind.VariableDeclarator If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then Return True End If Return False Case SyntaxKind.NamespaceStatement, SyntaxKind.NamespaceBlock, SyntaxKind.ModuleStatement, SyntaxKind.ModuleBlock, SyntaxKind.EnumStatement, SyntaxKind.EnumBlock, SyntaxKind.StructureStatement, SyntaxKind.StructureBlock, SyntaxKind.InterfaceStatement, SyntaxKind.InterfaceBlock, SyntaxKind.ClassStatement, SyntaxKind.ClassBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.EventStatement, SyntaxKind.EventBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.FieldDeclaration, SyntaxKind.SubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.FunctionBlock, SyntaxKind.PropertyStatement, SyntaxKind.PropertyBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.SubNewStatement, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorStatement, SyntaxKind.OperatorBlock Return True End Select Return False End Function ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock, SyntaxKind.ModuleBlock, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return True End Select Return False End Function Public Function GetObjectCreationInitializer(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationInitializer Return DirectCast(node, ObjectCreationExpressionSyntax).Initializer End Function Public Function GetObjectCreationType(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationType Return DirectCast(node, ObjectCreationExpressionSyntax).Type End Function Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement Return node.IsKind(SyntaxKind.SimpleAssignmentStatement) End Function Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement ' VB only has assignment statements, so this can just delegate to that helper GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right) End Sub Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement Dim assignment = DirectCast(statement, AssignmentStatementSyntax) left = assignment.Left operatorToken = assignment.OperatorToken right = assignment.Right End Sub Public Function GetNameOfMemberAccessExpression(memberAccessExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberAccessExpression Return DirectCast(memberAccessExpression, MemberAccessExpressionSyntax).Name End Function Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName Return DirectCast(node, SimpleNameSyntax).Identifier End Function Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier End Function Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter Return DirectCast(node, ParameterSyntax).Identifier.Identifier End Function Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier End Function Public Function IsLocalFunctionStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunctionStatement ' VB does not have local functions Return False End Function Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators. Contains(DirectCast(declarator, VariableDeclaratorSyntax)) End Function Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(token1, token2) End Function Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(node1, node2) End Function Public Function IsExpressionOfInvocationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfInvocationExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, InvocationExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfAwaitExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfAwaitExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, AwaitExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfMemberAccessExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, MemberAccessExpressionSyntax)?.Expression Is node End Function Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression Return DirectCast(node, AwaitExpressionSyntax).Expression End Function Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node End Function Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement Return DirectCast(node, ExpressionStatementSyntax).Expression End Function Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression Return TypeOf node Is BinaryExpressionSyntax End Function Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression Return node.IsKind(SyntaxKind.TypeOfIsExpression) End Function Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax) left = binaryExpression.Left operatorToken = binaryExpression.OperatorToken right = binaryExpression.Right End Sub Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax) condition = conditionalExpression.Condition whenTrue = conditionalExpression.WhenTrue whenFalse = conditionalExpression.WhenFalse End Sub Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node) End Function Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression Dim tupleExpr = DirectCast(node, TupleExpressionSyntax) openParen = tupleExpr.OpenParenToken arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax)) closeParen = tupleExpr.CloseParenToken End Sub Public Function GetOperandOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetOperandOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).Operand End Function Public Function GetOperatorTokenOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetOperatorTokenOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).OperatorToken End Function Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax) expression = memberAccess.Expression operatorToken = memberAccess.OperatorToken name = memberAccess.Name End Sub Public Function GetNextExecutableStatement(statement As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNextExecutableStatement Return DirectCast(statement, StatementSyntax).GetNextStatement()?.FirstAncestorOrSelf(Of ExecutableStatementSyntax) End Function Public Overrides Function IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Overrides Function IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have multi-line comments. Return False End Function Public Overrides Function IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Overrides Function IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have multi-line comments. Return False End Function Public Overrides Function IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have shebang directives. Return False End Function Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind()) End Function Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic Return trivia.IsElastic() End Function Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes) End Function Public Function IsOnTypeHeader( root As SyntaxNode, position As Integer, fullHeader As Boolean, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnTypeHeader Dim typeBlock = TryGetAncestorForLocation(Of TypeBlockSyntax)(root, position) If typeBlock Is Nothing Then Return Nothing End If Dim typeStatement = typeBlock.BlockStatement typeDeclaration = typeStatement Dim lastToken = If(typeStatement.TypeParameterList?.GetLastToken(), typeStatement.Identifier) If fullHeader Then lastToken = If(typeBlock.Implements.LastOrDefault()?.GetLastToken(), If(typeBlock.Inherits.LastOrDefault()?.GetLastToken(), lastToken)) End If Return IsOnHeader(root, position, typeBlock, lastToken) End Function Public Function IsOnPropertyDeclarationHeader(root As SyntaxNode, position As Integer, ByRef propertyDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnPropertyDeclarationHeader Dim node = TryGetAncestorForLocation(Of PropertyStatementSyntax)(root, position) propertyDeclaration = node If propertyDeclaration Is Nothing Then Return False End If If node.AsClause IsNot Nothing Then Return IsOnHeader(root, position, node, node.AsClause) End If Return IsOnHeader(root, position, node, node.Identifier) End Function Public Function IsOnParameterHeader(root As SyntaxNode, position As Integer, ByRef parameter As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnParameterHeader Dim node = TryGetAncestorForLocation(Of ParameterSyntax)(root, position) parameter = node If parameter Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnMethodHeader(root As SyntaxNode, position As Integer, ByRef method As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnMethodHeader Dim node = TryGetAncestorForLocation(Of MethodStatementSyntax)(root, position) method = node If method Is Nothing Then Return False End If If node.HasReturnType() Then Return IsOnHeader(root, position, method, node.GetReturnType()) End If If node.ParameterList IsNot Nothing Then Return IsOnHeader(root, position, method, node.ParameterList) End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnLocalFunctionHeader(root As SyntaxNode, position As Integer, ByRef localFunction As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalFunctionHeader ' No local functions in VisualBasic Return False End Function Public Function IsOnLocalDeclarationHeader(root As SyntaxNode, position As Integer, ByRef localDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalDeclarationHeader Dim node = TryGetAncestorForLocation(Of LocalDeclarationStatementSyntax)(root, position) localDeclaration = node If localDeclaration Is Nothing Then Return False End If Dim initializersExpressions = node.Declarators. Where(Function(d) d.Initializer IsNot Nothing). SelectAsArray(Function(initialized) initialized.Initializer.Value) Return IsOnHeader(root, position, node, node, initializersExpressions) End Function Public Function IsOnIfStatementHeader(root As SyntaxNode, position As Integer, ByRef ifStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnIfStatementHeader ifStatement = Nothing Dim multipleLineNode = TryGetAncestorForLocation(Of MultiLineIfBlockSyntax)(root, position) If multipleLineNode IsNot Nothing Then ifStatement = multipleLineNode Return IsOnHeader(root, position, multipleLineNode.IfStatement, multipleLineNode.IfStatement) End If Dim singleLineNode = TryGetAncestorForLocation(Of SingleLineIfStatementSyntax)(root, position) If singleLineNode IsNot Nothing Then ifStatement = singleLineNode Return IsOnHeader(root, position, singleLineNode, singleLineNode.Condition) End If Return False End Function Public Function IsOnWhileStatementHeader(root As SyntaxNode, position As Integer, ByRef whileStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnWhileStatementHeader whileStatement = Nothing Dim whileBlock = TryGetAncestorForLocation(Of WhileBlockSyntax)(root, position) If whileBlock IsNot Nothing Then whileStatement = whileBlock Return IsOnHeader(root, position, whileBlock.WhileStatement, whileBlock.WhileStatement) End If Return False End Function Public Function IsOnForeachHeader(root As SyntaxNode, position As Integer, ByRef foreachStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnForeachHeader Dim node = TryGetAncestorForLocation(Of ForEachBlockSyntax)(root, position) foreachStatement = node If foreachStatement Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node.ForEachStatement) End Function Public Function IsBetweenTypeMembers(sourceText As SourceText, root As SyntaxNode, position As Integer, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBetweenTypeMembers Dim token = root.FindToken(position) Dim typeDecl = token.GetAncestor(Of TypeBlockSyntax) typeDeclaration = typeDecl If typeDecl IsNot Nothing Then Dim start = If(typeDecl.Implements.LastOrDefault()?.Span.End, If(typeDecl.Inherits.LastOrDefault()?.Span.End, typeDecl.BlockStatement.Span.End)) If position >= start AndAlso position <= typeDecl.EndBlockStatement.Span.Start Then Dim line = sourceText.Lines.GetLineFromPosition(position) If Not line.IsEmptyOrWhitespace() Then Return False End If Dim member = typeDecl.Members.FirstOrDefault(Function(d) d.FullSpan.Contains(position)) If member Is Nothing Then ' There are no members, Or we're after the last member. Return True Else ' We're within a member. Make sure we're in the leading whitespace of ' the member. If position < member.SpanStart Then For Each trivia In member.GetLeadingTrivia() If Not trivia.IsWhitespaceOrEndOfLine() Then Return False End If If trivia.FullSpan.Contains(position) Then Return True End If Next End If End If End If End If Return False End Function Private Function ISyntaxFacts_GetFileBanner(root As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner Return GetFileBanner(root) End Function Private Function ISyntaxFacts_GetFileBanner(firstToken As SyntaxToken) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner Return GetFileBanner(firstToken) End Function Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean Return token.ContainsInterleavedDirective(span, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(node, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(nodes, cancellationToken) End Function Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia End Function Private Function ISyntaxFacts_GetBannerText(documentationCommentTriviaSyntax As SyntaxNode, maxBannerLength As Integer, cancellationToken As CancellationToken) As String Implements ISyntaxFacts.GetBannerText Return GetBannerText(documentationCommentTriviaSyntax, maxBannerLength, cancellationToken) End Function Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers Return node.GetModifiers() End Function Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers Return node.WithModifiers(modifiers) End Function Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression Return TypeOf node Is LiteralExpressionSyntax End Function Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators End Function Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Initializer End Function Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator Dim declarator = DirectCast(node, VariableDeclaratorSyntax) Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type End Function Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause Return DirectCast(node, EqualsValueSyntax).Value End Function Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock ' VB has no equivalent of curly braces. Return False End Function Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock Return node.IsExecutableBlock() End Function Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements Return node.GetExecutableBlockStatements() End Function Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock Return nodes.FindInnermostCommonExecutableBlock() End Function Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer Return IsExecutableBlock(node) End Function Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements Return GetExecutableBlockStatements(node) End Function Private Function ISyntaxFacts_GetLeadingBlankLines(node As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetLeadingBlankLines Return MyBase.GetLeadingBlankLines(node) End Function Private Function ISyntaxFacts_GetNodeWithoutLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As TSyntaxNode Implements ISyntaxFacts.GetNodeWithoutLeadingBlankLines Return MyBase.GetNodeWithoutLeadingBlankLines(node) End Function Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression Return node.Kind = SyntaxKind.CTypeExpression End Function Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression Return node.Kind = SyntaxKind.DirectCastExpression End Function Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression Dim cast = DirectCast(node, DirectCastExpressionSyntax) type = cast.Type expression = cast.Expression End Sub Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation Throw New NotImplementedException() End Function Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride If token.Kind() = SyntaxKind.OverridesKeyword Then Dim parent = token.Parent Select Case parent.Kind() Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(parent, MethodStatementSyntax) Return method.Identifier Case SyntaxKind.PropertyStatement Dim [property] = DirectCast(parent, PropertyStatementSyntax) Return [property].Identifier End Select End If Return Nothing End Function Public Shadows Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.SpansPreprocessorDirective Return MyBase.SpansPreprocessorDirective(nodes) End Function Public Shadows Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean Return MyBase.SpansPreprocessorDirective(tokens) End Function Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression Dim invocation = DirectCast(node, InvocationExpressionSyntax) expression = invocation.Expression argumentList = invocation.ArgumentList End Sub Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression ' Does not exist in VB. Return False End Function Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists Return node.GetAttributeLists() End Function Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective Dim importStatement = TryCast(node, ImportsStatementSyntax) If (importStatement IsNot Nothing) Then For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then Return True End If End If Next End If Return False End Function Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax Dim xmlElement = TryCast(node, XmlElementSyntax) If xmlElement IsNot Nothing Then Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax) Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName End If Return False End Function Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return documentationCommentTrivia.Content End If Return Nothing End Function Public Overrides Function CanHaveAccessibility(declaration As SyntaxNode) As Boolean Implements ISyntaxFacts.CanHaveAccessibility Select Case declaration.Kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement, SyntaxKind.StructureBlock, SyntaxKind.StructureStatement, SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement, SyntaxKind.EnumBlock, SyntaxKind.EnumStatement, SyntaxKind.ModuleBlock, SyntaxKind.ModuleStatement, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.FieldDeclaration, SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubStatement, SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement, SyntaxKind.EventBlock, SyntaxKind.EventStatement, SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return True Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement ' Shared constructor cannot have modifiers in VB. ' Module constructors are implicitly Shared and can't have accessibility modifier. Return Not declaration.GetModifiers().Any(SyntaxKind.SharedKeyword) AndAlso Not declaration.Parent.IsKind(SyntaxKind.ModuleBlock) Case SyntaxKind.ModifiedIdentifier Return If(IsChildOf(declaration, SyntaxKind.VariableDeclarator), CanHaveAccessibility(declaration.Parent), False) Case SyntaxKind.VariableDeclarator Return If(IsChildOfVariableDeclaration(declaration), CanHaveAccessibility(declaration.Parent), False) Case Else Return False End Select End Function Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind) End Function Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement) End Function Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Implements ISyntaxFacts.GetAccessibility If Not CanHaveAccessibility(declaration) Then Return Accessibility.NotApplicable End If Dim tokens = GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return acc End Function Public Overrides Function GetModifierTokens(declaration As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifierTokens Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).Modifiers Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).Modifiers Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).Modifiers Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Modifiers Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).Modifiers Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.Modifiers Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).Modifiers Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Modifiers Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Modifiers Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Modifiers Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).Modifiers Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Modifiers Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Modifiers Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).Modifiers Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Modifiers Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Modifiers Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.LocalDeclarationStatement Return DirectCast(declaration, LocalDeclarationStatementSyntax).Modifiers Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return GetModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).Modifiers Case Else Return Nothing End Select End Function Public Overrides Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean) Implements ISyntaxFacts.GetAccessibilityAndModifiers accessibility = Accessibility.NotApplicable modifiers = DeclarationModifiers.None isDefault = False For Each token In modifierTokens Select Case token.Kind Case SyntaxKind.DefaultKeyword isDefault = True Case SyntaxKind.PublicKeyword accessibility = Accessibility.Public Case SyntaxKind.PrivateKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Private End If Case SyntaxKind.FriendKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedOrFriend Else accessibility = Accessibility.Friend End If Case SyntaxKind.ProtectedKeyword If accessibility = Accessibility.Friend Then accessibility = Accessibility.ProtectedOrFriend ElseIf accessibility = Accessibility.Private Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Protected End If Case SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword modifiers = modifiers Or DeclarationModifiers.Abstract Case SyntaxKind.ShadowsKeyword modifiers = modifiers Or DeclarationModifiers.[New] Case SyntaxKind.OverridesKeyword modifiers = modifiers Or DeclarationModifiers.Override Case SyntaxKind.OverridableKeyword modifiers = modifiers Or DeclarationModifiers.Virtual Case SyntaxKind.SharedKeyword modifiers = modifiers Or DeclarationModifiers.Static Case SyntaxKind.AsyncKeyword modifiers = modifiers Or DeclarationModifiers.Async Case SyntaxKind.ConstKeyword modifiers = modifiers Or DeclarationModifiers.Const Case SyntaxKind.ReadOnlyKeyword modifiers = modifiers Or DeclarationModifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword modifiers = modifiers Or DeclarationModifiers.WriteOnly Case SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword modifiers = modifiers Or DeclarationModifiers.Sealed Case SyntaxKind.WithEventsKeyword modifiers = modifiers Or DeclarationModifiers.WithEvents Case SyntaxKind.PartialKeyword modifiers = modifiers Or DeclarationModifiers.Partial End Select Next End Sub Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Implements ISyntaxFacts.GetDeclarationKind Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DeclarationKind.CompilationUnit Case SyntaxKind.NamespaceBlock Return DeclarationKind.Namespace Case SyntaxKind.ImportsStatement Return DeclarationKind.NamespaceImport Case SyntaxKind.ClassBlock Return DeclarationKind.Class Case SyntaxKind.StructureBlock Return DeclarationKind.Struct Case SyntaxKind.InterfaceBlock Return DeclarationKind.Interface Case SyntaxKind.EnumBlock Return DeclarationKind.Enum Case SyntaxKind.EnumMemberDeclaration Return DeclarationKind.EnumMember Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationKind.Delegate Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DeclarationKind.Method Case SyntaxKind.FunctionStatement If Not IsChildOf(declaration, SyntaxKind.FunctionBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.SubStatement If Not IsChildOf(declaration, SyntaxKind.SubBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.ConstructorBlock Return DeclarationKind.Constructor Case SyntaxKind.PropertyBlock If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If End If Case SyntaxKind.OperatorBlock Return DeclarationKind.Operator Case SyntaxKind.OperatorStatement If Not IsChildOf(declaration, SyntaxKind.OperatorBlock) Then Return DeclarationKind.Operator End If Case SyntaxKind.EventBlock Return DeclarationKind.CustomEvent Case SyntaxKind.EventStatement If Not IsChildOf(declaration, SyntaxKind.EventBlock) Then Return DeclarationKind.Event End If Case SyntaxKind.Parameter Return DeclarationKind.Parameter Case SyntaxKind.FieldDeclaration Return DeclarationKind.Field Case SyntaxKind.LocalDeclarationStatement If GetDeclarationCount(declaration) = 1 Then Return DeclarationKind.Variable End If Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then If IsChildOf(declaration.Parent, SyntaxKind.FieldDeclaration) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Field ElseIf IsChildOf(declaration.Parent, SyntaxKind.LocalDeclarationStatement) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Variable End If End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list Is Nothing OrElse list.Attributes.Count > 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.GetAccessorBlock Return DeclarationKind.GetAccessor Case SyntaxKind.SetAccessorBlock Return DeclarationKind.SetAccessor Case SyntaxKind.AddHandlerAccessorBlock Return DeclarationKind.AddAccessor Case SyntaxKind.RemoveHandlerAccessorBlock Return DeclarationKind.RemoveAccessor Case SyntaxKind.RaiseEventAccessorBlock Return DeclarationKind.RaiseAccessor End Select Return DeclarationKind.None End Function Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer Dim count As Integer = 0 For i = 0 To nodes.Count - 1 count = count + GetDeclarationCount(nodes(i)) Next Return count End Function Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Select Case node.Kind Case SyntaxKind.FieldDeclaration Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Count Case SyntaxKind.AttributesStatement Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Return DirectCast(node, AttributeListSyntax).Attributes.Count Case SyntaxKind.ImportsStatement Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count End Select Return 1 End Function Private Shared Function IsIndexer(declaration As SyntaxNode) As Boolean Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim p = DirectCast(declaration, PropertyBlockSyntax).PropertyStatement Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then Dim p = DirectCast(declaration, PropertyStatementSyntax) Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) End If End Select Return False End Function Public Function IsImplicitObjectCreation(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsImplicitObjectCreation Return False End Function Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern Return False End Function Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression Return False End Function Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern Return False End Function Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern Return False End Function Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern Return False End Function Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern Return False End Function Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern Return False End Function Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern Return False End Function Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern Return False End Function Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern Return False End Function Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern Return False End Function Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern Return False End Function Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern Return False End Function Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern Return False End Function Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression Throw ExceptionUtilities.Unreachable End Sub Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern Throw ExceptionUtilities.Unreachable End Function Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern Throw New NotImplementedException() End Sub Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern Throw New NotImplementedException() End Sub Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern Throw New NotImplementedException() End Function Public Function GetExpressionOfThrowExpression(throwExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression ' ThrowExpression doesn't exist in VB Throw New NotImplementedException() End Function Public Function IsThrowStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowStatement Return node.IsKind(SyntaxKind.ThrowStatement) End Function Public Function IsLocalFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunction Return False End Function Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax) stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken contents = interpolatedStringExpressionSyntax.Contents stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken End Sub Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression Return False End Function End Class End Namespace
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/EditorFeatures/VisualBasicTest/Recommendations/Queries/LetKeywordRecommenderTests.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.Queries Public Class LetKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LetNotInStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Let") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LetInQueryTest() VerifyRecommendationsContain(<MethodBody>Dim x = From y In z |</MethodBody>, "Let") End Sub <WorkItem(543085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543085")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LetAfterLambdaInQueryTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = From num In numbers Let n6 As Func(Of Integer) = Function() 5 |</MethodBody>, "Let") End Sub <WorkItem(543173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543173")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LetAfterMultiLineFunctionLambdaExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By Function() Return 5 End Function |</MethodBody>, "Let") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> <WorkItem(543174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543174")> Public Sub LetAfterAnonymousObjectCreationExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By New With {.Key = 10} |</MethodBody>, "Let") End Sub <WorkItem(543219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543219")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LetAfterIntoClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = From i1 In arr Group By i1 Into Count |</MethodBody>, "Let") End Sub <WorkItem(543232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543232")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LetAfterNestedAggregateFromClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = Aggregate i1 In arr From i4 In arr |</MethodBody>, "Let") 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.Queries Public Class LetKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LetNotInStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Let") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LetInQueryTest() VerifyRecommendationsContain(<MethodBody>Dim x = From y In z |</MethodBody>, "Let") End Sub <WorkItem(543085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543085")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LetAfterLambdaInQueryTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = From num In numbers Let n6 As Func(Of Integer) = Function() 5 |</MethodBody>, "Let") End Sub <WorkItem(543173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543173")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LetAfterMultiLineFunctionLambdaExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By Function() Return 5 End Function |</MethodBody>, "Let") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> <WorkItem(543174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543174")> Public Sub LetAfterAnonymousObjectCreationExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By New With {.Key = 10} |</MethodBody>, "Let") End Sub <WorkItem(543219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543219")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LetAfterIntoClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = From i1 In arr Group By i1 Into Count |</MethodBody>, "Let") End Sub <WorkItem(543232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543232")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LetAfterNestedAggregateFromClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = Aggregate i1 In arr From i4 In arr |</MethodBody>, "Let") End Sub End Class End Namespace
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/EditorFeatures/Core/Implementation/InlineRename/Taggers/RenameTaggerProvider.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.Text; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { [Export(typeof(ITaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TagType(typeof(ITextMarkerTag))] internal class RenameTaggerProvider : ITaggerProvider { private readonly InlineRenameService _renameService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RenameTaggerProvider(InlineRenameService renameService) => _renameService = renameService; public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag => new RenameTagger(buffer, _renameService) as ITagger<T>; } }
// 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.Text; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { [Export(typeof(ITaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TagType(typeof(ITextMarkerTag))] internal class RenameTaggerProvider : ITaggerProvider { private readonly InlineRenameService _renameService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RenameTaggerProvider(InlineRenameService renameService) => _renameService = renameService; public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag => new RenameTagger(buffer, _renameService) as ITagger<T>; } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Workspaces/Remote/ServiceHub/Services/Host/ProcessExtensions.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.ComponentModel; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Remote { internal static class ProcessExtensions { private static bool s_settingPrioritySupported = true; public static bool TrySetPriorityClass(this Process process, ProcessPriorityClass priorityClass) { if (!s_settingPrioritySupported) { return false; } try { process.PriorityClass = priorityClass; return true; } catch (Exception e) when (e is PlatformNotSupportedException or Win32Exception) { // the runtime does not support changing process priority s_settingPrioritySupported = false; return 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. using System; using System.ComponentModel; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Remote { internal static class ProcessExtensions { private static bool s_settingPrioritySupported = true; public static bool TrySetPriorityClass(this Process process, ProcessPriorityClass priorityClass) { if (!s_settingPrioritySupported) { return false; } try { process.PriorityClass = priorityClass; return true; } catch (Exception e) when (e is PlatformNotSupportedException or Win32Exception) { // the runtime does not support changing process priority s_settingPrioritySupported = false; return false; } } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Features/Core/Portable/EditAndContinue/BidirectionalMap.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 Microsoft.CodeAnalysis.Differencing; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct BidirectionalMap<T> { public readonly IReadOnlyDictionary<T, T> Forward; public readonly IReadOnlyDictionary<T, T> Reverse; public BidirectionalMap(IReadOnlyDictionary<T, T> forward, IReadOnlyDictionary<T, T> reverse) { Forward = forward; Reverse = reverse; } public BidirectionalMap(IEnumerable<KeyValuePair<T, T>> entries) { var map = new Dictionary<T, T>(); var reverseMap = new Dictionary<T, T>(); foreach (var entry in entries) { map.Add(entry.Key, entry.Value); reverseMap.Add(entry.Value, entry.Key); } Forward = map; Reverse = reverseMap; } public static BidirectionalMap<T> FromMatch(Match<T> match) => new(match.Matches, match.ReverseMatches); public bool IsDefaultOrEmpty => Forward == null || Forward.Count == 0; } }
// 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 Microsoft.CodeAnalysis.Differencing; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct BidirectionalMap<T> { public readonly IReadOnlyDictionary<T, T> Forward; public readonly IReadOnlyDictionary<T, T> Reverse; public BidirectionalMap(IReadOnlyDictionary<T, T> forward, IReadOnlyDictionary<T, T> reverse) { Forward = forward; Reverse = reverse; } public BidirectionalMap(IEnumerable<KeyValuePair<T, T>> entries) { var map = new Dictionary<T, T>(); var reverseMap = new Dictionary<T, T>(); foreach (var entry in entries) { map.Add(entry.Key, entry.Value); reverseMap.Add(entry.Value, entry.Key); } Forward = map; Reverse = reverseMap; } public static BidirectionalMap<T> FromMatch(Match<T> match) => new(match.Matches, match.ReverseMatches); public bool IsDefaultOrEmpty => Forward == null || Forward.Count == 0; } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpRenameFileToMatchTypeRefactoring.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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpRenameFileToMatchTypeRefactoring : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpRenameFileToMatchTypeRefactoring(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpGenerateFromUsage)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public void RenameFileToMatchType_ExistingCode() { var project = new ProjectUtils.Project(ProjectName); SetUpEditor(@"class $$MismatchedClassName { }"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Rename file to MismatchedClassName.cs", applyFix: true); // Ensure the file is still open in the editor, and that the file name change was made & saved VisualStudio.Editor.Verify.TextContains("class MismatchedClassName { }"); VisualStudio.SolutionExplorer.Verify.FileContents(project, "MismatchedClassName.cs", @"class MismatchedClassName { }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public void RenameFileToMatchType_InSubfolder() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, @"folder1\folder2\test.cs", open: true); SetUpEditor(@"class $$MismatchedClassName { }"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Rename file to MismatchedClassName.cs", applyFix: true); // Ensure the file is still open in the editor, and that the file name change was made & saved VisualStudio.Editor.Verify.TextContains("class MismatchedClassName { }"); VisualStudio.SolutionExplorer.Verify.FileContents(project, @"folder1\folder2\MismatchedClassName.cs", @"class MismatchedClassName { }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public void RenameFileToMatchType_UndoStackPreserved() { var project = new ProjectUtils.Project(ProjectName); SetUpEditor(@"$$class MismatchedClassName { }"); VisualStudio.Editor.SendKeys("public "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Rename file to MismatchedClassName.cs", applyFix: true); // Ensure the file is still open in the editor, and that the file name change was made & saved VisualStudio.Editor.Verify.CurrentLineText("public class MismatchedClassName { }"); VisualStudio.SolutionExplorer.Verify.FileContents(project, "MismatchedClassName.cs", @"public class MismatchedClassName { }"); // The first undo is for the file rename. VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("public class MismatchedClassName { }"); VisualStudio.SolutionExplorer.Verify.FileContents(project, "Class1.cs", @"public class MismatchedClassName { }"); // The second undo is for the text changes. VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("class MismatchedClassName { }"); // Redo the text changes VisualStudio.Editor.Redo(); VisualStudio.Editor.Verify.CurrentLineText("public class MismatchedClassName { }"); // Redo the file rename VisualStudio.Editor.Redo(); VisualStudio.SolutionExplorer.Verify.FileContents(project, "MismatchedClassName.cs", @"public class MismatchedClassName { }"); } } }
// 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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpRenameFileToMatchTypeRefactoring : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpRenameFileToMatchTypeRefactoring(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpGenerateFromUsage)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public void RenameFileToMatchType_ExistingCode() { var project = new ProjectUtils.Project(ProjectName); SetUpEditor(@"class $$MismatchedClassName { }"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Rename file to MismatchedClassName.cs", applyFix: true); // Ensure the file is still open in the editor, and that the file name change was made & saved VisualStudio.Editor.Verify.TextContains("class MismatchedClassName { }"); VisualStudio.SolutionExplorer.Verify.FileContents(project, "MismatchedClassName.cs", @"class MismatchedClassName { }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public void RenameFileToMatchType_InSubfolder() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, @"folder1\folder2\test.cs", open: true); SetUpEditor(@"class $$MismatchedClassName { }"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Rename file to MismatchedClassName.cs", applyFix: true); // Ensure the file is still open in the editor, and that the file name change was made & saved VisualStudio.Editor.Verify.TextContains("class MismatchedClassName { }"); VisualStudio.SolutionExplorer.Verify.FileContents(project, @"folder1\folder2\MismatchedClassName.cs", @"class MismatchedClassName { }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public void RenameFileToMatchType_UndoStackPreserved() { var project = new ProjectUtils.Project(ProjectName); SetUpEditor(@"$$class MismatchedClassName { }"); VisualStudio.Editor.SendKeys("public "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Rename file to MismatchedClassName.cs", applyFix: true); // Ensure the file is still open in the editor, and that the file name change was made & saved VisualStudio.Editor.Verify.CurrentLineText("public class MismatchedClassName { }"); VisualStudio.SolutionExplorer.Verify.FileContents(project, "MismatchedClassName.cs", @"public class MismatchedClassName { }"); // The first undo is for the file rename. VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("public class MismatchedClassName { }"); VisualStudio.SolutionExplorer.Verify.FileContents(project, "Class1.cs", @"public class MismatchedClassName { }"); // The second undo is for the text changes. VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("class MismatchedClassName { }"); // Redo the text changes VisualStudio.Editor.Redo(); VisualStudio.Editor.Verify.CurrentLineText("public class MismatchedClassName { }"); // Redo the file rename VisualStudio.Editor.Redo(); VisualStudio.SolutionExplorer.Verify.FileContents(project, "MismatchedClassName.cs", @"public class MismatchedClassName { }"); } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/EditorFeatures/TestUtilities/ExtractInterface/AbstractExtractInterfaceTests.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.VisualBasic; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.ExtractInterface { [UseExportProvider] public abstract class AbstractExtractInterfaceTests { public static async Task TestExtractInterfaceCommandCSharpAsync( string markup, bool expectedSuccess, string expectedMemberName = null, string expectedInterfaceName = null, string expectedNamespaceName = null, string expectedTypeParameterSuffix = null, string expectedUpdatedOriginalDocumentCode = null, string expectedInterfaceCode = null) { await TestExtractInterfaceCommandAsync( markup, LanguageNames.CSharp, expectedSuccess, expectedMemberName, expectedInterfaceName, expectedNamespaceName, expectedTypeParameterSuffix, expectedUpdatedOriginalDocumentCode, expectedInterfaceCode); } public static async Task TestExtractInterfaceCodeActionCSharpAsync( string markup, string expectedMarkup) { await TestExtractInterfaceCodeActionAsync( markup, LanguageNames.CSharp, expectedMarkup); } public static async Task TestExtractInterfaceCommandVisualBasicAsync( string markup, bool expectedSuccess, string expectedMemberName = null, string expectedInterfaceName = null, string expectedNamespaceName = null, string expectedTypeParameterSuffix = null, string expectedUpdatedOriginalDocumentCode = null, string expectedInterfaceCode = null, string rootNamespace = null) { await TestExtractInterfaceCommandAsync( markup, LanguageNames.VisualBasic, expectedSuccess, expectedMemberName, expectedInterfaceName, expectedNamespaceName, expectedTypeParameterSuffix, expectedUpdatedOriginalDocumentCode, expectedInterfaceCode, new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace: rootNamespace)); } public static async Task TestExtractInterfaceCodeActionVisualBasicAsync( string markup, string expectedMarkup) { await TestExtractInterfaceCodeActionAsync( markup, LanguageNames.VisualBasic, expectedMarkup); } private static async Task TestExtractInterfaceCommandAsync( string markup, string languageName, bool expectedSuccess, string expectedMemberName = null, string expectedInterfaceName = null, string expectedNamespaceName = null, string expectedTypeParameterSuffix = null, string expectedUpdatedOriginalDocumentCode = null, string expectedInterfaceCode = null, CompilationOptions compilationOptions = null) { using var testState = ExtractInterfaceTestState.Create(markup, languageName, compilationOptions); var result = await testState.ExtractViaCommandAsync(); if (expectedSuccess) { Assert.True(result.Succeeded); Assert.False(testState.Workspace.Documents.Select(d => d.Id).Contains(result.NavigationDocumentId)); Assert.NotNull(result.UpdatedSolution.GetDocument(result.NavigationDocumentId)); if (expectedMemberName != null) { Assert.Equal(1, testState.TestExtractInterfaceOptionsService.AllExtractableMembers.Count()); Assert.Equal(expectedMemberName, testState.TestExtractInterfaceOptionsService.AllExtractableMembers.Single().Name); } if (expectedInterfaceName != null) { Assert.Equal(expectedInterfaceName, testState.TestExtractInterfaceOptionsService.DefaultInterfaceName); } if (expectedNamespaceName != null) { Assert.Equal(expectedNamespaceName, testState.TestExtractInterfaceOptionsService.DefaultNamespace); } if (expectedTypeParameterSuffix != null) { Assert.Equal(expectedTypeParameterSuffix, testState.TestExtractInterfaceOptionsService.GeneratedNameTypeParameterSuffix); } if (expectedUpdatedOriginalDocumentCode != null) { var updatedOriginalDocument = result.UpdatedSolution.GetDocument(testState.ExtractFromDocument.Id); var updatedCode = (await updatedOriginalDocument.GetTextAsync()).ToString(); Assert.Equal(expectedUpdatedOriginalDocumentCode, updatedCode); } if (expectedInterfaceCode != null) { var interfaceDocument = result.UpdatedSolution.GetDocument(result.NavigationDocumentId); var interfaceCode = (await interfaceDocument.GetTextAsync()).ToString(); Assert.Equal(expectedInterfaceCode, interfaceCode); } } else { Assert.False(result.Succeeded); } } private static async Task TestExtractInterfaceCodeActionAsync( string markup, string languageName, string expectedMarkup, CompilationOptions compilationOptions = null) { using var testState = ExtractInterfaceTestState.Create(markup, languageName, compilationOptions); var updatedSolution = await testState.ExtractViaCodeAction(); var updatedDocument = updatedSolution.GetDocument(testState.ExtractFromDocument.Id); var updatedCode = (await updatedDocument.GetTextAsync()).ToString(); Assert.Equal(expectedMarkup, 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.VisualBasic; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.ExtractInterface { [UseExportProvider] public abstract class AbstractExtractInterfaceTests { public static async Task TestExtractInterfaceCommandCSharpAsync( string markup, bool expectedSuccess, string expectedMemberName = null, string expectedInterfaceName = null, string expectedNamespaceName = null, string expectedTypeParameterSuffix = null, string expectedUpdatedOriginalDocumentCode = null, string expectedInterfaceCode = null) { await TestExtractInterfaceCommandAsync( markup, LanguageNames.CSharp, expectedSuccess, expectedMemberName, expectedInterfaceName, expectedNamespaceName, expectedTypeParameterSuffix, expectedUpdatedOriginalDocumentCode, expectedInterfaceCode); } public static async Task TestExtractInterfaceCodeActionCSharpAsync( string markup, string expectedMarkup) { await TestExtractInterfaceCodeActionAsync( markup, LanguageNames.CSharp, expectedMarkup); } public static async Task TestExtractInterfaceCommandVisualBasicAsync( string markup, bool expectedSuccess, string expectedMemberName = null, string expectedInterfaceName = null, string expectedNamespaceName = null, string expectedTypeParameterSuffix = null, string expectedUpdatedOriginalDocumentCode = null, string expectedInterfaceCode = null, string rootNamespace = null) { await TestExtractInterfaceCommandAsync( markup, LanguageNames.VisualBasic, expectedSuccess, expectedMemberName, expectedInterfaceName, expectedNamespaceName, expectedTypeParameterSuffix, expectedUpdatedOriginalDocumentCode, expectedInterfaceCode, new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace: rootNamespace)); } public static async Task TestExtractInterfaceCodeActionVisualBasicAsync( string markup, string expectedMarkup) { await TestExtractInterfaceCodeActionAsync( markup, LanguageNames.VisualBasic, expectedMarkup); } private static async Task TestExtractInterfaceCommandAsync( string markup, string languageName, bool expectedSuccess, string expectedMemberName = null, string expectedInterfaceName = null, string expectedNamespaceName = null, string expectedTypeParameterSuffix = null, string expectedUpdatedOriginalDocumentCode = null, string expectedInterfaceCode = null, CompilationOptions compilationOptions = null) { using var testState = ExtractInterfaceTestState.Create(markup, languageName, compilationOptions); var result = await testState.ExtractViaCommandAsync(); if (expectedSuccess) { Assert.True(result.Succeeded); Assert.False(testState.Workspace.Documents.Select(d => d.Id).Contains(result.NavigationDocumentId)); Assert.NotNull(result.UpdatedSolution.GetDocument(result.NavigationDocumentId)); if (expectedMemberName != null) { Assert.Equal(1, testState.TestExtractInterfaceOptionsService.AllExtractableMembers.Count()); Assert.Equal(expectedMemberName, testState.TestExtractInterfaceOptionsService.AllExtractableMembers.Single().Name); } if (expectedInterfaceName != null) { Assert.Equal(expectedInterfaceName, testState.TestExtractInterfaceOptionsService.DefaultInterfaceName); } if (expectedNamespaceName != null) { Assert.Equal(expectedNamespaceName, testState.TestExtractInterfaceOptionsService.DefaultNamespace); } if (expectedTypeParameterSuffix != null) { Assert.Equal(expectedTypeParameterSuffix, testState.TestExtractInterfaceOptionsService.GeneratedNameTypeParameterSuffix); } if (expectedUpdatedOriginalDocumentCode != null) { var updatedOriginalDocument = result.UpdatedSolution.GetDocument(testState.ExtractFromDocument.Id); var updatedCode = (await updatedOriginalDocument.GetTextAsync()).ToString(); Assert.Equal(expectedUpdatedOriginalDocumentCode, updatedCode); } if (expectedInterfaceCode != null) { var interfaceDocument = result.UpdatedSolution.GetDocument(result.NavigationDocumentId); var interfaceCode = (await interfaceDocument.GetTextAsync()).ToString(); Assert.Equal(expectedInterfaceCode, interfaceCode); } } else { Assert.False(result.Succeeded); } } private static async Task TestExtractInterfaceCodeActionAsync( string markup, string languageName, string expectedMarkup, CompilationOptions compilationOptions = null) { using var testState = ExtractInterfaceTestState.Create(markup, languageName, compilationOptions); var updatedSolution = await testState.ExtractViaCodeAction(); var updatedDocument = updatedSolution.GetDocument(testState.ExtractFromDocument.Id); var updatedCode = (await updatedDocument.GetTextAsync()).ToString(); Assert.Equal(expectedMarkup, updatedCode); } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./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,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./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,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Compilers/CSharp/Portable/Declarations/DeclarationTreeBuilder.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.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class DeclarationTreeBuilder : CSharpSyntaxVisitor<SingleNamespaceOrTypeDeclaration> { private readonly SyntaxTree _syntaxTree; private readonly string _scriptClassName; private readonly bool _isSubmission; private DeclarationTreeBuilder(SyntaxTree syntaxTree, string scriptClassName, bool isSubmission) { _syntaxTree = syntaxTree; _scriptClassName = scriptClassName; _isSubmission = isSubmission; } public static RootSingleNamespaceDeclaration ForTree( SyntaxTree syntaxTree, string scriptClassName, bool isSubmission) { var builder = new DeclarationTreeBuilder(syntaxTree, scriptClassName, isSubmission); return (RootSingleNamespaceDeclaration)builder.Visit(syntaxTree.GetRoot()); } private ImmutableArray<SingleNamespaceOrTypeDeclaration> VisitNamespaceChildren( CSharpSyntaxNode node, SyntaxList<MemberDeclarationSyntax> members, CoreInternalSyntax.SyntaxList<Syntax.InternalSyntax.MemberDeclarationSyntax> internalMembers) { Debug.Assert( node.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration || (node.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind == SourceCodeKind.Regular)); if (members.Count == 0) { return ImmutableArray<SingleNamespaceOrTypeDeclaration>.Empty; } // We look for members that are not allowed in a namespace. // If there are any we create an implicit class to wrap them. bool hasGlobalMembers = false; bool acceptSimpleProgram = node.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind == SourceCodeKind.Regular; bool hasAwaitExpressions = false; bool isIterator = false; bool hasReturnWithExpression = false; GlobalStatementSyntax firstGlobalStatement = null; bool hasNonEmptyGlobalSatement = false; var childrenBuilder = ArrayBuilder<SingleNamespaceOrTypeDeclaration>.GetInstance(); foreach (var member in members) { SingleNamespaceOrTypeDeclaration namespaceOrType = Visit(member); if (namespaceOrType != null) { childrenBuilder.Add(namespaceOrType); } else if (acceptSimpleProgram && member.IsKind(SyntaxKind.GlobalStatement)) { var global = (GlobalStatementSyntax)member; firstGlobalStatement ??= global; var topLevelStatement = global.Statement; if (!topLevelStatement.IsKind(SyntaxKind.EmptyStatement)) { hasNonEmptyGlobalSatement = true; } if (!hasAwaitExpressions) { hasAwaitExpressions = SyntaxFacts.HasAwaitOperations(topLevelStatement); } if (!isIterator) { isIterator = SyntaxFacts.HasYieldOperations(topLevelStatement); } if (!hasReturnWithExpression) { hasReturnWithExpression = SyntaxFacts.HasReturnWithExpression(topLevelStatement); } } else if (!hasGlobalMembers && member.Kind() != SyntaxKind.IncompleteMember) { hasGlobalMembers = true; } } // wrap all global statements in a compilation unit into a simple program type: if (firstGlobalStatement is object) { var diagnostics = ImmutableArray<Diagnostic>.Empty; if (!hasNonEmptyGlobalSatement) { var bag = DiagnosticBag.GetInstance(); bag.Add(ErrorCode.ERR_SimpleProgramIsEmpty, ((EmptyStatementSyntax)firstGlobalStatement.Statement).SemicolonToken.GetLocation()); diagnostics = bag.ToReadOnlyAndFree(); } childrenBuilder.Add(CreateSimpleProgram(firstGlobalStatement, hasAwaitExpressions, isIterator, hasReturnWithExpression, diagnostics)); } // wrap all members that are defined in a namespace or compilation unit into an implicit type: if (hasGlobalMembers) { //The implicit class is not static and has no extensions SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; var memberNames = GetNonTypeMemberNames(internalMembers, ref declFlags, skipGlobalStatements: acceptSimpleProgram); var container = _syntaxTree.GetReference(node); childrenBuilder.Add(CreateImplicitClass(memberNames, container, declFlags)); } return childrenBuilder.ToImmutableAndFree(); } private static SingleNamespaceOrTypeDeclaration CreateImplicitClass(ImmutableSegmentedDictionary<string, VoidResult> memberNames, SyntaxReference container, SingleTypeDeclaration.TypeDeclarationFlags declFlags) { return new SingleTypeDeclaration( kind: DeclarationKind.ImplicitClass, name: TypeSymbol.ImplicitTypeName, arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed, declFlags: declFlags, syntaxReference: container, nameLocation: new SourceLocation(container), memberNames: memberNames, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: ImmutableArray<Diagnostic>.Empty); } private static SingleNamespaceOrTypeDeclaration CreateSimpleProgram(GlobalStatementSyntax firstGlobalStatement, bool hasAwaitExpressions, bool isIterator, bool hasReturnWithExpression, ImmutableArray<Diagnostic> diagnostics) { return new SingleTypeDeclaration( kind: DeclarationKind.SimpleProgram, name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Static, declFlags: (hasAwaitExpressions ? SingleTypeDeclaration.TypeDeclarationFlags.HasAwaitExpressions : SingleTypeDeclaration.TypeDeclarationFlags.None) | (isIterator ? SingleTypeDeclaration.TypeDeclarationFlags.IsIterator : SingleTypeDeclaration.TypeDeclarationFlags.None) | (hasReturnWithExpression ? SingleTypeDeclaration.TypeDeclarationFlags.HasReturnWithExpression : SingleTypeDeclaration.TypeDeclarationFlags.None), syntaxReference: firstGlobalStatement.SyntaxTree.GetReference(firstGlobalStatement.Parent), nameLocation: new SourceLocation(firstGlobalStatement.GetFirstToken()), memberNames: ImmutableSegmentedDictionary<string, VoidResult>.Empty, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics); } /// <summary> /// Creates a root declaration that contains a Script class declaration (possibly in a namespace) and namespace declarations. /// Top-level declarations in script code are nested in Script class. /// </summary> private RootSingleNamespaceDeclaration CreateScriptRootDeclaration(CompilationUnitSyntax compilationUnit) { Debug.Assert(_syntaxTree.Options.Kind != SourceCodeKind.Regular); var members = compilationUnit.Members; var rootChildren = ArrayBuilder<SingleNamespaceOrTypeDeclaration>.GetInstance(); var scriptChildren = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); foreach (var member in members) { var decl = Visit(member); if (decl != null) { // Although namespaces are not allowed in script code process them // here as if they were to improve error reporting. if (decl.Kind == DeclarationKind.Namespace) { rootChildren.Add(decl); } else { scriptChildren.Add((SingleTypeDeclaration)decl); } } } //Script class is not static and contains no extensions. SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; var membernames = GetNonTypeMemberNames(((Syntax.InternalSyntax.CompilationUnitSyntax)(compilationUnit.Green)).Members, ref declFlags); rootChildren.Add( CreateScriptClass( compilationUnit, scriptChildren.ToImmutableAndFree(), membernames, declFlags)); return CreateRootSingleNamespaceDeclaration(compilationUnit, rootChildren.ToImmutableAndFree(), isForScript: true); } private static ImmutableArray<ReferenceDirective> GetReferenceDirectives(CompilationUnitSyntax compilationUnit) { IList<ReferenceDirectiveTriviaSyntax> directiveNodes = compilationUnit.GetReferenceDirectives( d => !d.File.ContainsDiagnostics && !string.IsNullOrEmpty(d.File.ValueText)); if (directiveNodes.Count == 0) { return ImmutableArray<ReferenceDirective>.Empty; } var directives = ArrayBuilder<ReferenceDirective>.GetInstance(directiveNodes.Count); foreach (var directiveNode in directiveNodes) { directives.Add(new ReferenceDirective(directiveNode.File.ValueText, new SourceLocation(directiveNode))); } return directives.ToImmutableAndFree(); } private SingleNamespaceOrTypeDeclaration CreateScriptClass( CompilationUnitSyntax parent, ImmutableArray<SingleTypeDeclaration> children, ImmutableSegmentedDictionary<string, VoidResult> memberNames, SingleTypeDeclaration.TypeDeclarationFlags declFlags) { Debug.Assert(parent.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind != SourceCodeKind.Regular); // script type is represented by the parent node: var parentReference = _syntaxTree.GetReference(parent); var fullName = _scriptClassName.Split('.'); // Note: The symbol representing the merged declarations uses parentReference to enumerate non-type members. SingleNamespaceOrTypeDeclaration decl = new SingleTypeDeclaration( kind: _isSubmission ? DeclarationKind.Submission : DeclarationKind.Script, name: fullName.Last(), arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed, declFlags: declFlags, syntaxReference: parentReference, nameLocation: new SourceLocation(parentReference), memberNames: memberNames, children: children, diagnostics: ImmutableArray<Diagnostic>.Empty); for (int i = fullName.Length - 2; i >= 0; i--) { decl = SingleNamespaceDeclaration.Create( name: fullName[i], hasUsings: false, hasExternAliases: false, syntaxReference: parentReference, nameLocation: new SourceLocation(parentReference), children: ImmutableArray.Create(decl), diagnostics: ImmutableArray<Diagnostic>.Empty); } return decl; } public override SingleNamespaceOrTypeDeclaration VisitCompilationUnit(CompilationUnitSyntax compilationUnit) { if (_syntaxTree.Options.Kind != SourceCodeKind.Regular) { return CreateScriptRootDeclaration(compilationUnit); } var children = VisitNamespaceChildren(compilationUnit, compilationUnit.Members, ((Syntax.InternalSyntax.CompilationUnitSyntax)(compilationUnit.Green)).Members); return CreateRootSingleNamespaceDeclaration(compilationUnit, children, isForScript: false); } private RootSingleNamespaceDeclaration CreateRootSingleNamespaceDeclaration(CompilationUnitSyntax compilationUnit, ImmutableArray<SingleNamespaceOrTypeDeclaration> children, bool isForScript) { bool hasUsings = false; bool hasGlobalUsings = false; bool reportedGlobalUsingOutOfOrder = false; var diagnostics = DiagnosticBag.GetInstance(); foreach (var directive in compilationUnit.Usings) { if (directive.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) { hasGlobalUsings = true; if (hasUsings && !reportedGlobalUsingOutOfOrder) { reportedGlobalUsingOutOfOrder = true; diagnostics.Add(ErrorCode.ERR_GlobalUsingOutOfOrder, directive.GlobalKeyword.GetLocation()); } } else { hasUsings = true; } } return new RootSingleNamespaceDeclaration( hasGlobalUsings: hasGlobalUsings, hasUsings: hasUsings, hasExternAliases: compilationUnit.Externs.Any(), treeNode: _syntaxTree.GetReference(compilationUnit), children: children, referenceDirectives: isForScript ? GetReferenceDirectives(compilationUnit) : ImmutableArray<ReferenceDirective>.Empty, hasAssemblyAttributes: compilationUnit.AttributeLists.Any(), diagnostics: diagnostics.ToReadOnlyAndFree()); } public override SingleNamespaceOrTypeDeclaration VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) => this.VisitBaseNamespaceDeclaration(node); public override SingleNamespaceOrTypeDeclaration VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) => this.VisitBaseNamespaceDeclaration(node); private SingleNamespaceDeclaration VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax node) { var children = VisitNamespaceChildren(node, node.Members, ((Syntax.InternalSyntax.BaseNamespaceDeclarationSyntax)node.Green).Members); bool hasUsings = node.Usings.Any(); bool hasExterns = node.Externs.Any(); NameSyntax name = node.Name; CSharpSyntaxNode currentNode = node; QualifiedNameSyntax dotted; while ((dotted = name as QualifiedNameSyntax) != null) { var ns = SingleNamespaceDeclaration.Create( name: dotted.Right.Identifier.ValueText, hasUsings: hasUsings, hasExternAliases: hasExterns, syntaxReference: _syntaxTree.GetReference(currentNode), nameLocation: new SourceLocation(dotted.Right), children: children, diagnostics: ImmutableArray<Diagnostic>.Empty); var nsDeclaration = new[] { ns }; children = nsDeclaration.AsImmutableOrNull<SingleNamespaceOrTypeDeclaration>(); currentNode = name = dotted.Left; hasUsings = false; hasExterns = false; } var diagnostics = DiagnosticBag.GetInstance(); if (node is FileScopedNamespaceDeclarationSyntax) { if (node.Parent is FileScopedNamespaceDeclarationSyntax) { // Happens when user writes: // namespace A.B; // namespace X.Y; diagnostics.Add(ErrorCode.ERR_MultipleFileScopedNamespace, node.Name.GetLocation()); } else if (node.Parent is NamespaceDeclarationSyntax) { // Happens with: // // namespace A.B // { // namespace X.Y; diagnostics.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); } else { // Happens with cases like: // // namespace A.B { } // namespace X.Y; // // or even // // class C { } // namespace X.Y; Debug.Assert(node.Parent is CompilationUnitSyntax); var compilationUnit = (CompilationUnitSyntax)node.Parent; if (node != compilationUnit.Members[0]) { diagnostics.Add(ErrorCode.ERR_FileScopedNamespaceNotBeforeAllMembers, node.Name.GetLocation()); } } } else { Debug.Assert(node is NamespaceDeclarationSyntax); // namespace X.Y; // namespace A.B { } if (node.Parent is FileScopedNamespaceDeclarationSyntax) { diagnostics.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); } } if (ContainsGeneric(node.Name)) { // We're not allowed to have generics. diagnostics.Add(ErrorCode.ERR_UnexpectedGenericName, node.Name.GetLocation()); } if (ContainsAlias(node.Name)) { diagnostics.Add(ErrorCode.ERR_UnexpectedAliasedName, node.Name.GetLocation()); } if (node.AttributeLists.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadModifiersOnNamespace, node.AttributeLists[0].GetLocation()); } if (node.Modifiers.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadModifiersOnNamespace, node.Modifiers[0].GetLocation()); } foreach (var directive in node.Usings) { if (directive.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) { diagnostics.Add(ErrorCode.ERR_GlobalUsingInNamespace, directive.GlobalKeyword.GetLocation()); break; } } // NOTE: *Something* has to happen for alias-qualified names. It turns out that we // just grab the part after the colons (via GetUnqualifiedName, below). This logic // must be kept in sync with NamespaceSymbol.GetNestedNamespace. return SingleNamespaceDeclaration.Create( name: name.GetUnqualifiedName().Identifier.ValueText, hasUsings: hasUsings, hasExternAliases: hasExterns, syntaxReference: _syntaxTree.GetReference(currentNode), nameLocation: new SourceLocation(name), children: children, diagnostics: diagnostics.ToReadOnlyAndFree()); } private static bool ContainsAlias(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: return false; case SyntaxKind.AliasQualifiedName: return true; case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)name; return ContainsAlias(qualifiedName.Left); } return false; } private static bool ContainsGeneric(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: return true; case SyntaxKind.AliasQualifiedName: return ContainsGeneric(((AliasQualifiedNameSyntax)name).Name); case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)name; return ContainsGeneric(qualifiedName.Left) || ContainsGeneric(qualifiedName.Right); } return false; } public override SingleNamespaceOrTypeDeclaration VisitClassDeclaration(ClassDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Class); } public override SingleNamespaceOrTypeDeclaration VisitStructDeclaration(StructDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Struct); } public override SingleNamespaceOrTypeDeclaration VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Interface); } public override SingleNamespaceOrTypeDeclaration VisitRecordDeclaration(RecordDeclarationSyntax node) { var declarationKind = node.Kind() switch { SyntaxKind.RecordDeclaration => DeclarationKind.Record, SyntaxKind.RecordStructDeclaration => DeclarationKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()) }; return VisitTypeDeclaration(node, declarationKind); } private SingleNamespaceOrTypeDeclaration VisitTypeDeclaration(TypeDeclarationSyntax node, DeclarationKind kind) { SingleTypeDeclaration.TypeDeclarationFlags declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; if (node.BaseList != null) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; } var diagnostics = DiagnosticBag.GetInstance(); if (node.Arity == 0) { Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, diagnostics); } var memberNames = GetNonTypeMemberNames(((Syntax.InternalSyntax.TypeDeclarationSyntax)(node.Green)).Members, ref declFlags); // A record with parameters at least has a primary constructor if (((declFlags & SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers) == 0) && node is RecordDeclarationSyntax { ParameterList: { } }) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: kind, name: node.Identifier.ValueText, modifiers: modifiers, arity: node.Arity, declFlags: declFlags, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: memberNames, children: VisitTypeChildren(node), diagnostics: diagnostics.ToReadOnlyAndFree()); } private ImmutableArray<SingleTypeDeclaration> VisitTypeChildren(TypeDeclarationSyntax node) { if (node.Members.Count == 0) { return ImmutableArray<SingleTypeDeclaration>.Empty; } var children = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); foreach (var member in node.Members) { var typeDecl = Visit(member) as SingleTypeDeclaration; if (typeDecl != null) { children.Add(typeDecl); } } return children.ToImmutableAndFree(); } public override SingleNamespaceOrTypeDeclaration VisitDelegateDeclaration(DelegateDeclarationSyntax node) { var declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; var diagnostics = DiagnosticBag.GetInstance(); if (node.Arity == 0) { Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, diagnostics); } declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: DeclarationKind.Delegate, name: node.Identifier.ValueText, modifiers: modifiers, declFlags: declFlags, arity: node.Arity, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: ImmutableSegmentedDictionary<string, VoidResult>.Empty, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics.ToReadOnlyAndFree()); } public override SingleNamespaceOrTypeDeclaration VisitEnumDeclaration(EnumDeclarationSyntax node) { var members = node.Members; SingleTypeDeclaration.TypeDeclarationFlags declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; if (node.BaseList != null) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; } ImmutableSegmentedDictionary<string, VoidResult> memberNames = GetEnumMemberNames(members, ref declFlags); var diagnostics = DiagnosticBag.GetInstance(); var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: DeclarationKind.Enum, name: node.Identifier.ValueText, arity: 0, modifiers: modifiers, declFlags: declFlags, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: memberNames, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics.ToReadOnlyAndFree()); } private static readonly ObjectPool<ImmutableSegmentedDictionary<string, VoidResult>.Builder> s_memberNameBuilderPool = new ObjectPool<ImmutableSegmentedDictionary<string, VoidResult>.Builder>(() => ImmutableSegmentedDictionary.CreateBuilder<string, VoidResult>()); private static ImmutableSegmentedDictionary<string, VoidResult> ToImmutableAndFree(ImmutableSegmentedDictionary<string, VoidResult>.Builder builder) { var result = builder.ToImmutable(); builder.Clear(); s_memberNameBuilderPool.Free(builder); return result; } private static ImmutableSegmentedDictionary<string, VoidResult> GetEnumMemberNames(SeparatedSyntaxList<EnumMemberDeclarationSyntax> members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags) { var cnt = members.Count; var memberNamesBuilder = s_memberNameBuilderPool.Allocate(); if (cnt != 0) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } bool anyMemberHasAttributes = false; foreach (var member in members) { memberNamesBuilder.TryAdd(member.Identifier.ValueText); if (!anyMemberHasAttributes && member.AttributeLists.Any()) { anyMemberHasAttributes = true; } } if (anyMemberHasAttributes) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; } return ToImmutableAndFree(memberNamesBuilder); } private static ImmutableSegmentedDictionary<string, VoidResult> GetNonTypeMemberNames( CoreInternalSyntax.SyntaxList<Syntax.InternalSyntax.MemberDeclarationSyntax> members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags, bool skipGlobalStatements = false) { bool anyMethodHadExtensionSyntax = false; bool anyMemberHasAttributes = false; bool anyNonTypeMembers = false; var memberNameBuilder = s_memberNameBuilderPool.Allocate(); foreach (var member in members) { AddNonTypeMemberNames(member, memberNameBuilder, ref anyNonTypeMembers, skipGlobalStatements); // Check to see if any method contains a 'this' modifier on its first parameter. // This data is used to determine if a type needs to have its members materialized // as part of extension method lookup. if (!anyMethodHadExtensionSyntax && CheckMethodMemberForExtensionSyntax(member)) { anyMethodHadExtensionSyntax = true; } if (!anyMemberHasAttributes && CheckMemberForAttributes(member)) { anyMemberHasAttributes = true; } } if (anyMethodHadExtensionSyntax) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasExtensionMethodSyntax; } if (anyMemberHasAttributes) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; } if (anyNonTypeMembers) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } return ToImmutableAndFree(memberNameBuilder); } private static bool CheckMethodMemberForExtensionSyntax(Syntax.InternalSyntax.CSharpSyntaxNode member) { if (member.Kind == SyntaxKind.MethodDeclaration) { var methodDecl = (Syntax.InternalSyntax.MethodDeclarationSyntax)member; var paramList = methodDecl.parameterList; if (paramList != null) { var parameters = paramList.Parameters; if (parameters.Count != 0) { var firstParameter = parameters[0]; foreach (var modifier in firstParameter.Modifiers) { if (modifier.Kind == SyntaxKind.ThisKeyword) { return true; } } } } } return false; } private static bool CheckMemberForAttributes(Syntax.InternalSyntax.CSharpSyntaxNode member) { switch (member.Kind) { case SyntaxKind.CompilationUnit: return (((Syntax.InternalSyntax.CompilationUnitSyntax)member).AttributeLists).Any(); case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return (((Syntax.InternalSyntax.BaseTypeDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.DelegateDeclaration: return (((Syntax.InternalSyntax.DelegateDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: return (((Syntax.InternalSyntax.BaseFieldDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return (((Syntax.InternalSyntax.BaseMethodDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.PropertyDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: var baseProp = (Syntax.InternalSyntax.BasePropertyDeclarationSyntax)member; bool hasAttributes = baseProp.AttributeLists.Any(); if (!hasAttributes && baseProp.AccessorList != null) { foreach (var accessor in baseProp.AccessorList.Accessors) { hasAttributes |= accessor.AttributeLists.Any(); } } return hasAttributes; } return false; } private static void AddNonTypeMemberNames( Syntax.InternalSyntax.CSharpSyntaxNode member, ImmutableSegmentedDictionary<string, VoidResult>.Builder set, ref bool anyNonTypeMembers, bool skipGlobalStatements) { switch (member.Kind) { case SyntaxKind.FieldDeclaration: anyNonTypeMembers = true; CodeAnalysis.Syntax.InternalSyntax.SeparatedSyntaxList<Syntax.InternalSyntax.VariableDeclaratorSyntax> fieldDeclarators = ((Syntax.InternalSyntax.FieldDeclarationSyntax)member).Declaration.Variables; int numFieldDeclarators = fieldDeclarators.Count; for (int i = 0; i < numFieldDeclarators; i++) { set.TryAdd(fieldDeclarators[i].Identifier.ValueText); } break; case SyntaxKind.EventFieldDeclaration: anyNonTypeMembers = true; CoreInternalSyntax.SeparatedSyntaxList<Syntax.InternalSyntax.VariableDeclaratorSyntax> eventDeclarators = ((Syntax.InternalSyntax.EventFieldDeclarationSyntax)member).Declaration.Variables; int numEventDeclarators = eventDeclarators.Count; for (int i = 0; i < numEventDeclarators; i++) { set.TryAdd(eventDeclarators[i].Identifier.ValueText); } break; case SyntaxKind.MethodDeclaration: anyNonTypeMembers = true; // Member names are exposed via NamedTypeSymbol.MemberNames and are used primarily // as an acid test to determine whether a more in-depth search of a type is worthwhile. // We decided that it was reasonable to exclude explicit interface implementations // from the list of member names. var methodDecl = (Syntax.InternalSyntax.MethodDeclarationSyntax)member; if (methodDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(methodDecl.Identifier.ValueText); } break; case SyntaxKind.PropertyDeclaration: anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var propertyDecl = (Syntax.InternalSyntax.PropertyDeclarationSyntax)member; if (propertyDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(propertyDecl.Identifier.ValueText); } break; case SyntaxKind.EventDeclaration: anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var eventDecl = (Syntax.InternalSyntax.EventDeclarationSyntax)member; if (eventDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(eventDecl.Identifier.ValueText); } break; case SyntaxKind.ConstructorDeclaration: anyNonTypeMembers = true; set.TryAdd(((Syntax.InternalSyntax.ConstructorDeclarationSyntax)member).Modifiers.Any((int)SyntaxKind.StaticKeyword) ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName); break; case SyntaxKind.DestructorDeclaration: anyNonTypeMembers = true; set.TryAdd(WellKnownMemberNames.DestructorName); break; case SyntaxKind.IndexerDeclaration: anyNonTypeMembers = true; set.TryAdd(WellKnownMemberNames.Indexer); break; case SyntaxKind.OperatorDeclaration: { anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var opDecl = (Syntax.InternalSyntax.OperatorDeclarationSyntax)member; if (opDecl.ExplicitInterfaceSpecifier == null) { var name = OperatorFacts.OperatorNameFromDeclaration(opDecl); set.TryAdd(name); } } break; case SyntaxKind.ConversionOperatorDeclaration: { anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var opDecl = (Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)member; if (opDecl.ExplicitInterfaceSpecifier == null) { var name = OperatorFacts.OperatorNameFromDeclaration(opDecl); set.TryAdd(name); } } break; case SyntaxKind.GlobalStatement: if (!skipGlobalStatements) { anyNonTypeMembers = true; } break; } } } }
// 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.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class DeclarationTreeBuilder : CSharpSyntaxVisitor<SingleNamespaceOrTypeDeclaration> { private readonly SyntaxTree _syntaxTree; private readonly string _scriptClassName; private readonly bool _isSubmission; private DeclarationTreeBuilder(SyntaxTree syntaxTree, string scriptClassName, bool isSubmission) { _syntaxTree = syntaxTree; _scriptClassName = scriptClassName; _isSubmission = isSubmission; } public static RootSingleNamespaceDeclaration ForTree( SyntaxTree syntaxTree, string scriptClassName, bool isSubmission) { var builder = new DeclarationTreeBuilder(syntaxTree, scriptClassName, isSubmission); return (RootSingleNamespaceDeclaration)builder.Visit(syntaxTree.GetRoot()); } private ImmutableArray<SingleNamespaceOrTypeDeclaration> VisitNamespaceChildren( CSharpSyntaxNode node, SyntaxList<MemberDeclarationSyntax> members, CoreInternalSyntax.SyntaxList<Syntax.InternalSyntax.MemberDeclarationSyntax> internalMembers) { Debug.Assert( node.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration || (node.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind == SourceCodeKind.Regular)); if (members.Count == 0) { return ImmutableArray<SingleNamespaceOrTypeDeclaration>.Empty; } // We look for members that are not allowed in a namespace. // If there are any we create an implicit class to wrap them. bool hasGlobalMembers = false; bool acceptSimpleProgram = node.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind == SourceCodeKind.Regular; bool hasAwaitExpressions = false; bool isIterator = false; bool hasReturnWithExpression = false; GlobalStatementSyntax firstGlobalStatement = null; bool hasNonEmptyGlobalSatement = false; var childrenBuilder = ArrayBuilder<SingleNamespaceOrTypeDeclaration>.GetInstance(); foreach (var member in members) { SingleNamespaceOrTypeDeclaration namespaceOrType = Visit(member); if (namespaceOrType != null) { childrenBuilder.Add(namespaceOrType); } else if (acceptSimpleProgram && member.IsKind(SyntaxKind.GlobalStatement)) { var global = (GlobalStatementSyntax)member; firstGlobalStatement ??= global; var topLevelStatement = global.Statement; if (!topLevelStatement.IsKind(SyntaxKind.EmptyStatement)) { hasNonEmptyGlobalSatement = true; } if (!hasAwaitExpressions) { hasAwaitExpressions = SyntaxFacts.HasAwaitOperations(topLevelStatement); } if (!isIterator) { isIterator = SyntaxFacts.HasYieldOperations(topLevelStatement); } if (!hasReturnWithExpression) { hasReturnWithExpression = SyntaxFacts.HasReturnWithExpression(topLevelStatement); } } else if (!hasGlobalMembers && member.Kind() != SyntaxKind.IncompleteMember) { hasGlobalMembers = true; } } // wrap all global statements in a compilation unit into a simple program type: if (firstGlobalStatement is object) { var diagnostics = ImmutableArray<Diagnostic>.Empty; if (!hasNonEmptyGlobalSatement) { var bag = DiagnosticBag.GetInstance(); bag.Add(ErrorCode.ERR_SimpleProgramIsEmpty, ((EmptyStatementSyntax)firstGlobalStatement.Statement).SemicolonToken.GetLocation()); diagnostics = bag.ToReadOnlyAndFree(); } childrenBuilder.Add(CreateSimpleProgram(firstGlobalStatement, hasAwaitExpressions, isIterator, hasReturnWithExpression, diagnostics)); } // wrap all members that are defined in a namespace or compilation unit into an implicit type: if (hasGlobalMembers) { //The implicit class is not static and has no extensions SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; var memberNames = GetNonTypeMemberNames(internalMembers, ref declFlags, skipGlobalStatements: acceptSimpleProgram); var container = _syntaxTree.GetReference(node); childrenBuilder.Add(CreateImplicitClass(memberNames, container, declFlags)); } return childrenBuilder.ToImmutableAndFree(); } private static SingleNamespaceOrTypeDeclaration CreateImplicitClass(ImmutableSegmentedDictionary<string, VoidResult> memberNames, SyntaxReference container, SingleTypeDeclaration.TypeDeclarationFlags declFlags) { return new SingleTypeDeclaration( kind: DeclarationKind.ImplicitClass, name: TypeSymbol.ImplicitTypeName, arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed, declFlags: declFlags, syntaxReference: container, nameLocation: new SourceLocation(container), memberNames: memberNames, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: ImmutableArray<Diagnostic>.Empty); } private static SingleNamespaceOrTypeDeclaration CreateSimpleProgram(GlobalStatementSyntax firstGlobalStatement, bool hasAwaitExpressions, bool isIterator, bool hasReturnWithExpression, ImmutableArray<Diagnostic> diagnostics) { return new SingleTypeDeclaration( kind: DeclarationKind.SimpleProgram, name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Static, declFlags: (hasAwaitExpressions ? SingleTypeDeclaration.TypeDeclarationFlags.HasAwaitExpressions : SingleTypeDeclaration.TypeDeclarationFlags.None) | (isIterator ? SingleTypeDeclaration.TypeDeclarationFlags.IsIterator : SingleTypeDeclaration.TypeDeclarationFlags.None) | (hasReturnWithExpression ? SingleTypeDeclaration.TypeDeclarationFlags.HasReturnWithExpression : SingleTypeDeclaration.TypeDeclarationFlags.None), syntaxReference: firstGlobalStatement.SyntaxTree.GetReference(firstGlobalStatement.Parent), nameLocation: new SourceLocation(firstGlobalStatement.GetFirstToken()), memberNames: ImmutableSegmentedDictionary<string, VoidResult>.Empty, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics); } /// <summary> /// Creates a root declaration that contains a Script class declaration (possibly in a namespace) and namespace declarations. /// Top-level declarations in script code are nested in Script class. /// </summary> private RootSingleNamespaceDeclaration CreateScriptRootDeclaration(CompilationUnitSyntax compilationUnit) { Debug.Assert(_syntaxTree.Options.Kind != SourceCodeKind.Regular); var members = compilationUnit.Members; var rootChildren = ArrayBuilder<SingleNamespaceOrTypeDeclaration>.GetInstance(); var scriptChildren = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); foreach (var member in members) { var decl = Visit(member); if (decl != null) { // Although namespaces are not allowed in script code process them // here as if they were to improve error reporting. if (decl.Kind == DeclarationKind.Namespace) { rootChildren.Add(decl); } else { scriptChildren.Add((SingleTypeDeclaration)decl); } } } //Script class is not static and contains no extensions. SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; var membernames = GetNonTypeMemberNames(((Syntax.InternalSyntax.CompilationUnitSyntax)(compilationUnit.Green)).Members, ref declFlags); rootChildren.Add( CreateScriptClass( compilationUnit, scriptChildren.ToImmutableAndFree(), membernames, declFlags)); return CreateRootSingleNamespaceDeclaration(compilationUnit, rootChildren.ToImmutableAndFree(), isForScript: true); } private static ImmutableArray<ReferenceDirective> GetReferenceDirectives(CompilationUnitSyntax compilationUnit) { IList<ReferenceDirectiveTriviaSyntax> directiveNodes = compilationUnit.GetReferenceDirectives( d => !d.File.ContainsDiagnostics && !string.IsNullOrEmpty(d.File.ValueText)); if (directiveNodes.Count == 0) { return ImmutableArray<ReferenceDirective>.Empty; } var directives = ArrayBuilder<ReferenceDirective>.GetInstance(directiveNodes.Count); foreach (var directiveNode in directiveNodes) { directives.Add(new ReferenceDirective(directiveNode.File.ValueText, new SourceLocation(directiveNode))); } return directives.ToImmutableAndFree(); } private SingleNamespaceOrTypeDeclaration CreateScriptClass( CompilationUnitSyntax parent, ImmutableArray<SingleTypeDeclaration> children, ImmutableSegmentedDictionary<string, VoidResult> memberNames, SingleTypeDeclaration.TypeDeclarationFlags declFlags) { Debug.Assert(parent.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind != SourceCodeKind.Regular); // script type is represented by the parent node: var parentReference = _syntaxTree.GetReference(parent); var fullName = _scriptClassName.Split('.'); // Note: The symbol representing the merged declarations uses parentReference to enumerate non-type members. SingleNamespaceOrTypeDeclaration decl = new SingleTypeDeclaration( kind: _isSubmission ? DeclarationKind.Submission : DeclarationKind.Script, name: fullName.Last(), arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed, declFlags: declFlags, syntaxReference: parentReference, nameLocation: new SourceLocation(parentReference), memberNames: memberNames, children: children, diagnostics: ImmutableArray<Diagnostic>.Empty); for (int i = fullName.Length - 2; i >= 0; i--) { decl = SingleNamespaceDeclaration.Create( name: fullName[i], hasUsings: false, hasExternAliases: false, syntaxReference: parentReference, nameLocation: new SourceLocation(parentReference), children: ImmutableArray.Create(decl), diagnostics: ImmutableArray<Diagnostic>.Empty); } return decl; } public override SingleNamespaceOrTypeDeclaration VisitCompilationUnit(CompilationUnitSyntax compilationUnit) { if (_syntaxTree.Options.Kind != SourceCodeKind.Regular) { return CreateScriptRootDeclaration(compilationUnit); } var children = VisitNamespaceChildren(compilationUnit, compilationUnit.Members, ((Syntax.InternalSyntax.CompilationUnitSyntax)(compilationUnit.Green)).Members); return CreateRootSingleNamespaceDeclaration(compilationUnit, children, isForScript: false); } private RootSingleNamespaceDeclaration CreateRootSingleNamespaceDeclaration(CompilationUnitSyntax compilationUnit, ImmutableArray<SingleNamespaceOrTypeDeclaration> children, bool isForScript) { bool hasUsings = false; bool hasGlobalUsings = false; bool reportedGlobalUsingOutOfOrder = false; var diagnostics = DiagnosticBag.GetInstance(); foreach (var directive in compilationUnit.Usings) { if (directive.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) { hasGlobalUsings = true; if (hasUsings && !reportedGlobalUsingOutOfOrder) { reportedGlobalUsingOutOfOrder = true; diagnostics.Add(ErrorCode.ERR_GlobalUsingOutOfOrder, directive.GlobalKeyword.GetLocation()); } } else { hasUsings = true; } } return new RootSingleNamespaceDeclaration( hasGlobalUsings: hasGlobalUsings, hasUsings: hasUsings, hasExternAliases: compilationUnit.Externs.Any(), treeNode: _syntaxTree.GetReference(compilationUnit), children: children, referenceDirectives: isForScript ? GetReferenceDirectives(compilationUnit) : ImmutableArray<ReferenceDirective>.Empty, hasAssemblyAttributes: compilationUnit.AttributeLists.Any(), diagnostics: diagnostics.ToReadOnlyAndFree()); } public override SingleNamespaceOrTypeDeclaration VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) => this.VisitBaseNamespaceDeclaration(node); public override SingleNamespaceOrTypeDeclaration VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) => this.VisitBaseNamespaceDeclaration(node); private SingleNamespaceDeclaration VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax node) { var children = VisitNamespaceChildren(node, node.Members, ((Syntax.InternalSyntax.BaseNamespaceDeclarationSyntax)node.Green).Members); bool hasUsings = node.Usings.Any(); bool hasExterns = node.Externs.Any(); NameSyntax name = node.Name; CSharpSyntaxNode currentNode = node; QualifiedNameSyntax dotted; while ((dotted = name as QualifiedNameSyntax) != null) { var ns = SingleNamespaceDeclaration.Create( name: dotted.Right.Identifier.ValueText, hasUsings: hasUsings, hasExternAliases: hasExterns, syntaxReference: _syntaxTree.GetReference(currentNode), nameLocation: new SourceLocation(dotted.Right), children: children, diagnostics: ImmutableArray<Diagnostic>.Empty); var nsDeclaration = new[] { ns }; children = nsDeclaration.AsImmutableOrNull<SingleNamespaceOrTypeDeclaration>(); currentNode = name = dotted.Left; hasUsings = false; hasExterns = false; } var diagnostics = DiagnosticBag.GetInstance(); if (node is FileScopedNamespaceDeclarationSyntax) { if (node.Parent is FileScopedNamespaceDeclarationSyntax) { // Happens when user writes: // namespace A.B; // namespace X.Y; diagnostics.Add(ErrorCode.ERR_MultipleFileScopedNamespace, node.Name.GetLocation()); } else if (node.Parent is NamespaceDeclarationSyntax) { // Happens with: // // namespace A.B // { // namespace X.Y; diagnostics.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); } else { // Happens with cases like: // // namespace A.B { } // namespace X.Y; // // or even // // class C { } // namespace X.Y; Debug.Assert(node.Parent is CompilationUnitSyntax); var compilationUnit = (CompilationUnitSyntax)node.Parent; if (node != compilationUnit.Members[0]) { diagnostics.Add(ErrorCode.ERR_FileScopedNamespaceNotBeforeAllMembers, node.Name.GetLocation()); } } } else { Debug.Assert(node is NamespaceDeclarationSyntax); // namespace X.Y; // namespace A.B { } if (node.Parent is FileScopedNamespaceDeclarationSyntax) { diagnostics.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); } } if (ContainsGeneric(node.Name)) { // We're not allowed to have generics. diagnostics.Add(ErrorCode.ERR_UnexpectedGenericName, node.Name.GetLocation()); } if (ContainsAlias(node.Name)) { diagnostics.Add(ErrorCode.ERR_UnexpectedAliasedName, node.Name.GetLocation()); } if (node.AttributeLists.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadModifiersOnNamespace, node.AttributeLists[0].GetLocation()); } if (node.Modifiers.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadModifiersOnNamespace, node.Modifiers[0].GetLocation()); } foreach (var directive in node.Usings) { if (directive.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) { diagnostics.Add(ErrorCode.ERR_GlobalUsingInNamespace, directive.GlobalKeyword.GetLocation()); break; } } // NOTE: *Something* has to happen for alias-qualified names. It turns out that we // just grab the part after the colons (via GetUnqualifiedName, below). This logic // must be kept in sync with NamespaceSymbol.GetNestedNamespace. return SingleNamespaceDeclaration.Create( name: name.GetUnqualifiedName().Identifier.ValueText, hasUsings: hasUsings, hasExternAliases: hasExterns, syntaxReference: _syntaxTree.GetReference(currentNode), nameLocation: new SourceLocation(name), children: children, diagnostics: diagnostics.ToReadOnlyAndFree()); } private static bool ContainsAlias(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: return false; case SyntaxKind.AliasQualifiedName: return true; case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)name; return ContainsAlias(qualifiedName.Left); } return false; } private static bool ContainsGeneric(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: return true; case SyntaxKind.AliasQualifiedName: return ContainsGeneric(((AliasQualifiedNameSyntax)name).Name); case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)name; return ContainsGeneric(qualifiedName.Left) || ContainsGeneric(qualifiedName.Right); } return false; } public override SingleNamespaceOrTypeDeclaration VisitClassDeclaration(ClassDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Class); } public override SingleNamespaceOrTypeDeclaration VisitStructDeclaration(StructDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Struct); } public override SingleNamespaceOrTypeDeclaration VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Interface); } public override SingleNamespaceOrTypeDeclaration VisitRecordDeclaration(RecordDeclarationSyntax node) { var declarationKind = node.Kind() switch { SyntaxKind.RecordDeclaration => DeclarationKind.Record, SyntaxKind.RecordStructDeclaration => DeclarationKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()) }; return VisitTypeDeclaration(node, declarationKind); } private SingleNamespaceOrTypeDeclaration VisitTypeDeclaration(TypeDeclarationSyntax node, DeclarationKind kind) { SingleTypeDeclaration.TypeDeclarationFlags declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; if (node.BaseList != null) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; } var diagnostics = DiagnosticBag.GetInstance(); if (node.Arity == 0) { Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, diagnostics); } var memberNames = GetNonTypeMemberNames(((Syntax.InternalSyntax.TypeDeclarationSyntax)(node.Green)).Members, ref declFlags); // A record with parameters at least has a primary constructor if (((declFlags & SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers) == 0) && node is RecordDeclarationSyntax { ParameterList: { } }) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: kind, name: node.Identifier.ValueText, modifiers: modifiers, arity: node.Arity, declFlags: declFlags, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: memberNames, children: VisitTypeChildren(node), diagnostics: diagnostics.ToReadOnlyAndFree()); } private ImmutableArray<SingleTypeDeclaration> VisitTypeChildren(TypeDeclarationSyntax node) { if (node.Members.Count == 0) { return ImmutableArray<SingleTypeDeclaration>.Empty; } var children = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); foreach (var member in node.Members) { var typeDecl = Visit(member) as SingleTypeDeclaration; if (typeDecl != null) { children.Add(typeDecl); } } return children.ToImmutableAndFree(); } public override SingleNamespaceOrTypeDeclaration VisitDelegateDeclaration(DelegateDeclarationSyntax node) { var declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; var diagnostics = DiagnosticBag.GetInstance(); if (node.Arity == 0) { Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, diagnostics); } declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: DeclarationKind.Delegate, name: node.Identifier.ValueText, modifiers: modifiers, declFlags: declFlags, arity: node.Arity, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: ImmutableSegmentedDictionary<string, VoidResult>.Empty, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics.ToReadOnlyAndFree()); } public override SingleNamespaceOrTypeDeclaration VisitEnumDeclaration(EnumDeclarationSyntax node) { var members = node.Members; SingleTypeDeclaration.TypeDeclarationFlags declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; if (node.BaseList != null) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; } ImmutableSegmentedDictionary<string, VoidResult> memberNames = GetEnumMemberNames(members, ref declFlags); var diagnostics = DiagnosticBag.GetInstance(); var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: DeclarationKind.Enum, name: node.Identifier.ValueText, arity: 0, modifiers: modifiers, declFlags: declFlags, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: memberNames, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics.ToReadOnlyAndFree()); } private static readonly ObjectPool<ImmutableSegmentedDictionary<string, VoidResult>.Builder> s_memberNameBuilderPool = new ObjectPool<ImmutableSegmentedDictionary<string, VoidResult>.Builder>(() => ImmutableSegmentedDictionary.CreateBuilder<string, VoidResult>()); private static ImmutableSegmentedDictionary<string, VoidResult> ToImmutableAndFree(ImmutableSegmentedDictionary<string, VoidResult>.Builder builder) { var result = builder.ToImmutable(); builder.Clear(); s_memberNameBuilderPool.Free(builder); return result; } private static ImmutableSegmentedDictionary<string, VoidResult> GetEnumMemberNames(SeparatedSyntaxList<EnumMemberDeclarationSyntax> members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags) { var cnt = members.Count; var memberNamesBuilder = s_memberNameBuilderPool.Allocate(); if (cnt != 0) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } bool anyMemberHasAttributes = false; foreach (var member in members) { memberNamesBuilder.TryAdd(member.Identifier.ValueText); if (!anyMemberHasAttributes && member.AttributeLists.Any()) { anyMemberHasAttributes = true; } } if (anyMemberHasAttributes) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; } return ToImmutableAndFree(memberNamesBuilder); } private static ImmutableSegmentedDictionary<string, VoidResult> GetNonTypeMemberNames( CoreInternalSyntax.SyntaxList<Syntax.InternalSyntax.MemberDeclarationSyntax> members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags, bool skipGlobalStatements = false) { bool anyMethodHadExtensionSyntax = false; bool anyMemberHasAttributes = false; bool anyNonTypeMembers = false; var memberNameBuilder = s_memberNameBuilderPool.Allocate(); foreach (var member in members) { AddNonTypeMemberNames(member, memberNameBuilder, ref anyNonTypeMembers, skipGlobalStatements); // Check to see if any method contains a 'this' modifier on its first parameter. // This data is used to determine if a type needs to have its members materialized // as part of extension method lookup. if (!anyMethodHadExtensionSyntax && CheckMethodMemberForExtensionSyntax(member)) { anyMethodHadExtensionSyntax = true; } if (!anyMemberHasAttributes && CheckMemberForAttributes(member)) { anyMemberHasAttributes = true; } } if (anyMethodHadExtensionSyntax) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasExtensionMethodSyntax; } if (anyMemberHasAttributes) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; } if (anyNonTypeMembers) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } return ToImmutableAndFree(memberNameBuilder); } private static bool CheckMethodMemberForExtensionSyntax(Syntax.InternalSyntax.CSharpSyntaxNode member) { if (member.Kind == SyntaxKind.MethodDeclaration) { var methodDecl = (Syntax.InternalSyntax.MethodDeclarationSyntax)member; var paramList = methodDecl.parameterList; if (paramList != null) { var parameters = paramList.Parameters; if (parameters.Count != 0) { var firstParameter = parameters[0]; foreach (var modifier in firstParameter.Modifiers) { if (modifier.Kind == SyntaxKind.ThisKeyword) { return true; } } } } } return false; } private static bool CheckMemberForAttributes(Syntax.InternalSyntax.CSharpSyntaxNode member) { switch (member.Kind) { case SyntaxKind.CompilationUnit: return (((Syntax.InternalSyntax.CompilationUnitSyntax)member).AttributeLists).Any(); case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return (((Syntax.InternalSyntax.BaseTypeDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.DelegateDeclaration: return (((Syntax.InternalSyntax.DelegateDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: return (((Syntax.InternalSyntax.BaseFieldDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return (((Syntax.InternalSyntax.BaseMethodDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.PropertyDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: var baseProp = (Syntax.InternalSyntax.BasePropertyDeclarationSyntax)member; bool hasAttributes = baseProp.AttributeLists.Any(); if (!hasAttributes && baseProp.AccessorList != null) { foreach (var accessor in baseProp.AccessorList.Accessors) { hasAttributes |= accessor.AttributeLists.Any(); } } return hasAttributes; } return false; } private static void AddNonTypeMemberNames( Syntax.InternalSyntax.CSharpSyntaxNode member, ImmutableSegmentedDictionary<string, VoidResult>.Builder set, ref bool anyNonTypeMembers, bool skipGlobalStatements) { switch (member.Kind) { case SyntaxKind.FieldDeclaration: anyNonTypeMembers = true; CodeAnalysis.Syntax.InternalSyntax.SeparatedSyntaxList<Syntax.InternalSyntax.VariableDeclaratorSyntax> fieldDeclarators = ((Syntax.InternalSyntax.FieldDeclarationSyntax)member).Declaration.Variables; int numFieldDeclarators = fieldDeclarators.Count; for (int i = 0; i < numFieldDeclarators; i++) { set.TryAdd(fieldDeclarators[i].Identifier.ValueText); } break; case SyntaxKind.EventFieldDeclaration: anyNonTypeMembers = true; CoreInternalSyntax.SeparatedSyntaxList<Syntax.InternalSyntax.VariableDeclaratorSyntax> eventDeclarators = ((Syntax.InternalSyntax.EventFieldDeclarationSyntax)member).Declaration.Variables; int numEventDeclarators = eventDeclarators.Count; for (int i = 0; i < numEventDeclarators; i++) { set.TryAdd(eventDeclarators[i].Identifier.ValueText); } break; case SyntaxKind.MethodDeclaration: anyNonTypeMembers = true; // Member names are exposed via NamedTypeSymbol.MemberNames and are used primarily // as an acid test to determine whether a more in-depth search of a type is worthwhile. // We decided that it was reasonable to exclude explicit interface implementations // from the list of member names. var methodDecl = (Syntax.InternalSyntax.MethodDeclarationSyntax)member; if (methodDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(methodDecl.Identifier.ValueText); } break; case SyntaxKind.PropertyDeclaration: anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var propertyDecl = (Syntax.InternalSyntax.PropertyDeclarationSyntax)member; if (propertyDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(propertyDecl.Identifier.ValueText); } break; case SyntaxKind.EventDeclaration: anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var eventDecl = (Syntax.InternalSyntax.EventDeclarationSyntax)member; if (eventDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(eventDecl.Identifier.ValueText); } break; case SyntaxKind.ConstructorDeclaration: anyNonTypeMembers = true; set.TryAdd(((Syntax.InternalSyntax.ConstructorDeclarationSyntax)member).Modifiers.Any((int)SyntaxKind.StaticKeyword) ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName); break; case SyntaxKind.DestructorDeclaration: anyNonTypeMembers = true; set.TryAdd(WellKnownMemberNames.DestructorName); break; case SyntaxKind.IndexerDeclaration: anyNonTypeMembers = true; set.TryAdd(WellKnownMemberNames.Indexer); break; case SyntaxKind.OperatorDeclaration: { anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var opDecl = (Syntax.InternalSyntax.OperatorDeclarationSyntax)member; if (opDecl.ExplicitInterfaceSpecifier == null) { var name = OperatorFacts.OperatorNameFromDeclaration(opDecl); set.TryAdd(name); } } break; case SyntaxKind.ConversionOperatorDeclaration: { anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var opDecl = (Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)member; if (opDecl.ExplicitInterfaceSpecifier == null) { var name = OperatorFacts.OperatorNameFromDeclaration(opDecl); set.TryAdd(name); } } break; case SyntaxKind.GlobalStatement: if (!skipGlobalStatements) { anyNonTypeMembers = true; } break; } } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/ITemporaryStreamStorageExtensions.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.IO; namespace Microsoft.CodeAnalysis.Host { internal static class ITemporaryStreamStorageExtensions { public static void WriteAllLines(this ITemporaryStreamStorage storage, ImmutableArray<string> values) { using var stream = SerializableBytes.CreateWritableStream(); using var writer = new StreamWriter(stream); foreach (var value in values) { writer.WriteLine(value); } writer.Flush(); stream.Position = 0; storage.WriteStream(stream); } public static ImmutableArray<string> ReadLines(this ITemporaryStreamStorage storage) { return EnumerateLines(storage).ToImmutableArray(); } private static IEnumerable<string> EnumerateLines(ITemporaryStreamStorage storage) { using var stream = storage.ReadStream(); using var reader = new StreamReader(stream); string line; while ((line = reader.ReadLine()) != null) { yield return line; } } } }
// 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.IO; namespace Microsoft.CodeAnalysis.Host { internal static class ITemporaryStreamStorageExtensions { public static void WriteAllLines(this ITemporaryStreamStorage storage, ImmutableArray<string> values) { using var stream = SerializableBytes.CreateWritableStream(); using var writer = new StreamWriter(stream); foreach (var value in values) { writer.WriteLine(value); } writer.Flush(); stream.Position = 0; storage.WriteStream(stream); } public static ImmutableArray<string> ReadLines(this ITemporaryStreamStorage storage) { return EnumerateLines(storage).ToImmutableArray(); } private static IEnumerable<string> EnumerateLines(ITemporaryStreamStorage storage) { using var stream = storage.ReadStream(); using var reader = new StreamReader(stream); string line; while ((line = reader.ReadLine()) != null) { yield return line; } } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Features/CSharp/Portable/CodeRefactorings/UseRecursivePatterns/UseRecursivePatternsCodeRefactoringProvider.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.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseRecursivePatterns { using static SyntaxFactory; using static SyntaxKind; [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.UseRecursivePatterns), Shared] internal sealed class UseRecursivePatternsCodeRefactoringProvider : CodeRefactoringProvider { private static readonly PatternSyntax s_trueConstantPattern = ConstantPattern(LiteralExpression(TrueLiteralExpression)); private static readonly PatternSyntax s_falseConstantPattern = ConstantPattern(LiteralExpression(FalseLiteralExpression)); private static readonly Func<IdentifierNameSyntax, SemanticModel, bool> s_canConvertToSubpattern = (name, model) => model.GetSymbolInfo(name).Symbol is { IsStatic: false, Kind: SymbolKind.Property or SymbolKind.Field, ContainingType: not { SpecialType: SpecialType.System_Nullable_T } }; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UseRecursivePatternsCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) return; if (textSpan.Length > 0) return; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (((CSharpParseOptions)root.SyntaxTree.Options).LanguageVersion < LanguageVersion.CSharp9) return; var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var node = root.FindToken(textSpan.Start).Parent; var replacementFunc = GetReplacementFunc(node, model); if (replacementFunc is null) return; context.RegisterRefactoring( new MyCodeAction( CSharpFeaturesResources.Use_recursive_patterns, _ => Task.FromResult(document.WithSyntaxRoot(replacementFunc(root))), nameof(CSharpFeaturesResources.Use_recursive_patterns))); } private static Func<SyntaxNode, SyntaxNode>? GetReplacementFunc(SyntaxNode? node, SemanticModel model) => node switch { BinaryExpressionSyntax(LogicalAndExpression) logicalAnd => CombineLogicalAndOperands(logicalAnd, model), CasePatternSwitchLabelSyntax { WhenClause: { } whenClause } switchLabel => CombineWhenClauseCondition(switchLabel.Pattern, whenClause.Condition, model), SwitchExpressionArmSyntax { WhenClause: { } whenClause } switchArm => CombineWhenClauseCondition(switchArm.Pattern, whenClause.Condition, model), WhenClauseSyntax { Parent: CasePatternSwitchLabelSyntax switchLabel } whenClause => CombineWhenClauseCondition(switchLabel.Pattern, whenClause.Condition, model), WhenClauseSyntax { Parent: SwitchExpressionArmSyntax switchArm } whenClause => CombineWhenClauseCondition(switchArm.Pattern, whenClause.Condition, model), _ => null }; private static Func<SyntaxNode, SyntaxNode>? CombineLogicalAndOperands(BinaryExpressionSyntax logicalAnd, SemanticModel model) { if (TryDetermineReceiver(logicalAnd.Left, model) is not var (leftReceiver, leftTarget, leftFlipped) || TryDetermineReceiver(logicalAnd.Right, model) is not var (rightReceiver, rightTarget, rightFlipped)) { return null; } // If we have an is-expression on the left, first we check if there is a variable designation that's been used on the right-hand-side, // in which case, we'll convert and move the check inside the existing pattern, if possible. // For instance, `e is C c && c.p == 0` is converted to `e is C { p: 0 } c` if (leftTarget.Parent is IsPatternExpressionSyntax isPatternExpression && TryFindVariableDesignation(isPatternExpression.Pattern, rightReceiver, model) is var (containingPattern, rightNamesOpt)) { Debug.Assert(leftTarget == isPatternExpression.Pattern); Debug.Assert(leftReceiver == isPatternExpression.Expression); return root => { var rightPattern = CreatePattern(rightReceiver, rightTarget, rightFlipped); var rewrittenPattern = RewriteContainingPattern(containingPattern, rightPattern, rightNamesOpt); var replacement = isPatternExpression.ReplaceNode(containingPattern, rewrittenPattern); return root.ReplaceNode(logicalAnd, AdjustBinaryExpressionOperands(logicalAnd, replacement)); }; } if (TryGetCommonReceiver(leftReceiver, rightReceiver, model) is var (commonReceiver, leftNames, rightNames)) { return root => { var leftSubpattern = CreateSubpattern(leftNames, CreatePattern(leftReceiver, leftTarget, leftFlipped)); var rightSubpattern = CreateSubpattern(rightNames, CreatePattern(rightReceiver, rightTarget, rightFlipped)); // If the common receiver is null, it's an implicit `this` reference in source. // For instance, `prop == 1 && field == 2` would be converted to `this is { prop: 1, field: 2 }` var replacement = IsPatternExpression(commonReceiver, RecursivePattern(leftSubpattern, rightSubpattern)); return root.ReplaceNode(logicalAnd, AdjustBinaryExpressionOperands(logicalAnd, replacement)); }; } return null; static SyntaxNode AdjustBinaryExpressionOperands(BinaryExpressionSyntax logicalAnd, ExpressionSyntax replacement) { // If there's a `&&` on the left, we have picked the right-hand-side for the combination. // In which case, we should replace that instead of the whole `&&` operator in a chain. // For instance, `expr && a.b == 1 && a.c == 2` is converted to `expr && a is { b: 1, c: 2 }` if (logicalAnd.Left is BinaryExpressionSyntax(LogicalAndExpression) leftExpression) replacement = leftExpression.WithRight(replacement); return replacement.ConvertToSingleLine().WithAdditionalAnnotations(Formatter.Annotation); } } private static Func<SyntaxNode, SyntaxNode>? CombineWhenClauseCondition(PatternSyntax switchPattern, ExpressionSyntax condition, SemanticModel model) { if (TryDetermineReceiver(condition, model, inWhenClause: true) is not var (receiver, target, flipped) || TryFindVariableDesignation(switchPattern, receiver, model) is not var (containingPattern, namesOpt)) { return null; } return root => { var editor = new SyntaxEditor(root, CSharpSyntaxGenerator.Instance); switch (receiver.GetRequiredParent().Parent) { // This is the leftmost `&&` operand in a when-clause. Remove the left-hand-side which we've just morphed in the switch pattern. // For instance, `case { p: var v } when v.q == 1 && expr:` would be converted to `case { p: { q: 1 } } v when expr:` case BinaryExpressionSyntax(LogicalAndExpression) logicalAnd: editor.ReplaceNode(logicalAnd, logicalAnd.Right); break; // If we reach here, there's no other expression left in the when-clause. Remove. // For instance, `case { p: var v } when v.q == 1:` would be converted to `case { p: { q: 1 } v }:` case WhenClauseSyntax whenClause: editor.RemoveNode(whenClause, SyntaxRemoveOptions.AddElasticMarker); break; case var v: throw ExceptionUtilities.UnexpectedValue(v); } var generatedPattern = CreatePattern(receiver, target, flipped); var rewrittenPattern = RewriteContainingPattern(containingPattern, generatedPattern, namesOpt); editor.ReplaceNode(containingPattern, rewrittenPattern); return editor.GetChangedRoot(); }; } private static PatternSyntax RewriteContainingPattern( PatternSyntax containingPattern, PatternSyntax generatedPattern, ImmutableArray<IdentifierNameSyntax> namesOpt) { // This is a variable designation match. We'll try to combine the generated // pattern from the right-hand-side into the containing pattern of this designation. var rewrittenPattern = namesOpt.IsDefault // If there's no name, we will combine the pattern itself. ? Combine(containingPattern, generatedPattern) // Otherwise, we generate a subpattern per each name and rewrite as a recursive pattern. : AddSubpattern(containingPattern, CreateSubpattern(namesOpt, generatedPattern)); return rewrittenPattern.ConvertToSingleLine().WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation); static PatternSyntax Combine(PatternSyntax containingPattern, PatternSyntax generatedPattern) { // We know we have a var-pattern, declaration-pattern or a recursive-pattern on the left as the containing node of the variable designation. // Depending on the generated pattern off of the expression on the right, we can give a better result by morphing it into the existing match. return (containingPattern, generatedPattern) switch { // e.g. `e is var x && x is { p: 1 }` => `e is { p: 1 } x` (VarPatternSyntax var, RecursivePatternSyntax { Designation: null } recursive) => recursive.WithDesignation(var.Designation), // e.g. `e is C x && x is { p: 1 }` => `is C { p: 1 } x` (DeclarationPatternSyntax decl, RecursivePatternSyntax { Type: null, Designation: null } recursive) => recursive.WithType(decl.Type).WithDesignation(decl.Designation), // e.g. `e is { p: 1 } x && x is C` => `is C { p: 1 } x` (RecursivePatternSyntax { Type: null } recursive, TypePatternSyntax type) => recursive.WithType(type.Type), // e.g. `e is { p: 1 } x && x is { q: 2 }` => `e is { p: 1, q: 2 } x` (RecursivePatternSyntax recursive, RecursivePatternSyntax { Type: null, Designation: null } other) when recursive.PositionalPatternClause is null || other.PositionalPatternClause is null => recursive .WithPositionalPatternClause(recursive.PositionalPatternClause ?? other.PositionalPatternClause) .WithPropertyPatternClause(Concat(recursive.PropertyPatternClause, other.PropertyPatternClause)), // In any other case, we fallback to an `and` pattern. // UNDONE: This may result in a few unused variables which should be removed in a later pass. _ => BinaryPattern(AndPattern, containingPattern.Parenthesize(), generatedPattern.Parenthesize()), }; } static PatternSyntax AddSubpattern(PatternSyntax containingPattern, SubpatternSyntax subpattern) { return containingPattern switch { // e.g. `case var x when x.p is 1` => `case { p: 1 } x` VarPatternSyntax p => RecursivePattern(type: null, subpattern, p.Designation), // e.g. `case Type x when x.p is 1` => `case Type { p: 1 } x` DeclarationPatternSyntax p => RecursivePattern(p.Type, subpattern, p.Designation), // e.g. `case { p: 1 } x when x.q is 2` => `case { p: 1, q: 2 } x` RecursivePatternSyntax p => p.AddPropertyPatternClauseSubpatterns(subpattern), // We've already checked that the designation is contained in any of the above pattern forms. var p => throw ExceptionUtilities.UnexpectedValue(p) }; } static PropertyPatternClauseSyntax? Concat(PropertyPatternClauseSyntax? left, PropertyPatternClauseSyntax? right) { if (left is null || right is null) return left ?? right; var leftSubpatterns = left.Subpatterns.GetWithSeparators(); if (leftSubpatterns.Any() && !leftSubpatterns.Last().IsToken) leftSubpatterns = leftSubpatterns.Add(Token(CommaToken)); var rightSubpatterns = right.Subpatterns.GetWithSeparators(); var list = new SyntaxNodeOrTokenList(leftSubpatterns.Concat(rightSubpatterns)); return left.WithSubpatterns(SeparatedList<SubpatternSyntax>(list)); } } private static PatternSyntax CreatePattern(ExpressionSyntax originalReceiver, ExpressionOrPatternSyntax target, bool flipped) { return target switch { // A pattern come from an `is` expression on either side of `&&` PatternSyntax pattern => pattern, TypeSyntax type when originalReceiver.IsParentKind(IsExpression) => TypePattern(type), // Otherwise, this is a constant. Depending on the original receiver, we create an appropriate pattern. ExpressionSyntax constant => originalReceiver.Parent switch { BinaryExpressionSyntax(EqualsExpression) => ConstantPattern(constant), BinaryExpressionSyntax(NotEqualsExpression) => UnaryPattern(ConstantPattern(constant)), BinaryExpressionSyntax(GreaterThanExpression or GreaterThanOrEqualExpression or LessThanOrEqualExpression or LessThanExpression) e => RelationalPattern(flipped ? Flip(e.OperatorToken) : e.OperatorToken, constant), var v => throw ExceptionUtilities.UnexpectedValue(v), }, var v => throw ExceptionUtilities.UnexpectedValue(v), }; static SyntaxToken Flip(SyntaxToken token) { return Token(token.Kind() switch { LessThanToken => GreaterThanToken, LessThanEqualsToken => GreaterThanEqualsToken, GreaterThanEqualsToken => LessThanEqualsToken, GreaterThanToken => LessThanToken, var v => throw ExceptionUtilities.UnexpectedValue(v) }); } } private static (PatternSyntax ContainingPattern, ImmutableArray<IdentifierNameSyntax> NamesOpt)? TryFindVariableDesignation( PatternSyntax leftPattern, ExpressionSyntax rightReceiver, SemanticModel model) { using var _ = ArrayBuilder<IdentifierNameSyntax>.GetInstance(out var names); if (GetInnermostReceiver(rightReceiver, names, model) is not IdentifierNameSyntax identifierName) return null; var designation = leftPattern.DescendantNodes() .OfType<SingleVariableDesignationSyntax>() .Where(d => d.Identifier.ValueText == identifierName.Identifier.ValueText) .FirstOrDefault(); if (designation is not { Parent: PatternSyntax containingPattern }) return null; // Only the following patterns can directly contain a variable designation. // Note: While a parenthesized designation can also contain other variables, // it is not a pattern, so it would not get past the PatternSyntax test above. Debug.Assert(containingPattern.IsKind(SyntaxKind.VarPattern, SyntaxKind.DeclarationPattern, SyntaxKind.RecursivePattern)); return (containingPattern, names.ToImmutableOrNull()); } private static (ExpressionSyntax Receiver, ExpressionOrPatternSyntax Target, bool Flipped)? TryDetermineReceiver( ExpressionSyntax node, SemanticModel model, bool inWhenClause = false) { return node switch { // For comparison operators, after we have determined the // constant operand, we rewrite it as a constant or relational pattern. BinaryExpressionSyntax(EqualsExpression or NotEqualsExpression or GreaterThanExpression or GreaterThanOrEqualExpression or LessThanOrEqualExpression or LessThanExpression) expr => TryDetermineConstant(expr, model), // If we found a `&&` here, there's two possibilities: // // 1) If we're in a when-clause, we look for the leftmost expression // which we will try to combine with the switch arm/label pattern. // For instance, we return `a` if we have `case <pat> when a && b && c`. // // 2) Otherwise, we will return the operand that *appears* to be on the left in the source. // For instance, we return `a` if we have `x && a && b` with the cursor on the second operator. // Since `&&` is left-associative, it's guaranteed to be the expression that we want. // For simplicity, we won't descend into any parenthesized expression here. // BinaryExpressionSyntax(LogicalAndExpression) expr => TryDetermineReceiver(inWhenClause ? expr.Left : expr.Right, model, inWhenClause), // If we have an `is` operator, we'll try to combine the existing pattern/type with the other operand. BinaryExpressionSyntax(IsExpression) { Right: NullableTypeSyntax type } expr => (expr.Left, type.ElementType, Flipped: false), BinaryExpressionSyntax(IsExpression) { Right: TypeSyntax type } expr => (expr.Left, type, Flipped: false), IsPatternExpressionSyntax expr => (expr.Expression, expr.Pattern, Flipped: false), // We treat any other expression as if they were compared to true/false. // For instance, `a.b && !a.c` will be converted to `a is { b: true, c: false }` PrefixUnaryExpressionSyntax(LogicalNotExpression) expr => (expr.Operand, s_falseConstantPattern, Flipped: false), var expr => (expr, s_trueConstantPattern, Flipped: false), }; static (ExpressionSyntax Expression, ExpressionSyntax Constant, bool Flipped)? TryDetermineConstant(BinaryExpressionSyntax node, SemanticModel model) { return (node.Left, node.Right) switch { var (left, right) when model.GetConstantValue(left).HasValue => (right, left, Flipped: true), var (left, right) when model.GetConstantValue(right).HasValue => (left, right, Flipped: false), _ => null }; } } private static SubpatternSyntax CreateSubpattern(ImmutableArray<IdentifierNameSyntax> names, PatternSyntax pattern) { Debug.Assert(!names.IsDefaultOrEmpty); var subpattern = Subpattern(names[0], pattern); for (var i = 1; i < names.Length; i++) subpattern = Subpattern(names[i], RecursivePattern(subpattern)); return subpattern; } private static SubpatternSyntax Subpattern(IdentifierNameSyntax name, PatternSyntax pattern) => SyntaxFactory.Subpattern(NameColon(name), pattern); private static RecursivePatternSyntax RecursivePattern(params SubpatternSyntax[] subpatterns) => SyntaxFactory.RecursivePattern(type: null, positionalPatternClause: null, PropertyPatternClause(SeparatedList(subpatterns)), designation: null); private static RecursivePatternSyntax RecursivePattern(TypeSyntax? type, SubpatternSyntax subpattern, VariableDesignationSyntax? designation) => SyntaxFactory.RecursivePattern(type, positionalPatternClause: null, PropertyPatternClause(SingletonSeparatedList(subpattern)), designation); private static RecursivePatternSyntax RecursivePattern(SubpatternSyntax subpattern) => RecursivePattern(type: null, subpattern, designation: null); /// <summary> /// Obtain the outermost common receiver between two expressions. This can succeed with a null 'CommonReceiver' /// in the case that the common receiver is the 'implicit this'. /// </summary> private static (ExpressionSyntax CommonReceiver, ImmutableArray<IdentifierNameSyntax> LeftNames, ImmutableArray<IdentifierNameSyntax> RightNames)? TryGetCommonReceiver( ExpressionSyntax left, ExpressionSyntax right, SemanticModel model) { using var _1 = ArrayBuilder<IdentifierNameSyntax>.GetInstance(out var leftNames); using var _2 = ArrayBuilder<IdentifierNameSyntax>.GetInstance(out var rightNames); if (!TryGetInnermostReceiver(left, leftNames, out var leftReceiver, model) || !TryGetInnermostReceiver(right, rightNames, out var rightReceiver, model) || !AreEquivalent(leftReceiver, rightReceiver)) // We must have a common starting point to proceed. { return null; } var commonReceiver = leftReceiver; // To reduce noise on superfluous subpatterns and avoid duplicates, skip any common name in the path. var lastName = SkipCommonNames(leftNames, rightNames); if (lastName is not null) { // If there were some common names in the path, we rewrite the receiver to include those. // For instance, in `a.b.c && a.b.d`, we have `b` as the last common name in the path, // So we want `a.b` as the receiver so that we convert it to `a.b is { c: true, d: true }`. commonReceiver = GetInnermostReceiver(left, lastName, static (identifierName, lastName) => identifierName != lastName); } return (commonReceiver ?? ThisExpression(), leftNames.ToImmutable(), rightNames.ToImmutable()); static bool TryGetInnermostReceiver(ExpressionSyntax node, ArrayBuilder<IdentifierNameSyntax> builder, [NotNullWhen(true)] out ExpressionSyntax? receiver, SemanticModel model) { receiver = GetInnermostReceiver(node, builder, model); return builder.Any(); } static IdentifierNameSyntax? SkipCommonNames(ArrayBuilder<IdentifierNameSyntax> leftNames, ArrayBuilder<IdentifierNameSyntax> rightNames) { IdentifierNameSyntax? lastName = null; int leftIndex, rightIndex; // Note: we don't want to skip the first name to still be able to convert to a subpattern, hence checking `> 0` below. for (leftIndex = leftNames.Count - 1, rightIndex = rightNames.Count - 1; leftIndex > 0 && rightIndex > 0; leftIndex--, rightIndex--) { var leftName = leftNames[leftIndex]; var rightName = rightNames[rightIndex]; if (!AreEquivalent(leftName, rightName)) break; lastName = leftName; } leftNames.Clip(leftIndex + 1); rightNames.Clip(rightIndex + 1); return lastName; } } private static ExpressionSyntax? GetInnermostReceiver(ExpressionSyntax node, ArrayBuilder<IdentifierNameSyntax> builder, SemanticModel model) => GetInnermostReceiver(node, model, s_canConvertToSubpattern, builder); private static ExpressionSyntax? GetInnermostReceiver<TArg>( ExpressionSyntax node, TArg arg, Func<IdentifierNameSyntax, TArg, bool> canConvertToSubpattern, ArrayBuilder<IdentifierNameSyntax>? builder = null) { return GetInnermostReceiver(node); ExpressionSyntax? GetInnermostReceiver(ExpressionSyntax node) { switch (node) { case IdentifierNameSyntax name when canConvertToSubpattern(name, arg): builder?.Add(name); // This is a member reference with an implicit `this` receiver. // We know this is true because we already checked canConvertToSubpattern. // Any other name outside the receiver position is captured in the cases below. return null; case MemberBindingExpressionSyntax { Name: IdentifierNameSyntax name } when canConvertToSubpattern(name, arg): builder?.Add(name); // We only reach here from a parent conditional-access. // Returning null here means that all the names on the right were convertible to a property pattern. return null; case MemberAccessExpressionSyntax(SimpleMemberAccessExpression) { Name: IdentifierNameSyntax name } memberAccess when canConvertToSubpattern(name, arg) && !memberAccess.Expression.IsKind(SyntaxKind.BaseExpression): builder?.Add(name); // For a simple member access we simply record the name and descend into the expression on the left-hand-side. return GetInnermostReceiver(memberAccess.Expression); case ConditionalAccessExpressionSyntax conditionalAccess: // For a conditional access, first we need to verify the right-hand-side is convertible to a property pattern. var right = GetInnermostReceiver(conditionalAccess.WhenNotNull); if (right is not null) { // If it has it's own receiver other than a member-binding expression, we return this node as the receiver. // For instance, if we had `a?.M().b`, the name `b` is already captured, so we need to return `a?.M()` as the innermost receiver. // If there was no name, this call returns itself, e.g. in `a?.M()` the receiver is the entire existing conditional access. return conditionalAccess.WithWhenNotNull(right); } // Otherwise, descend into the the expression on the left-hand-side. return GetInnermostReceiver(conditionalAccess.Expression); default: return node; } } } private sealed class MyCodeAction : CodeActions.CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } } }
// 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.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseRecursivePatterns { using static SyntaxFactory; using static SyntaxKind; [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.UseRecursivePatterns), Shared] internal sealed class UseRecursivePatternsCodeRefactoringProvider : CodeRefactoringProvider { private static readonly PatternSyntax s_trueConstantPattern = ConstantPattern(LiteralExpression(TrueLiteralExpression)); private static readonly PatternSyntax s_falseConstantPattern = ConstantPattern(LiteralExpression(FalseLiteralExpression)); private static readonly Func<IdentifierNameSyntax, SemanticModel, bool> s_canConvertToSubpattern = (name, model) => model.GetSymbolInfo(name).Symbol is { IsStatic: false, Kind: SymbolKind.Property or SymbolKind.Field, ContainingType: not { SpecialType: SpecialType.System_Nullable_T } }; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UseRecursivePatternsCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) return; if (textSpan.Length > 0) return; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (((CSharpParseOptions)root.SyntaxTree.Options).LanguageVersion < LanguageVersion.CSharp9) return; var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var node = root.FindToken(textSpan.Start).Parent; var replacementFunc = GetReplacementFunc(node, model); if (replacementFunc is null) return; context.RegisterRefactoring( new MyCodeAction( CSharpFeaturesResources.Use_recursive_patterns, _ => Task.FromResult(document.WithSyntaxRoot(replacementFunc(root))), nameof(CSharpFeaturesResources.Use_recursive_patterns))); } private static Func<SyntaxNode, SyntaxNode>? GetReplacementFunc(SyntaxNode? node, SemanticModel model) => node switch { BinaryExpressionSyntax(LogicalAndExpression) logicalAnd => CombineLogicalAndOperands(logicalAnd, model), CasePatternSwitchLabelSyntax { WhenClause: { } whenClause } switchLabel => CombineWhenClauseCondition(switchLabel.Pattern, whenClause.Condition, model), SwitchExpressionArmSyntax { WhenClause: { } whenClause } switchArm => CombineWhenClauseCondition(switchArm.Pattern, whenClause.Condition, model), WhenClauseSyntax { Parent: CasePatternSwitchLabelSyntax switchLabel } whenClause => CombineWhenClauseCondition(switchLabel.Pattern, whenClause.Condition, model), WhenClauseSyntax { Parent: SwitchExpressionArmSyntax switchArm } whenClause => CombineWhenClauseCondition(switchArm.Pattern, whenClause.Condition, model), _ => null }; private static Func<SyntaxNode, SyntaxNode>? CombineLogicalAndOperands(BinaryExpressionSyntax logicalAnd, SemanticModel model) { if (TryDetermineReceiver(logicalAnd.Left, model) is not var (leftReceiver, leftTarget, leftFlipped) || TryDetermineReceiver(logicalAnd.Right, model) is not var (rightReceiver, rightTarget, rightFlipped)) { return null; } // If we have an is-expression on the left, first we check if there is a variable designation that's been used on the right-hand-side, // in which case, we'll convert and move the check inside the existing pattern, if possible. // For instance, `e is C c && c.p == 0` is converted to `e is C { p: 0 } c` if (leftTarget.Parent is IsPatternExpressionSyntax isPatternExpression && TryFindVariableDesignation(isPatternExpression.Pattern, rightReceiver, model) is var (containingPattern, rightNamesOpt)) { Debug.Assert(leftTarget == isPatternExpression.Pattern); Debug.Assert(leftReceiver == isPatternExpression.Expression); return root => { var rightPattern = CreatePattern(rightReceiver, rightTarget, rightFlipped); var rewrittenPattern = RewriteContainingPattern(containingPattern, rightPattern, rightNamesOpt); var replacement = isPatternExpression.ReplaceNode(containingPattern, rewrittenPattern); return root.ReplaceNode(logicalAnd, AdjustBinaryExpressionOperands(logicalAnd, replacement)); }; } if (TryGetCommonReceiver(leftReceiver, rightReceiver, model) is var (commonReceiver, leftNames, rightNames)) { return root => { var leftSubpattern = CreateSubpattern(leftNames, CreatePattern(leftReceiver, leftTarget, leftFlipped)); var rightSubpattern = CreateSubpattern(rightNames, CreatePattern(rightReceiver, rightTarget, rightFlipped)); // If the common receiver is null, it's an implicit `this` reference in source. // For instance, `prop == 1 && field == 2` would be converted to `this is { prop: 1, field: 2 }` var replacement = IsPatternExpression(commonReceiver, RecursivePattern(leftSubpattern, rightSubpattern)); return root.ReplaceNode(logicalAnd, AdjustBinaryExpressionOperands(logicalAnd, replacement)); }; } return null; static SyntaxNode AdjustBinaryExpressionOperands(BinaryExpressionSyntax logicalAnd, ExpressionSyntax replacement) { // If there's a `&&` on the left, we have picked the right-hand-side for the combination. // In which case, we should replace that instead of the whole `&&` operator in a chain. // For instance, `expr && a.b == 1 && a.c == 2` is converted to `expr && a is { b: 1, c: 2 }` if (logicalAnd.Left is BinaryExpressionSyntax(LogicalAndExpression) leftExpression) replacement = leftExpression.WithRight(replacement); return replacement.ConvertToSingleLine().WithAdditionalAnnotations(Formatter.Annotation); } } private static Func<SyntaxNode, SyntaxNode>? CombineWhenClauseCondition(PatternSyntax switchPattern, ExpressionSyntax condition, SemanticModel model) { if (TryDetermineReceiver(condition, model, inWhenClause: true) is not var (receiver, target, flipped) || TryFindVariableDesignation(switchPattern, receiver, model) is not var (containingPattern, namesOpt)) { return null; } return root => { var editor = new SyntaxEditor(root, CSharpSyntaxGenerator.Instance); switch (receiver.GetRequiredParent().Parent) { // This is the leftmost `&&` operand in a when-clause. Remove the left-hand-side which we've just morphed in the switch pattern. // For instance, `case { p: var v } when v.q == 1 && expr:` would be converted to `case { p: { q: 1 } } v when expr:` case BinaryExpressionSyntax(LogicalAndExpression) logicalAnd: editor.ReplaceNode(logicalAnd, logicalAnd.Right); break; // If we reach here, there's no other expression left in the when-clause. Remove. // For instance, `case { p: var v } when v.q == 1:` would be converted to `case { p: { q: 1 } v }:` case WhenClauseSyntax whenClause: editor.RemoveNode(whenClause, SyntaxRemoveOptions.AddElasticMarker); break; case var v: throw ExceptionUtilities.UnexpectedValue(v); } var generatedPattern = CreatePattern(receiver, target, flipped); var rewrittenPattern = RewriteContainingPattern(containingPattern, generatedPattern, namesOpt); editor.ReplaceNode(containingPattern, rewrittenPattern); return editor.GetChangedRoot(); }; } private static PatternSyntax RewriteContainingPattern( PatternSyntax containingPattern, PatternSyntax generatedPattern, ImmutableArray<IdentifierNameSyntax> namesOpt) { // This is a variable designation match. We'll try to combine the generated // pattern from the right-hand-side into the containing pattern of this designation. var rewrittenPattern = namesOpt.IsDefault // If there's no name, we will combine the pattern itself. ? Combine(containingPattern, generatedPattern) // Otherwise, we generate a subpattern per each name and rewrite as a recursive pattern. : AddSubpattern(containingPattern, CreateSubpattern(namesOpt, generatedPattern)); return rewrittenPattern.ConvertToSingleLine().WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation); static PatternSyntax Combine(PatternSyntax containingPattern, PatternSyntax generatedPattern) { // We know we have a var-pattern, declaration-pattern or a recursive-pattern on the left as the containing node of the variable designation. // Depending on the generated pattern off of the expression on the right, we can give a better result by morphing it into the existing match. return (containingPattern, generatedPattern) switch { // e.g. `e is var x && x is { p: 1 }` => `e is { p: 1 } x` (VarPatternSyntax var, RecursivePatternSyntax { Designation: null } recursive) => recursive.WithDesignation(var.Designation), // e.g. `e is C x && x is { p: 1 }` => `is C { p: 1 } x` (DeclarationPatternSyntax decl, RecursivePatternSyntax { Type: null, Designation: null } recursive) => recursive.WithType(decl.Type).WithDesignation(decl.Designation), // e.g. `e is { p: 1 } x && x is C` => `is C { p: 1 } x` (RecursivePatternSyntax { Type: null } recursive, TypePatternSyntax type) => recursive.WithType(type.Type), // e.g. `e is { p: 1 } x && x is { q: 2 }` => `e is { p: 1, q: 2 } x` (RecursivePatternSyntax recursive, RecursivePatternSyntax { Type: null, Designation: null } other) when recursive.PositionalPatternClause is null || other.PositionalPatternClause is null => recursive .WithPositionalPatternClause(recursive.PositionalPatternClause ?? other.PositionalPatternClause) .WithPropertyPatternClause(Concat(recursive.PropertyPatternClause, other.PropertyPatternClause)), // In any other case, we fallback to an `and` pattern. // UNDONE: This may result in a few unused variables which should be removed in a later pass. _ => BinaryPattern(AndPattern, containingPattern.Parenthesize(), generatedPattern.Parenthesize()), }; } static PatternSyntax AddSubpattern(PatternSyntax containingPattern, SubpatternSyntax subpattern) { return containingPattern switch { // e.g. `case var x when x.p is 1` => `case { p: 1 } x` VarPatternSyntax p => RecursivePattern(type: null, subpattern, p.Designation), // e.g. `case Type x when x.p is 1` => `case Type { p: 1 } x` DeclarationPatternSyntax p => RecursivePattern(p.Type, subpattern, p.Designation), // e.g. `case { p: 1 } x when x.q is 2` => `case { p: 1, q: 2 } x` RecursivePatternSyntax p => p.AddPropertyPatternClauseSubpatterns(subpattern), // We've already checked that the designation is contained in any of the above pattern forms. var p => throw ExceptionUtilities.UnexpectedValue(p) }; } static PropertyPatternClauseSyntax? Concat(PropertyPatternClauseSyntax? left, PropertyPatternClauseSyntax? right) { if (left is null || right is null) return left ?? right; var leftSubpatterns = left.Subpatterns.GetWithSeparators(); if (leftSubpatterns.Any() && !leftSubpatterns.Last().IsToken) leftSubpatterns = leftSubpatterns.Add(Token(CommaToken)); var rightSubpatterns = right.Subpatterns.GetWithSeparators(); var list = new SyntaxNodeOrTokenList(leftSubpatterns.Concat(rightSubpatterns)); return left.WithSubpatterns(SeparatedList<SubpatternSyntax>(list)); } } private static PatternSyntax CreatePattern(ExpressionSyntax originalReceiver, ExpressionOrPatternSyntax target, bool flipped) { return target switch { // A pattern come from an `is` expression on either side of `&&` PatternSyntax pattern => pattern, TypeSyntax type when originalReceiver.IsParentKind(IsExpression) => TypePattern(type), // Otherwise, this is a constant. Depending on the original receiver, we create an appropriate pattern. ExpressionSyntax constant => originalReceiver.Parent switch { BinaryExpressionSyntax(EqualsExpression) => ConstantPattern(constant), BinaryExpressionSyntax(NotEqualsExpression) => UnaryPattern(ConstantPattern(constant)), BinaryExpressionSyntax(GreaterThanExpression or GreaterThanOrEqualExpression or LessThanOrEqualExpression or LessThanExpression) e => RelationalPattern(flipped ? Flip(e.OperatorToken) : e.OperatorToken, constant), var v => throw ExceptionUtilities.UnexpectedValue(v), }, var v => throw ExceptionUtilities.UnexpectedValue(v), }; static SyntaxToken Flip(SyntaxToken token) { return Token(token.Kind() switch { LessThanToken => GreaterThanToken, LessThanEqualsToken => GreaterThanEqualsToken, GreaterThanEqualsToken => LessThanEqualsToken, GreaterThanToken => LessThanToken, var v => throw ExceptionUtilities.UnexpectedValue(v) }); } } private static (PatternSyntax ContainingPattern, ImmutableArray<IdentifierNameSyntax> NamesOpt)? TryFindVariableDesignation( PatternSyntax leftPattern, ExpressionSyntax rightReceiver, SemanticModel model) { using var _ = ArrayBuilder<IdentifierNameSyntax>.GetInstance(out var names); if (GetInnermostReceiver(rightReceiver, names, model) is not IdentifierNameSyntax identifierName) return null; var designation = leftPattern.DescendantNodes() .OfType<SingleVariableDesignationSyntax>() .Where(d => d.Identifier.ValueText == identifierName.Identifier.ValueText) .FirstOrDefault(); if (designation is not { Parent: PatternSyntax containingPattern }) return null; // Only the following patterns can directly contain a variable designation. // Note: While a parenthesized designation can also contain other variables, // it is not a pattern, so it would not get past the PatternSyntax test above. Debug.Assert(containingPattern.IsKind(SyntaxKind.VarPattern, SyntaxKind.DeclarationPattern, SyntaxKind.RecursivePattern)); return (containingPattern, names.ToImmutableOrNull()); } private static (ExpressionSyntax Receiver, ExpressionOrPatternSyntax Target, bool Flipped)? TryDetermineReceiver( ExpressionSyntax node, SemanticModel model, bool inWhenClause = false) { return node switch { // For comparison operators, after we have determined the // constant operand, we rewrite it as a constant or relational pattern. BinaryExpressionSyntax(EqualsExpression or NotEqualsExpression or GreaterThanExpression or GreaterThanOrEqualExpression or LessThanOrEqualExpression or LessThanExpression) expr => TryDetermineConstant(expr, model), // If we found a `&&` here, there's two possibilities: // // 1) If we're in a when-clause, we look for the leftmost expression // which we will try to combine with the switch arm/label pattern. // For instance, we return `a` if we have `case <pat> when a && b && c`. // // 2) Otherwise, we will return the operand that *appears* to be on the left in the source. // For instance, we return `a` if we have `x && a && b` with the cursor on the second operator. // Since `&&` is left-associative, it's guaranteed to be the expression that we want. // For simplicity, we won't descend into any parenthesized expression here. // BinaryExpressionSyntax(LogicalAndExpression) expr => TryDetermineReceiver(inWhenClause ? expr.Left : expr.Right, model, inWhenClause), // If we have an `is` operator, we'll try to combine the existing pattern/type with the other operand. BinaryExpressionSyntax(IsExpression) { Right: NullableTypeSyntax type } expr => (expr.Left, type.ElementType, Flipped: false), BinaryExpressionSyntax(IsExpression) { Right: TypeSyntax type } expr => (expr.Left, type, Flipped: false), IsPatternExpressionSyntax expr => (expr.Expression, expr.Pattern, Flipped: false), // We treat any other expression as if they were compared to true/false. // For instance, `a.b && !a.c` will be converted to `a is { b: true, c: false }` PrefixUnaryExpressionSyntax(LogicalNotExpression) expr => (expr.Operand, s_falseConstantPattern, Flipped: false), var expr => (expr, s_trueConstantPattern, Flipped: false), }; static (ExpressionSyntax Expression, ExpressionSyntax Constant, bool Flipped)? TryDetermineConstant(BinaryExpressionSyntax node, SemanticModel model) { return (node.Left, node.Right) switch { var (left, right) when model.GetConstantValue(left).HasValue => (right, left, Flipped: true), var (left, right) when model.GetConstantValue(right).HasValue => (left, right, Flipped: false), _ => null }; } } private static SubpatternSyntax CreateSubpattern(ImmutableArray<IdentifierNameSyntax> names, PatternSyntax pattern) { Debug.Assert(!names.IsDefaultOrEmpty); var subpattern = Subpattern(names[0], pattern); for (var i = 1; i < names.Length; i++) subpattern = Subpattern(names[i], RecursivePattern(subpattern)); return subpattern; } private static SubpatternSyntax Subpattern(IdentifierNameSyntax name, PatternSyntax pattern) => SyntaxFactory.Subpattern(NameColon(name), pattern); private static RecursivePatternSyntax RecursivePattern(params SubpatternSyntax[] subpatterns) => SyntaxFactory.RecursivePattern(type: null, positionalPatternClause: null, PropertyPatternClause(SeparatedList(subpatterns)), designation: null); private static RecursivePatternSyntax RecursivePattern(TypeSyntax? type, SubpatternSyntax subpattern, VariableDesignationSyntax? designation) => SyntaxFactory.RecursivePattern(type, positionalPatternClause: null, PropertyPatternClause(SingletonSeparatedList(subpattern)), designation); private static RecursivePatternSyntax RecursivePattern(SubpatternSyntax subpattern) => RecursivePattern(type: null, subpattern, designation: null); /// <summary> /// Obtain the outermost common receiver between two expressions. This can succeed with a null 'CommonReceiver' /// in the case that the common receiver is the 'implicit this'. /// </summary> private static (ExpressionSyntax CommonReceiver, ImmutableArray<IdentifierNameSyntax> LeftNames, ImmutableArray<IdentifierNameSyntax> RightNames)? TryGetCommonReceiver( ExpressionSyntax left, ExpressionSyntax right, SemanticModel model) { using var _1 = ArrayBuilder<IdentifierNameSyntax>.GetInstance(out var leftNames); using var _2 = ArrayBuilder<IdentifierNameSyntax>.GetInstance(out var rightNames); if (!TryGetInnermostReceiver(left, leftNames, out var leftReceiver, model) || !TryGetInnermostReceiver(right, rightNames, out var rightReceiver, model) || !AreEquivalent(leftReceiver, rightReceiver)) // We must have a common starting point to proceed. { return null; } var commonReceiver = leftReceiver; // To reduce noise on superfluous subpatterns and avoid duplicates, skip any common name in the path. var lastName = SkipCommonNames(leftNames, rightNames); if (lastName is not null) { // If there were some common names in the path, we rewrite the receiver to include those. // For instance, in `a.b.c && a.b.d`, we have `b` as the last common name in the path, // So we want `a.b` as the receiver so that we convert it to `a.b is { c: true, d: true }`. commonReceiver = GetInnermostReceiver(left, lastName, static (identifierName, lastName) => identifierName != lastName); } return (commonReceiver ?? ThisExpression(), leftNames.ToImmutable(), rightNames.ToImmutable()); static bool TryGetInnermostReceiver(ExpressionSyntax node, ArrayBuilder<IdentifierNameSyntax> builder, [NotNullWhen(true)] out ExpressionSyntax? receiver, SemanticModel model) { receiver = GetInnermostReceiver(node, builder, model); return builder.Any(); } static IdentifierNameSyntax? SkipCommonNames(ArrayBuilder<IdentifierNameSyntax> leftNames, ArrayBuilder<IdentifierNameSyntax> rightNames) { IdentifierNameSyntax? lastName = null; int leftIndex, rightIndex; // Note: we don't want to skip the first name to still be able to convert to a subpattern, hence checking `> 0` below. for (leftIndex = leftNames.Count - 1, rightIndex = rightNames.Count - 1; leftIndex > 0 && rightIndex > 0; leftIndex--, rightIndex--) { var leftName = leftNames[leftIndex]; var rightName = rightNames[rightIndex]; if (!AreEquivalent(leftName, rightName)) break; lastName = leftName; } leftNames.Clip(leftIndex + 1); rightNames.Clip(rightIndex + 1); return lastName; } } private static ExpressionSyntax? GetInnermostReceiver(ExpressionSyntax node, ArrayBuilder<IdentifierNameSyntax> builder, SemanticModel model) => GetInnermostReceiver(node, model, s_canConvertToSubpattern, builder); private static ExpressionSyntax? GetInnermostReceiver<TArg>( ExpressionSyntax node, TArg arg, Func<IdentifierNameSyntax, TArg, bool> canConvertToSubpattern, ArrayBuilder<IdentifierNameSyntax>? builder = null) { return GetInnermostReceiver(node); ExpressionSyntax? GetInnermostReceiver(ExpressionSyntax node) { switch (node) { case IdentifierNameSyntax name when canConvertToSubpattern(name, arg): builder?.Add(name); // This is a member reference with an implicit `this` receiver. // We know this is true because we already checked canConvertToSubpattern. // Any other name outside the receiver position is captured in the cases below. return null; case MemberBindingExpressionSyntax { Name: IdentifierNameSyntax name } when canConvertToSubpattern(name, arg): builder?.Add(name); // We only reach here from a parent conditional-access. // Returning null here means that all the names on the right were convertible to a property pattern. return null; case MemberAccessExpressionSyntax(SimpleMemberAccessExpression) { Name: IdentifierNameSyntax name } memberAccess when canConvertToSubpattern(name, arg) && !memberAccess.Expression.IsKind(SyntaxKind.BaseExpression): builder?.Add(name); // For a simple member access we simply record the name and descend into the expression on the left-hand-side. return GetInnermostReceiver(memberAccess.Expression); case ConditionalAccessExpressionSyntax conditionalAccess: // For a conditional access, first we need to verify the right-hand-side is convertible to a property pattern. var right = GetInnermostReceiver(conditionalAccess.WhenNotNull); if (right is not null) { // If it has it's own receiver other than a member-binding expression, we return this node as the receiver. // For instance, if we had `a?.M().b`, the name `b` is already captured, so we need to return `a?.M()` as the innermost receiver. // If there was no name, this call returns itself, e.g. in `a?.M()` the receiver is the entire existing conditional access. return conditionalAccess.WithWhenNotNull(right); } // Otherwise, descend into the the expression on the left-hand-side. return GetInnermostReceiver(conditionalAccess.Expression); default: return node; } } } private sealed class MyCodeAction : CodeActions.CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Features/CSharp/Portable/Completion/CompletionProviders/FunctionPointerUnmanagedCallingConventionCompletionProvider.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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(FunctionPointerUnmanagedCallingConventionCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(EmbeddedLanguageCompletionProvider))] [Shared] internal partial class FunctionPointerUnmanagedCallingConventionCompletionProvider : LSPCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FunctionPointerUnmanagedCallingConventionCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters; private static readonly ImmutableArray<string> s_predefinedCallingConventions = ImmutableArray.Create("Cdecl", "Fastcall", "Thiscall", "Stdcall"); public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.IsInNonUserCode(position, cancellationToken)) { return; } var token = syntaxTree .FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (!token.IsKind(SyntaxKind.OpenBracketToken, SyntaxKind.CommaToken)) { return; } if (token.Parent is not FunctionPointerUnmanagedCallingConventionListSyntax callingConventionList) { return; } var contextPosition = token.SpanStart; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(callingConventionList, cancellationToken).ConfigureAwait(false); var completionItems = new HashSet<CompletionItem>(CompletionItemComparer.Instance); AddTypes(completionItems, contextPosition, semanticModel, cancellationToken); // Even if we didn't have types, there are four magic calling conventions recognized regardless. // We add these after doing the type lookup so if we had types we can show that instead foreach (var callingConvention in s_predefinedCallingConventions) { completionItems.Add(CompletionItem.Create(callingConvention, tags: GlyphTags.GetTags(Glyph.Keyword))); } context.AddItems(completionItems); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private static void AddTypes(HashSet<CompletionItem> completionItems, int contextPosition, SemanticModel semanticModel, CancellationToken cancellationToken) { // We have to find the set of types that meet the criteria listed in // https://github.com/dotnet/csharplang/blob/main/proposals/csharp-9.0/function-pointers.md#mapping-the-calling_convention_specifier-to-a-callkind // We skip the check of an type being in the core assembly since that's not really necessary for our work. var compilerServicesNamespace = semanticModel.Compilation.GlobalNamespace.GetQualifiedNamespace("System.Runtime.CompilerServices"); if (compilerServicesNamespace == null) { return; } foreach (var type in compilerServicesNamespace.GetTypeMembers()) { cancellationToken.ThrowIfCancellationRequested(); const string CallConvPrefix = "CallConv"; if (type.DeclaredAccessibility == Accessibility.Public && type.Name.StartsWith(CallConvPrefix)) { var displayName = type.Name[CallConvPrefix.Length..]; completionItems.Add( SymbolCompletionItem.CreateWithSymbolId( displayName, ImmutableArray.Create(type), rules: CompletionItemRules.Default, contextPosition)); } } } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); private class CompletionItemComparer : IEqualityComparer<CompletionItem> { public static readonly IEqualityComparer<CompletionItem> Instance = new CompletionItemComparer(); public bool Equals(CompletionItem? x, CompletionItem? y) { return x?.DisplayText == y?.DisplayText; } public int GetHashCode(CompletionItem obj) { return obj?.DisplayText.GetHashCode() ?? 0; } } } }
// 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(FunctionPointerUnmanagedCallingConventionCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(EmbeddedLanguageCompletionProvider))] [Shared] internal partial class FunctionPointerUnmanagedCallingConventionCompletionProvider : LSPCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FunctionPointerUnmanagedCallingConventionCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters; private static readonly ImmutableArray<string> s_predefinedCallingConventions = ImmutableArray.Create("Cdecl", "Fastcall", "Thiscall", "Stdcall"); public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.IsInNonUserCode(position, cancellationToken)) { return; } var token = syntaxTree .FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (!token.IsKind(SyntaxKind.OpenBracketToken, SyntaxKind.CommaToken)) { return; } if (token.Parent is not FunctionPointerUnmanagedCallingConventionListSyntax callingConventionList) { return; } var contextPosition = token.SpanStart; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(callingConventionList, cancellationToken).ConfigureAwait(false); var completionItems = new HashSet<CompletionItem>(CompletionItemComparer.Instance); AddTypes(completionItems, contextPosition, semanticModel, cancellationToken); // Even if we didn't have types, there are four magic calling conventions recognized regardless. // We add these after doing the type lookup so if we had types we can show that instead foreach (var callingConvention in s_predefinedCallingConventions) { completionItems.Add(CompletionItem.Create(callingConvention, tags: GlyphTags.GetTags(Glyph.Keyword))); } context.AddItems(completionItems); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private static void AddTypes(HashSet<CompletionItem> completionItems, int contextPosition, SemanticModel semanticModel, CancellationToken cancellationToken) { // We have to find the set of types that meet the criteria listed in // https://github.com/dotnet/csharplang/blob/main/proposals/csharp-9.0/function-pointers.md#mapping-the-calling_convention_specifier-to-a-callkind // We skip the check of an type being in the core assembly since that's not really necessary for our work. var compilerServicesNamespace = semanticModel.Compilation.GlobalNamespace.GetQualifiedNamespace("System.Runtime.CompilerServices"); if (compilerServicesNamespace == null) { return; } foreach (var type in compilerServicesNamespace.GetTypeMembers()) { cancellationToken.ThrowIfCancellationRequested(); const string CallConvPrefix = "CallConv"; if (type.DeclaredAccessibility == Accessibility.Public && type.Name.StartsWith(CallConvPrefix)) { var displayName = type.Name[CallConvPrefix.Length..]; completionItems.Add( SymbolCompletionItem.CreateWithSymbolId( displayName, ImmutableArray.Create(type), rules: CompletionItemRules.Default, contextPosition)); } } } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); private class CompletionItemComparer : IEqualityComparer<CompletionItem> { public static readonly IEqualityComparer<CompletionItem> Instance = new CompletionItemComparer(); public bool Equals(CompletionItem? x, CompletionItem? y) { return x?.DisplayText == y?.DisplayText; } public int GetHashCode(CompletionItem obj) { return obj?.DisplayText.GetHashCode() ?? 0; } } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/AnalyzedArguments.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { // Note: instances of this object are pooled internal sealed class AnalyzedArguments { public readonly ArrayBuilder<BoundExpression> Arguments; public readonly ArrayBuilder<(string Name, Location Location)?> Names; public readonly ArrayBuilder<RefKind> RefKinds; public bool IsExtensionMethodInvocation; private ThreeState _lazyHasDynamicArgument; internal AnalyzedArguments() { this.Arguments = new ArrayBuilder<BoundExpression>(32); this.Names = new ArrayBuilder<(string, Location)?>(32); this.RefKinds = new ArrayBuilder<RefKind>(32); } public void Clear() { this.Arguments.Clear(); this.Names.Clear(); this.RefKinds.Clear(); this.IsExtensionMethodInvocation = false; _lazyHasDynamicArgument = ThreeState.Unknown; } public BoundExpression Argument(int i) { return Arguments[i]; } public void AddName(IdentifierNameSyntax name) { Names.Add((name.Identifier.ValueText, name.Location)); } public string? Name(int i) { if (Names.Count == 0) { return null; } var nameAndLocation = Names[i]; return nameAndLocation?.Name; } public ImmutableArray<string?> GetNames() { int count = this.Names.Count; if (count == 0) { return default; } var builder = ArrayBuilder<string?>.GetInstance(this.Names.Count); for (int i = 0; i < this.Names.Count; ++i) { builder.Add(Name(i)); } return builder.ToImmutableAndFree(); } public RefKind RefKind(int i) { return RefKinds.Count > 0 ? RefKinds[i] : Microsoft.CodeAnalysis.RefKind.None; } public bool IsExtensionMethodThisArgument(int i) { return (i == 0) && this.IsExtensionMethodInvocation; } public bool HasDynamicArgument { get { if (_lazyHasDynamicArgument.HasValue()) { return _lazyHasDynamicArgument.Value(); } bool hasRefKinds = RefKinds.Count > 0; for (int i = 0; i < Arguments.Count; i++) { var argument = Arguments[i]; // By-ref dynamic arguments don't make the invocation dynamic. if ((object?)argument.Type != null && argument.Type.IsDynamic() && (!hasRefKinds || RefKinds[i] == Microsoft.CodeAnalysis.RefKind.None)) { _lazyHasDynamicArgument = ThreeState.True; return true; } } _lazyHasDynamicArgument = ThreeState.False; return false; } } public bool HasErrors { get { foreach (var argument in this.Arguments) { if (argument.HasAnyErrors) { return true; } } return false; } } #region "Poolable" public static AnalyzedArguments GetInstance() { return Pool.Allocate(); } public static AnalyzedArguments GetInstance(AnalyzedArguments original) { var instance = GetInstance(); instance.Arguments.AddRange(original.Arguments); instance.Names.AddRange(original.Names); instance.RefKinds.AddRange(original.RefKinds); instance.IsExtensionMethodInvocation = original.IsExtensionMethodInvocation; instance._lazyHasDynamicArgument = original._lazyHasDynamicArgument; return instance; } public static AnalyzedArguments GetInstance( ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<(string, Location)?> argumentNamesOpt) { var instance = GetInstance(); instance.Arguments.AddRange(arguments); if (!argumentRefKindsOpt.IsDefault) { instance.RefKinds.AddRange(argumentRefKindsOpt); } if (!argumentNamesOpt.IsDefault) { instance.Names.AddRange(argumentNamesOpt); } return instance; } public void Free() { this.Clear(); Pool.Free(this); } //2) Expose the pool or the way to create a pool or the way to get an instance. // for now we will expose both and figure which way works better public static readonly ObjectPool<AnalyzedArguments> Pool = CreatePool(); private static ObjectPool<AnalyzedArguments> CreatePool() { ObjectPool<AnalyzedArguments>? pool = null; pool = new ObjectPool<AnalyzedArguments>(() => new AnalyzedArguments(), 10); return pool; } #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. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { // Note: instances of this object are pooled internal sealed class AnalyzedArguments { public readonly ArrayBuilder<BoundExpression> Arguments; public readonly ArrayBuilder<(string Name, Location Location)?> Names; public readonly ArrayBuilder<RefKind> RefKinds; public bool IsExtensionMethodInvocation; private ThreeState _lazyHasDynamicArgument; internal AnalyzedArguments() { this.Arguments = new ArrayBuilder<BoundExpression>(32); this.Names = new ArrayBuilder<(string, Location)?>(32); this.RefKinds = new ArrayBuilder<RefKind>(32); } public void Clear() { this.Arguments.Clear(); this.Names.Clear(); this.RefKinds.Clear(); this.IsExtensionMethodInvocation = false; _lazyHasDynamicArgument = ThreeState.Unknown; } public BoundExpression Argument(int i) { return Arguments[i]; } public void AddName(IdentifierNameSyntax name) { Names.Add((name.Identifier.ValueText, name.Location)); } public string? Name(int i) { if (Names.Count == 0) { return null; } var nameAndLocation = Names[i]; return nameAndLocation?.Name; } public ImmutableArray<string?> GetNames() { int count = this.Names.Count; if (count == 0) { return default; } var builder = ArrayBuilder<string?>.GetInstance(this.Names.Count); for (int i = 0; i < this.Names.Count; ++i) { builder.Add(Name(i)); } return builder.ToImmutableAndFree(); } public RefKind RefKind(int i) { return RefKinds.Count > 0 ? RefKinds[i] : Microsoft.CodeAnalysis.RefKind.None; } public bool IsExtensionMethodThisArgument(int i) { return (i == 0) && this.IsExtensionMethodInvocation; } public bool HasDynamicArgument { get { if (_lazyHasDynamicArgument.HasValue()) { return _lazyHasDynamicArgument.Value(); } bool hasRefKinds = RefKinds.Count > 0; for (int i = 0; i < Arguments.Count; i++) { var argument = Arguments[i]; // By-ref dynamic arguments don't make the invocation dynamic. if ((object?)argument.Type != null && argument.Type.IsDynamic() && (!hasRefKinds || RefKinds[i] == Microsoft.CodeAnalysis.RefKind.None)) { _lazyHasDynamicArgument = ThreeState.True; return true; } } _lazyHasDynamicArgument = ThreeState.False; return false; } } public bool HasErrors { get { foreach (var argument in this.Arguments) { if (argument.HasAnyErrors) { return true; } } return false; } } #region "Poolable" public static AnalyzedArguments GetInstance() { return Pool.Allocate(); } public static AnalyzedArguments GetInstance(AnalyzedArguments original) { var instance = GetInstance(); instance.Arguments.AddRange(original.Arguments); instance.Names.AddRange(original.Names); instance.RefKinds.AddRange(original.RefKinds); instance.IsExtensionMethodInvocation = original.IsExtensionMethodInvocation; instance._lazyHasDynamicArgument = original._lazyHasDynamicArgument; return instance; } public static AnalyzedArguments GetInstance( ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<(string, Location)?> argumentNamesOpt) { var instance = GetInstance(); instance.Arguments.AddRange(arguments); if (!argumentRefKindsOpt.IsDefault) { instance.RefKinds.AddRange(argumentRefKindsOpt); } if (!argumentNamesOpt.IsDefault) { instance.Names.AddRange(argumentNamesOpt); } return instance; } public void Free() { this.Clear(); Pool.Free(this); } //2) Expose the pool or the way to create a pool or the way to get an instance. // for now we will expose both and figure which way works better public static readonly ObjectPool<AnalyzedArguments> Pool = CreatePool(); private static ObjectPool<AnalyzedArguments> CreatePool() { ObjectPool<AnalyzedArguments>? pool = null; pool = new ObjectPool<AnalyzedArguments>(() => new AnalyzedArguments(), 10); return pool; } #endregion } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_DelegateCreation.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 Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode ' if there is a stub needed because of a delegate relaxation, the DelegateCreationNode has ' it stored in RelaxationLambdaOpt. ' The lambda rewriter will then take care of the code generation later on. If node.RelaxationLambdaOpt Is Nothing Then Debug.Assert(node.RelaxationReceiverPlaceholderOpt Is Nothing OrElse Me._inExpressionLambda) Return MyBase.VisitDelegateCreationExpression(node) Else Dim placeholderOpt As BoundRValuePlaceholder = node.RelaxationReceiverPlaceholderOpt Dim captureTemp As SynthesizedLocal = Nothing If placeholderOpt IsNot Nothing Then If Me._inExpressionLambda Then Me.AddPlaceholderReplacement(placeholderOpt, VisitExpression(node.ReceiverOpt)) Else captureTemp = New SynthesizedLocal(Me._currentMethodOrLambda, placeholderOpt.Type, SynthesizedLocalKind.DelegateRelaxationReceiver, syntaxOpt:=placeholderOpt.Syntax) Dim actualReceiver = New BoundLocal(placeholderOpt.Syntax, captureTemp, captureTemp.Type).MakeRValue Me.AddPlaceholderReplacement(placeholderOpt, actualReceiver) End If End If Dim relaxationLambda = DirectCast(Me.Visit(node.RelaxationLambdaOpt), BoundLambda) If placeholderOpt IsNot Nothing Then Me.RemovePlaceholderReplacement(placeholderOpt) End If Dim result As BoundExpression = New BoundConversion( relaxationLambda.Syntax, relaxationLambda, ConversionKind.Lambda Or ConversionKind.Widening, checked:=False, explicitCastInCode:=False, Type:=node.Type, hasErrors:=node.HasErrors) If captureTemp IsNot Nothing Then Dim receiverToCapture As BoundExpression = VisitExpressionNode(node.ReceiverOpt) Dim capture = New BoundAssignmentOperator(receiverToCapture.Syntax, New BoundLocal(receiverToCapture.Syntax, captureTemp, captureTemp.Type), receiverToCapture.MakeRValue(), suppressObjectClone:=True, Type:=captureTemp.Type) result = New BoundSequence( result.Syntax, ImmutableArray.Create(Of LocalSymbol)(captureTemp), ImmutableArray.Create(Of BoundExpression)(capture), result, result.Type) End If Return result End If 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.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode ' if there is a stub needed because of a delegate relaxation, the DelegateCreationNode has ' it stored in RelaxationLambdaOpt. ' The lambda rewriter will then take care of the code generation later on. If node.RelaxationLambdaOpt Is Nothing Then Debug.Assert(node.RelaxationReceiverPlaceholderOpt Is Nothing OrElse Me._inExpressionLambda) Return MyBase.VisitDelegateCreationExpression(node) Else Dim placeholderOpt As BoundRValuePlaceholder = node.RelaxationReceiverPlaceholderOpt Dim captureTemp As SynthesizedLocal = Nothing If placeholderOpt IsNot Nothing Then If Me._inExpressionLambda Then Me.AddPlaceholderReplacement(placeholderOpt, VisitExpression(node.ReceiverOpt)) Else captureTemp = New SynthesizedLocal(Me._currentMethodOrLambda, placeholderOpt.Type, SynthesizedLocalKind.DelegateRelaxationReceiver, syntaxOpt:=placeholderOpt.Syntax) Dim actualReceiver = New BoundLocal(placeholderOpt.Syntax, captureTemp, captureTemp.Type).MakeRValue Me.AddPlaceholderReplacement(placeholderOpt, actualReceiver) End If End If Dim relaxationLambda = DirectCast(Me.Visit(node.RelaxationLambdaOpt), BoundLambda) If placeholderOpt IsNot Nothing Then Me.RemovePlaceholderReplacement(placeholderOpt) End If Dim result As BoundExpression = New BoundConversion( relaxationLambda.Syntax, relaxationLambda, ConversionKind.Lambda Or ConversionKind.Widening, checked:=False, explicitCastInCode:=False, Type:=node.Type, hasErrors:=node.HasErrors) If captureTemp IsNot Nothing Then Dim receiverToCapture As BoundExpression = VisitExpressionNode(node.ReceiverOpt) Dim capture = New BoundAssignmentOperator(receiverToCapture.Syntax, New BoundLocal(receiverToCapture.Syntax, captureTemp, captureTemp.Type), receiverToCapture.MakeRValue(), suppressObjectClone:=True, Type:=captureTemp.Type) result = New BoundSequence( result.Syntax, ImmutableArray.Create(Of LocalSymbol)(captureTemp), ImmutableArray.Create(Of BoundExpression)(capture), result, result.Type) End If Return result End If End Function End Class End Namespace
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Compilers/VisualBasic/Portable/Binding/BlockStatementBinders.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 Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ' The binder for a statement that can be exited with Exit and/or Continue. Friend Class ExitableStatementBinder Inherits BlockBaseBinder Private ReadOnly _continueLabel As LabelSymbol ' the label to jump to for a continue (or Nothing for none) Private ReadOnly _continueKind As SyntaxKind ' the kind of continue to go there Private ReadOnly _exitLabel As LabelSymbol ' the label to jump to for an exit (or Nothing for none) Private ReadOnly _exitKind As SyntaxKind ' the kind of exit to go there Public Sub New(enclosing As Binder, continueKind As SyntaxKind, exitKind As SyntaxKind) MyBase.New(enclosing) Me._continueKind = continueKind If continueKind <> SyntaxKind.None Then Me._continueLabel = New GeneratedLabelSymbol("continue") End If Me._exitKind = exitKind If exitKind <> SyntaxKind.None Then Me._exitLabel = New GeneratedLabelSymbol("exit") End If End Sub Friend Overrides ReadOnly Property Locals As ImmutableArray(Of LocalSymbol) Get Return ImmutableArray(Of LocalSymbol).Empty End Get End Property Public Overrides Function GetContinueLabel(continueSyntaxKind As SyntaxKind) As LabelSymbol If _continueKind = continueSyntaxKind Then Return _continueLabel Else Return ContainingBinder.GetContinueLabel(continueSyntaxKind) End If End Function Public Overrides Function GetExitLabel(exitSyntaxKind As SyntaxKind) As LabelSymbol If _exitKind = exitSyntaxKind Then Return _exitLabel Else Return ContainingBinder.GetExitLabel(exitSyntaxKind) End If End Function Public Overrides Function GetReturnLabel() As LabelSymbol Select Case _exitKind Case SyntaxKind.ExitSubStatement, SyntaxKind.ExitPropertyStatement, SyntaxKind.ExitFunctionStatement, SyntaxKind.EventStatement, SyntaxKind.OperatorStatement ' the last two are not real exit statements, they are used specifically in ' block events and operators to indicate that there is a return label, but ' no ExitXXX statement should be able to bind to it. Return _exitLabel Case Else Return ContainingBinder.GetReturnLabel() End Select 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.Collections.Immutable Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ' The binder for a statement that can be exited with Exit and/or Continue. Friend Class ExitableStatementBinder Inherits BlockBaseBinder Private ReadOnly _continueLabel As LabelSymbol ' the label to jump to for a continue (or Nothing for none) Private ReadOnly _continueKind As SyntaxKind ' the kind of continue to go there Private ReadOnly _exitLabel As LabelSymbol ' the label to jump to for an exit (or Nothing for none) Private ReadOnly _exitKind As SyntaxKind ' the kind of exit to go there Public Sub New(enclosing As Binder, continueKind As SyntaxKind, exitKind As SyntaxKind) MyBase.New(enclosing) Me._continueKind = continueKind If continueKind <> SyntaxKind.None Then Me._continueLabel = New GeneratedLabelSymbol("continue") End If Me._exitKind = exitKind If exitKind <> SyntaxKind.None Then Me._exitLabel = New GeneratedLabelSymbol("exit") End If End Sub Friend Overrides ReadOnly Property Locals As ImmutableArray(Of LocalSymbol) Get Return ImmutableArray(Of LocalSymbol).Empty End Get End Property Public Overrides Function GetContinueLabel(continueSyntaxKind As SyntaxKind) As LabelSymbol If _continueKind = continueSyntaxKind Then Return _continueLabel Else Return ContainingBinder.GetContinueLabel(continueSyntaxKind) End If End Function Public Overrides Function GetExitLabel(exitSyntaxKind As SyntaxKind) As LabelSymbol If _exitKind = exitSyntaxKind Then Return _exitLabel Else Return ContainingBinder.GetExitLabel(exitSyntaxKind) End If End Function Public Overrides Function GetReturnLabel() As LabelSymbol Select Case _exitKind Case SyntaxKind.ExitSubStatement, SyntaxKind.ExitPropertyStatement, SyntaxKind.ExitFunctionStatement, SyntaxKind.EventStatement, SyntaxKind.OperatorStatement ' the last two are not real exit statements, they are used specifically in ' block events and operators to indicate that there is a return label, but ' no ExitXXX statement should be able to bind to it. Return _exitLabel Case Else Return ContainingBinder.GetReturnLabel() End Select End Function End Class End Namespace
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/NoPIATests.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 Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class NoPIATests : ExpressionCompilerTestBase { [WorkItem(1033598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033598")] [Fact] public void ExplicitEmbeddedType() { var source = @"using System.Runtime.InteropServices; [TypeIdentifier] [Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9D8"")] public interface I { object F(); } class C { void M() { var o = (I)null; } static void Main() { (new C()).M(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugExe); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("this", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (I V_0) //o IL_0000: ldarg.0 IL_0001: ret }"); }); } [WorkItem(1035310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1035310")] [Fact] public void EmbeddedType() { var sourcePIA = @"using System.Runtime.InteropServices; [assembly: PrimaryInteropAssembly(0, 0)] [assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DA"")] [ComImport] [Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DA"")] public interface I { object F(); }"; var source = @"class C { static void M() { var o = (I)null; } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source, new[] { referencePIA }, TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("o", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (I V_0) //o IL_0000: ldloc.0 IL_0001: ret }"); }); } /// <summary> /// Duplicate type definitions: in PIA /// and as embedded type. /// </summary> [Fact] public void PIATypeAndEmbeddedType() { var sourcePIA = @"using System.Runtime.InteropServices; [assembly: PrimaryInteropAssembly(0, 0)] [assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DC"")] [ComImport] [Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DC"")] public interface I { object F(); }"; var sourceA = @"public class A { public static void M(I x) { } }"; var sourceB = @"class B { static void Main() { I y = null; A.M(y); } }"; var modulePIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll).ToModuleInstance(); // csc /t:library /l:PIA.dll A.cs var moduleA = CreateCompilation( sourceA, options: TestOptions.DebugDll, references: new[] { modulePIA.GetReference().WithEmbedInteropTypes(true) }).ToModuleInstance(); // csc /r:A.dll /r:PIA.dll B.cs var moduleB = CreateCompilation( sourceB, options: TestOptions.DebugExe, references: new[] { moduleA.GetReference(), modulePIA.GetReference() }).ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { MscorlibRef.ToModuleInstance(), moduleA, modulePIA, moduleB }); var context = CreateMethodContext(runtime, "A.M"); ResultProperties resultProperties; string error; // Bind to local of embedded PIA type. var testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); // Binding to method on original PIA should fail // since it was not included in embedded type. ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( "x.F()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); Assert.Equal("error CS1061: 'I' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'I' could be found (are you missing a using directive or an assembly reference?)", error); // Binding to method on original PIA should succeed // in assembly referencing PIA.dll. context = CreateMethodContext(runtime, "B.Main"); testData = new CompilationTestData(); context.CompileExpression("y.F()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (I V_0) //y IL_0000: ldloc.0 IL_0001: callvirt ""object I.F()"" IL_0006: 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.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class NoPIATests : ExpressionCompilerTestBase { [WorkItem(1033598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033598")] [Fact] public void ExplicitEmbeddedType() { var source = @"using System.Runtime.InteropServices; [TypeIdentifier] [Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9D8"")] public interface I { object F(); } class C { void M() { var o = (I)null; } static void Main() { (new C()).M(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugExe); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("this", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (I V_0) //o IL_0000: ldarg.0 IL_0001: ret }"); }); } [WorkItem(1035310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1035310")] [Fact] public void EmbeddedType() { var sourcePIA = @"using System.Runtime.InteropServices; [assembly: PrimaryInteropAssembly(0, 0)] [assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DA"")] [ComImport] [Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DA"")] public interface I { object F(); }"; var source = @"class C { static void M() { var o = (I)null; } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source, new[] { referencePIA }, TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("o", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (I V_0) //o IL_0000: ldloc.0 IL_0001: ret }"); }); } /// <summary> /// Duplicate type definitions: in PIA /// and as embedded type. /// </summary> [Fact] public void PIATypeAndEmbeddedType() { var sourcePIA = @"using System.Runtime.InteropServices; [assembly: PrimaryInteropAssembly(0, 0)] [assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DC"")] [ComImport] [Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DC"")] public interface I { object F(); }"; var sourceA = @"public class A { public static void M(I x) { } }"; var sourceB = @"class B { static void Main() { I y = null; A.M(y); } }"; var modulePIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll).ToModuleInstance(); // csc /t:library /l:PIA.dll A.cs var moduleA = CreateCompilation( sourceA, options: TestOptions.DebugDll, references: new[] { modulePIA.GetReference().WithEmbedInteropTypes(true) }).ToModuleInstance(); // csc /r:A.dll /r:PIA.dll B.cs var moduleB = CreateCompilation( sourceB, options: TestOptions.DebugExe, references: new[] { moduleA.GetReference(), modulePIA.GetReference() }).ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { MscorlibRef.ToModuleInstance(), moduleA, modulePIA, moduleB }); var context = CreateMethodContext(runtime, "A.M"); ResultProperties resultProperties; string error; // Bind to local of embedded PIA type. var testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); // Binding to method on original PIA should fail // since it was not included in embedded type. ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( "x.F()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); Assert.Equal("error CS1061: 'I' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'I' could be found (are you missing a using directive or an assembly reference?)", error); // Binding to method on original PIA should succeed // in assembly referencing PIA.dll. context = CreateMethodContext(runtime, "B.Main"); testData = new CompilationTestData(); context.CompileExpression("y.F()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (I V_0) //y IL_0000: ldloc.0 IL_0001: callvirt ""object I.F()"" IL_0006: ret }"); } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Workspaces/CoreTestUtilities/TestExportJoinableTaskContext.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.ComponentModel.Composition; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Threading; using Xunit.Sdk; namespace Microsoft.CodeAnalysis.Test.Utilities { // Starting with 15.3 the editor took a dependency on JoinableTaskContext // in Text.Logic and IntelliSense layers as an editor host provided service. [Export] internal partial class TestExportJoinableTaskContext { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestExportJoinableTaskContext() { var synchronizationContext = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(GetEffectiveSynchronizationContext()); (JoinableTaskContext, SynchronizationContext) = CreateJoinableTaskContext(); ResetThreadAffinity(JoinableTaskContext.Factory); } finally { SynchronizationContext.SetSynchronizationContext(synchronizationContext); } } private static (JoinableTaskContext joinableTaskContext, SynchronizationContext synchronizationContext) CreateJoinableTaskContext() { Thread mainThread; SynchronizationContext synchronizationContext; if (SynchronizationContext.Current is DispatcherSynchronizationContext) { // The current thread is the main thread, and provides a suitable synchronization context mainThread = Thread.CurrentThread; synchronizationContext = SynchronizationContext.Current; } else { // The current thread is not known to be the main thread; we have no way to know if the // synchronization context of the current thread will behave in a manner consistent with main thread // synchronization contexts, so we use DenyExecutionSynchronizationContext to track any attempted // use of it. var denyExecutionSynchronizationContext = new DenyExecutionSynchronizationContext(SynchronizationContext.Current); mainThread = denyExecutionSynchronizationContext.MainThread; synchronizationContext = denyExecutionSynchronizationContext; } return (new JoinableTaskContext(mainThread, synchronizationContext), synchronizationContext); } [Export] private JoinableTaskContext JoinableTaskContext { get; } internal SynchronizationContext SynchronizationContext { get; } internal static SynchronizationContext? GetEffectiveSynchronizationContext() { if (SynchronizationContext.Current is AsyncTestSyncContext asyncTestSyncContext) { SynchronizationContext? innerSynchronizationContext = null; asyncTestSyncContext.Send( _ => { innerSynchronizationContext = SynchronizationContext.Current; }, null); return innerSynchronizationContext; } else { return SynchronizationContext.Current; } } /// <summary> /// Reset the thread affinity, in particular the designated foreground thread, to the active /// thread. /// </summary> internal static void ResetThreadAffinity(JoinableTaskFactory joinableTaskFactory) { // HACK: When the platform team took over several of our components they created a copy // of ForegroundThreadAffinitizedObject. This needs to be reset in the same way as our copy // does. Reflection is the only choice at the moment. var thread = joinableTaskFactory.Context.MainThread; var taskScheduler = new JoinableTaskFactoryTaskScheduler(joinableTaskFactory); foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) { var type = assembly.GetType("Microsoft.VisualStudio.Language.Intellisense.Implementation.ForegroundThreadAffinitizedObject", throwOnError: false); if (type != null) { type.GetField("foregroundThread", BindingFlags.Static | BindingFlags.NonPublic)!.SetValue(null, thread); type.GetField("ForegroundTaskScheduler", BindingFlags.Static | BindingFlags.NonPublic)!.SetValue(null, taskScheduler); break; } } } // HACK: Part of ResetThreadAffinity private class JoinableTaskFactoryTaskScheduler : TaskScheduler { private readonly JoinableTaskFactory _joinableTaskFactory; public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory) => _joinableTaskFactory = joinableTaskFactory; public override int MaximumConcurrencyLevel => 1; protected override IEnumerable<Task>? GetScheduledTasks() => null; protected override void QueueTask(Task task) { _joinableTaskFactory.RunAsync(async () => { await _joinableTaskFactory.SwitchToMainThreadAsync(); TryExecuteTask(task); }); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (_joinableTaskFactory.Context.IsOnMainThread) { return TryExecuteTask(task); } return 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. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Threading; using Xunit.Sdk; namespace Microsoft.CodeAnalysis.Test.Utilities { // Starting with 15.3 the editor took a dependency on JoinableTaskContext // in Text.Logic and IntelliSense layers as an editor host provided service. [Export] internal partial class TestExportJoinableTaskContext { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestExportJoinableTaskContext() { var synchronizationContext = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(GetEffectiveSynchronizationContext()); (JoinableTaskContext, SynchronizationContext) = CreateJoinableTaskContext(); ResetThreadAffinity(JoinableTaskContext.Factory); } finally { SynchronizationContext.SetSynchronizationContext(synchronizationContext); } } private static (JoinableTaskContext joinableTaskContext, SynchronizationContext synchronizationContext) CreateJoinableTaskContext() { Thread mainThread; SynchronizationContext synchronizationContext; if (SynchronizationContext.Current is DispatcherSynchronizationContext) { // The current thread is the main thread, and provides a suitable synchronization context mainThread = Thread.CurrentThread; synchronizationContext = SynchronizationContext.Current; } else { // The current thread is not known to be the main thread; we have no way to know if the // synchronization context of the current thread will behave in a manner consistent with main thread // synchronization contexts, so we use DenyExecutionSynchronizationContext to track any attempted // use of it. var denyExecutionSynchronizationContext = new DenyExecutionSynchronizationContext(SynchronizationContext.Current); mainThread = denyExecutionSynchronizationContext.MainThread; synchronizationContext = denyExecutionSynchronizationContext; } return (new JoinableTaskContext(mainThread, synchronizationContext), synchronizationContext); } [Export] private JoinableTaskContext JoinableTaskContext { get; } internal SynchronizationContext SynchronizationContext { get; } internal static SynchronizationContext? GetEffectiveSynchronizationContext() { if (SynchronizationContext.Current is AsyncTestSyncContext asyncTestSyncContext) { SynchronizationContext? innerSynchronizationContext = null; asyncTestSyncContext.Send( _ => { innerSynchronizationContext = SynchronizationContext.Current; }, null); return innerSynchronizationContext; } else { return SynchronizationContext.Current; } } /// <summary> /// Reset the thread affinity, in particular the designated foreground thread, to the active /// thread. /// </summary> internal static void ResetThreadAffinity(JoinableTaskFactory joinableTaskFactory) { // HACK: When the platform team took over several of our components they created a copy // of ForegroundThreadAffinitizedObject. This needs to be reset in the same way as our copy // does. Reflection is the only choice at the moment. var thread = joinableTaskFactory.Context.MainThread; var taskScheduler = new JoinableTaskFactoryTaskScheduler(joinableTaskFactory); foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) { var type = assembly.GetType("Microsoft.VisualStudio.Language.Intellisense.Implementation.ForegroundThreadAffinitizedObject", throwOnError: false); if (type != null) { type.GetField("foregroundThread", BindingFlags.Static | BindingFlags.NonPublic)!.SetValue(null, thread); type.GetField("ForegroundTaskScheduler", BindingFlags.Static | BindingFlags.NonPublic)!.SetValue(null, taskScheduler); break; } } } // HACK: Part of ResetThreadAffinity private class JoinableTaskFactoryTaskScheduler : TaskScheduler { private readonly JoinableTaskFactory _joinableTaskFactory; public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory) => _joinableTaskFactory = joinableTaskFactory; public override int MaximumConcurrencyLevel => 1; protected override IEnumerable<Task>? GetScheduledTasks() => null; protected override void QueueTask(Task task) { _joinableTaskFactory.RunAsync(async () => { await _joinableTaskFactory.SwitchToMainThreadAsync(); TryExecuteTask(task); }); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (_joinableTaskFactory.Context.IsOnMainThread) { return TryExecuteTask(task); } return false; } } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.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.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public abstract partial class AbstractCodeActionTest : AbstractCodeActionOrUserDiagnosticTest { protected abstract CodeRefactoringProvider CreateCodeRefactoringProvider( Workspace workspace, TestParameters parameters); protected override async Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync( TestWorkspace workspace, TestParameters parameters) { var refactoring = await GetCodeRefactoringAsync(workspace, parameters); var actions = refactoring == null ? ImmutableArray<CodeAction>.Empty : refactoring.CodeActions.Select(n => n.action).AsImmutable(); actions = MassageActions(actions); return (actions, actions.IsDefaultOrEmpty ? null : actions[parameters.index]); } protected override Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync(TestWorkspace workspace, TestParameters parameters) => SpecializedTasks.EmptyImmutableArray<Diagnostic>(); internal async Task<CodeRefactoring> GetCodeRefactoringAsync( TestWorkspace workspace, TestParameters parameters) { return (await GetCodeRefactoringsAsync(workspace, parameters)).FirstOrDefault(); } private async Task<IEnumerable<CodeRefactoring>> GetCodeRefactoringsAsync( TestWorkspace workspace, TestParameters parameters) { var provider = CreateCodeRefactoringProvider(workspace, parameters); return SpecializedCollections.SingletonEnumerable( await GetCodeRefactoringAsync(provider, workspace)); } private static async Task<CodeRefactoring> GetCodeRefactoringAsync( CodeRefactoringProvider provider, TestWorkspace workspace) { var documentsWithSelections = workspace.Documents.Where(d => !d.IsLinkFile && d.SelectedSpans.Count == 1); Debug.Assert(documentsWithSelections.Count() == 1, "One document must have a single span annotation"); var span = documentsWithSelections.Single().SelectedSpans.Single(); var actions = ArrayBuilder<(CodeAction, TextSpan?)>.GetInstance(); var document = workspace.CurrentSolution.GetDocument(documentsWithSelections.Single().Id); var context = new CodeRefactoringContext(document, span, (a, t) => actions.Add((a, t)), isBlocking: false, CancellationToken.None); await provider.ComputeRefactoringsAsync(context); var result = actions.Count > 0 ? new CodeRefactoring(provider, actions.ToImmutable()) : null; actions.Free(); return result; } protected async Task TestActionOnLinkedFiles( TestWorkspace workspace, string expectedText, CodeAction action, string expectedPreviewContents = null) { var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default); await VerifyPreviewContents(workspace, expectedPreviewContents, operations); var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First(); applyChangesOperation.TryApply(workspace, new ProgressTracker(), CancellationToken.None); foreach (var document in workspace.Documents) { var fixedRoot = await workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync(); var actualText = fixedRoot.ToFullString(); Assert.Equal(expectedText, actualText); } } private static async Task VerifyPreviewContents( TestWorkspace workspace, string expectedPreviewContents, ImmutableArray<CodeActionOperation> operations) { if (expectedPreviewContents != null) { var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); var content = (await editHandler.GetPreviews(workspace, operations, CancellationToken.None).GetPreviewsAsync())[0]; var diffView = content as DifferenceViewerPreview; Assert.NotNull(diffView.Viewer); var previewContents = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString(); diffView.Dispose(); Assert.Equal(expectedPreviewContents, previewContents); } } protected static Document GetDocument(TestWorkspace workspace) => workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); internal static void EnableOptions( ImmutableArray<PickMembersOption> options, params string[] ids) { foreach (var id in ids) { EnableOption(options, id); } } internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id) { var option = options.FirstOrDefault(o => o.Id == id); if (option != null) { option.Value = true; } } internal Task TestWithPickMembersDialogAsync( string initialMarkup, string expectedMarkup, string[] chosenSymbols, Action<ImmutableArray<PickMembersOption>> optionsCallback = null, int index = 0, TestParameters parameters = default) { var pickMembersService = new TestPickMembersService(chosenSymbols.AsImmutableOrNull(), optionsCallback); return TestInRegularAndScript1Async( initialMarkup, expectedMarkup, index, parameters.WithFixProviderData(pickMembersService)); } } [ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host), Shared, PartNotDiscoverable] internal class TestPickMembersService : IPickMembersService { public ImmutableArray<string> MemberNames; public Action<ImmutableArray<PickMembersOption>> OptionsCallback; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestPickMembersService() { } #pragma warning disable RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute' public TestPickMembersService( ImmutableArray<string> memberNames, Action<ImmutableArray<PickMembersOption>> optionsCallback) { MemberNames = memberNames; OptionsCallback = optionsCallback; } #pragma warning restore RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute' public PickMembersResult PickMembers( string title, ImmutableArray<ISymbol> members, ImmutableArray<PickMembersOption> options, bool selectAll) { OptionsCallback?.Invoke(options); return new PickMembersResult( MemberNames.IsDefault ? members : MemberNames.SelectAsArray(n => members.Single(m => m.Name == n)), options, selectAll); } } }
// 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.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public abstract partial class AbstractCodeActionTest : AbstractCodeActionOrUserDiagnosticTest { protected abstract CodeRefactoringProvider CreateCodeRefactoringProvider( Workspace workspace, TestParameters parameters); protected override async Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync( TestWorkspace workspace, TestParameters parameters) { var refactoring = await GetCodeRefactoringAsync(workspace, parameters); var actions = refactoring == null ? ImmutableArray<CodeAction>.Empty : refactoring.CodeActions.Select(n => n.action).AsImmutable(); actions = MassageActions(actions); return (actions, actions.IsDefaultOrEmpty ? null : actions[parameters.index]); } protected override Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync(TestWorkspace workspace, TestParameters parameters) => SpecializedTasks.EmptyImmutableArray<Diagnostic>(); internal async Task<CodeRefactoring> GetCodeRefactoringAsync( TestWorkspace workspace, TestParameters parameters) { return (await GetCodeRefactoringsAsync(workspace, parameters)).FirstOrDefault(); } private async Task<IEnumerable<CodeRefactoring>> GetCodeRefactoringsAsync( TestWorkspace workspace, TestParameters parameters) { var provider = CreateCodeRefactoringProvider(workspace, parameters); return SpecializedCollections.SingletonEnumerable( await GetCodeRefactoringAsync(provider, workspace)); } private static async Task<CodeRefactoring> GetCodeRefactoringAsync( CodeRefactoringProvider provider, TestWorkspace workspace) { var documentsWithSelections = workspace.Documents.Where(d => !d.IsLinkFile && d.SelectedSpans.Count == 1); Debug.Assert(documentsWithSelections.Count() == 1, "One document must have a single span annotation"); var span = documentsWithSelections.Single().SelectedSpans.Single(); var actions = ArrayBuilder<(CodeAction, TextSpan?)>.GetInstance(); var document = workspace.CurrentSolution.GetDocument(documentsWithSelections.Single().Id); var context = new CodeRefactoringContext(document, span, (a, t) => actions.Add((a, t)), isBlocking: false, CancellationToken.None); await provider.ComputeRefactoringsAsync(context); var result = actions.Count > 0 ? new CodeRefactoring(provider, actions.ToImmutable()) : null; actions.Free(); return result; } protected async Task TestActionOnLinkedFiles( TestWorkspace workspace, string expectedText, CodeAction action, string expectedPreviewContents = null) { var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default); await VerifyPreviewContents(workspace, expectedPreviewContents, operations); var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First(); applyChangesOperation.TryApply(workspace, new ProgressTracker(), CancellationToken.None); foreach (var document in workspace.Documents) { var fixedRoot = await workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync(); var actualText = fixedRoot.ToFullString(); Assert.Equal(expectedText, actualText); } } private static async Task VerifyPreviewContents( TestWorkspace workspace, string expectedPreviewContents, ImmutableArray<CodeActionOperation> operations) { if (expectedPreviewContents != null) { var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); var content = (await editHandler.GetPreviews(workspace, operations, CancellationToken.None).GetPreviewsAsync())[0]; var diffView = content as DifferenceViewerPreview; Assert.NotNull(diffView.Viewer); var previewContents = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString(); diffView.Dispose(); Assert.Equal(expectedPreviewContents, previewContents); } } protected static Document GetDocument(TestWorkspace workspace) => workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); internal static void EnableOptions( ImmutableArray<PickMembersOption> options, params string[] ids) { foreach (var id in ids) { EnableOption(options, id); } } internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id) { var option = options.FirstOrDefault(o => o.Id == id); if (option != null) { option.Value = true; } } internal Task TestWithPickMembersDialogAsync( string initialMarkup, string expectedMarkup, string[] chosenSymbols, Action<ImmutableArray<PickMembersOption>> optionsCallback = null, int index = 0, TestParameters parameters = default) { var pickMembersService = new TestPickMembersService(chosenSymbols.AsImmutableOrNull(), optionsCallback); return TestInRegularAndScript1Async( initialMarkup, expectedMarkup, index, parameters.WithFixProviderData(pickMembersService)); } } [ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host), Shared, PartNotDiscoverable] internal class TestPickMembersService : IPickMembersService { public ImmutableArray<string> MemberNames; public Action<ImmutableArray<PickMembersOption>> OptionsCallback; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestPickMembersService() { } #pragma warning disable RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute' public TestPickMembersService( ImmutableArray<string> memberNames, Action<ImmutableArray<PickMembersOption>> optionsCallback) { MemberNames = memberNames; OptionsCallback = optionsCallback; } #pragma warning restore RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute' public PickMembersResult PickMembers( string title, ImmutableArray<ISymbol> members, ImmutableArray<PickMembersOption> options, bool selectAll) { OptionsCallback?.Invoke(options); return new PickMembersResult( MemberNames.IsDefault ? members : MemberNames.SelectAsArray(n => members.Single(m => m.Name == n)), options, selectAll); } } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/EditorFeatures/VisualBasic/GoToDefinition/VisualBasicGoToDefinitionService.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.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.GoToDefinition Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.GoToDefinition <ExportLanguageService(GetType(IGoToDefinitionService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicGoToDefinitionService Inherits AbstractGoToDefinitionService <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New(threadingContext As IThreadingContext, streamingPresenter As IStreamingFindUsagesPresenter) MyBase.New(threadingContext, streamingPresenter) 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.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.GoToDefinition Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.GoToDefinition <ExportLanguageService(GetType(IGoToDefinitionService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicGoToDefinitionService Inherits AbstractGoToDefinitionService <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New(threadingContext As IThreadingContext, streamingPresenter As IStreamingFindUsagesPresenter) MyBase.New(threadingContext, streamingPresenter) End Sub End Class End Namespace
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Features/Core/Portable/Completion/CompletionProvider.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Implement a subtype of this class and export it to provide completions during typing in an editor. /// </summary> public abstract class CompletionProvider { internal string Name { get; } protected CompletionProvider() => Name = GetType().FullName; /// <summary> /// Implement to contribute <see cref="CompletionItem"/>'s and other details to a <see cref="CompletionList"/> /// </summary> public abstract Task ProvideCompletionsAsync(CompletionContext context); /// <summary> /// Returns true if the character recently inserted or deleted in the text should trigger completion. /// </summary> /// <param name="text">The text that completion is occurring within.</param> /// <param name="caretPosition">The position of the caret after the triggering action.</param> /// <param name="trigger">The triggering action.</param> /// <param name="options">The set of options in effect.</param> public virtual bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options) => false; /// <summary> /// Returns true if the character recently inserted or deleted in the text should trigger completion. /// </summary> /// <param name="languageServices">The language services available on the text document.</param> /// <param name="text">The text that completion is occurring within.</param> /// <param name="caretPosition">The position of the caret after the triggering action.</param> /// <param name="trigger">The triggering action.</param> /// <param name="options">The set of options in effect.</param> internal virtual bool ShouldTriggerCompletion(HostLanguageServices languageServices, SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options) => ShouldTriggerCompletion(text, caretPosition, trigger, options); /// <summary> /// This allows Completion Providers that indicated they were triggered textually to use syntax to /// confirm they are really triggered, or decide they are not actually triggered and should become /// an augmenting provider instead. /// </summary> internal virtual async Task<bool> IsSyntacticTriggerCharacterAsync(Document document, int caretPosition, CompletionTrigger trigger, OptionSet options, CancellationToken cancellationToken) => ShouldTriggerCompletion(document.Project.LanguageServices, await document.GetTextAsync(cancellationToken).ConfigureAwait(false), caretPosition, trigger, options); /// <summary> /// Gets the description of the specified item. /// </summary> public virtual Task<CompletionDescription> GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => Task.FromResult(CompletionDescription.Empty); /// <summary> /// Gets the change to be applied when the specified item is committed. /// </summary> /// <param name="document">The current document.</param> /// <param name="item">The item to be committed.</param> /// <param name="commitKey">The optional key character that caused the commit.</param> /// <param name="cancellationToken"></param> public virtual Task<CompletionChange> GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) => Task.FromResult(CompletionChange.Create(new TextChange(item.Span, item.DisplayText))); /// <summary> /// True if the provider produces snippet items. /// </summary> internal virtual bool IsSnippetProvider => false; /// <summary> /// True if the provider produces items show be shown in expanded list only. /// </summary> internal virtual bool IsExpandItemProvider => 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Implement a subtype of this class and export it to provide completions during typing in an editor. /// </summary> public abstract class CompletionProvider { internal string Name { get; } protected CompletionProvider() => Name = GetType().FullName; /// <summary> /// Implement to contribute <see cref="CompletionItem"/>'s and other details to a <see cref="CompletionList"/> /// </summary> public abstract Task ProvideCompletionsAsync(CompletionContext context); /// <summary> /// Returns true if the character recently inserted or deleted in the text should trigger completion. /// </summary> /// <param name="text">The text that completion is occurring within.</param> /// <param name="caretPosition">The position of the caret after the triggering action.</param> /// <param name="trigger">The triggering action.</param> /// <param name="options">The set of options in effect.</param> public virtual bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options) => false; /// <summary> /// Returns true if the character recently inserted or deleted in the text should trigger completion. /// </summary> /// <param name="languageServices">The language services available on the text document.</param> /// <param name="text">The text that completion is occurring within.</param> /// <param name="caretPosition">The position of the caret after the triggering action.</param> /// <param name="trigger">The triggering action.</param> /// <param name="options">The set of options in effect.</param> internal virtual bool ShouldTriggerCompletion(HostLanguageServices languageServices, SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options) => ShouldTriggerCompletion(text, caretPosition, trigger, options); /// <summary> /// This allows Completion Providers that indicated they were triggered textually to use syntax to /// confirm they are really triggered, or decide they are not actually triggered and should become /// an augmenting provider instead. /// </summary> internal virtual async Task<bool> IsSyntacticTriggerCharacterAsync(Document document, int caretPosition, CompletionTrigger trigger, OptionSet options, CancellationToken cancellationToken) => ShouldTriggerCompletion(document.Project.LanguageServices, await document.GetTextAsync(cancellationToken).ConfigureAwait(false), caretPosition, trigger, options); /// <summary> /// Gets the description of the specified item. /// </summary> public virtual Task<CompletionDescription> GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => Task.FromResult(CompletionDescription.Empty); /// <summary> /// Gets the change to be applied when the specified item is committed. /// </summary> /// <param name="document">The current document.</param> /// <param name="item">The item to be committed.</param> /// <param name="commitKey">The optional key character that caused the commit.</param> /// <param name="cancellationToken"></param> public virtual Task<CompletionChange> GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) => Task.FromResult(CompletionChange.Create(new TextChange(item.Span, item.DisplayText))); /// <summary> /// True if the provider produces snippet items. /// </summary> internal virtual bool IsSnippetProvider => false; /// <summary> /// True if the provider produces items show be shown in expanded list only. /// </summary> internal virtual bool IsExpandItemProvider => false; } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Features/Core/Portable/CodeLens/CodeLensReferencesServiceFactory.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.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CodeLens { [ExportWorkspaceServiceFactory(typeof(ICodeLensReferencesService)), Shared] internal sealed class CodeLensReferencesServiceFactory : IWorkspaceServiceFactory { public static readonly ICodeLensReferencesService Instance = new CodeLensReferencesService(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CodeLensReferencesServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => Instance; } }
// 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.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CodeLens { [ExportWorkspaceServiceFactory(typeof(ICodeLensReferencesService)), Shared] internal sealed class CodeLensReferencesServiceFactory : IWorkspaceServiceFactory { public static readonly ICodeLensReferencesService Instance = new CodeLensReferencesService(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CodeLensReferencesServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => Instance; } }
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/EditorFeatures/VisualBasicTest/SignatureHelp/GenericNameSignatureHelpProviderTests.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.Editor.UnitTests.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp Public Class GenericNameSignatureHelpProviderTests Inherits AbstractVisualBasicSignatureHelpProviderTests Friend Overrides Function GetSignatureHelpProviderType() As Type Return GetType(GenericNameSignatureHelpProvider) End Function #Region "Declaring generic type objects" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith1ParameterUnterminated() As Task Dim markup = <a><![CDATA[ Class G(Of T) End Class Class C Sub Goo() Dim q As [|G(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith1ParameterTerminated() As Task Dim markup = <a><![CDATA[ Class G(Of T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn1() As Task Dim markup = <a><![CDATA[ Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn2() As Task Dim markup = <a><![CDATA[ Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn1XmlDoc() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS. Also see <see cref="C"/></typeparam> ''' <typeparam name="T">ParamT</typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamS. Also see C", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn2XmlDoc() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT. Also see <see cref="C"/></typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamT. Also see C", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(827031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827031")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn1XmlDocReferencingTypeParams() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS. Also see <see cref="T"/></typeparam> ''' <typeparam name="T">ParamT. Also see <see cref="S"/></typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamS. Also see T", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(827031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827031")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn2XmlDocReferencingTypeParams() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS. Also see <see cref="T"/></typeparam> ''' <typeparam name="T">ParamT. Also see <see cref="S"/></typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamT. Also see S", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Constraints on generic types" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsStructure() As Task Dim markup = <a><![CDATA[ Class G(Of S As Structure, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As Structure, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsClass() As Task Dim markup = <a><![CDATA[ Class G(Of S As Class, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As Class, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsNew() As Task Dim markup = <a><![CDATA[ Class G(Of S As New, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As New, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBase() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Class G(Of S As SomeBaseClass, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBaseGenericWithGeneric() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass(Of X) End Class Class G(Of S As SomeBaseClass(Of S), T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass(Of S), T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBaseGenericWithNonGeneric() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass(Of X) End Class Class G(Of S As SomeBaseClass(Of Integer), T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass(Of Integer), T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBaseGenericWithGenericNested() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass(Of X) End Class Class G(Of S As SomeBaseClass(Of SomeBaseClass(Of S)), T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass(Of SomeBaseClass(Of S)), T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsDeriveFromAnotherGenericParameter() As Task Dim markup = <a><![CDATA[ Class G(Of S As T, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As T, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsMixed1() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Class G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New}) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})", "SummaryG", "ParamS", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsMixed2() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Class G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New}) End Class Class C Sub Goo() Dim q As [|G(Of Bar, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})", "SummaryG", "ParamT", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Generic member invocation" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith1ParameterUnterminated() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of T)(arg As T) As T End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(arg As T) As T", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith1ParameterTerminated() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of T)(arg As T) As T End Function Sub Bar() [|Goo(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(arg As T) As T", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn1() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of S, T)(arg As T) As S End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As S", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn2() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of S, T)(arg As T) As T End Function Sub Bar() [|Goo(Of Integer, $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As T", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn1XmlDoc() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S, T)(arg As T) As S End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As S", "GooSummary", "ParamS", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn2XmlDoc() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S, T)(arg As T) As S End Function Sub Bar() [|Goo(Of Integer, $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As S", "GooSummary", "ParamT", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(544124, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544124")> <WorkItem(544123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544123")> <WorkItem(684631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684631")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestCallingGenericExtensionMethod() As Task Dim markup = <a><![CDATA[ Imports System Class D End Class Module ExtnMethods <Runtime.CompilerServices.Extension()> Function Goo(Of S, T)(ByRef dClass As D, objS as S, objT As T) As S End Function End Module Class C Sub Bar() Dim obj As D = Nothing obj.[|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem($"<{VBFeaturesResources.Extension}> D.Goo(Of S, T)(objS As S, objT As T) As S", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Constraints on generic methods" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodTypeWithConstraintsMixed1() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T", "GooSummary", "ParamS", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWithConstraintsMixed2() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T End Function Sub Bar() [|Goo(Of Bas, $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T", "GooSummary", "ParamT", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Trigger tests" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerSpace() As Task Dim markup = <a><![CDATA[ Class G(Of T) End Class Class C Sub Goo() Dim q As [|G(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerComma() As Task Dim markup = <a><![CDATA[ Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer,$$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestTriggerCharacters() Dim expectedTriggerCharacters() As Char = {","c, " "c} Dim unexpectedTriggerCharacters() As Char = {"["c, "<"c, "("c} VerifyTriggerCharacters(expectedTriggerCharacters, unexpectedTriggerCharacters) End Sub #End Region #Region "EditorBrowsable tests" <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub Goo(Of T)(x As T) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(Of T)(x As T) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Sub Goo(Of T)(x As T) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableMixed() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub Goo(Of T)(x As T) End Sub <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(Of T, U)(x As T, y As U) End Sub End Class ]]></Text>.Value Dim expectedOrderedItemsMetadataReference = New List(Of SignatureHelpTestItem)() expectedOrderedItemsMetadataReference.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Dim expectedOrderedItemsSameSolution = New List(Of SignatureHelpTestItem)() expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C.Goo(Of T, U)(x As T, y As U)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution:=expectedOrderedItemsSameSolution, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericType_BrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class C(Of T) End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericType_BrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class C(Of T) End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericType_BrowsableAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Class C(Of T) End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function #End Region 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.Editor.UnitTests.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp Public Class GenericNameSignatureHelpProviderTests Inherits AbstractVisualBasicSignatureHelpProviderTests Friend Overrides Function GetSignatureHelpProviderType() As Type Return GetType(GenericNameSignatureHelpProvider) End Function #Region "Declaring generic type objects" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith1ParameterUnterminated() As Task Dim markup = <a><![CDATA[ Class G(Of T) End Class Class C Sub Goo() Dim q As [|G(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith1ParameterTerminated() As Task Dim markup = <a><![CDATA[ Class G(Of T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn1() As Task Dim markup = <a><![CDATA[ Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn2() As Task Dim markup = <a><![CDATA[ Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn1XmlDoc() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS. Also see <see cref="C"/></typeparam> ''' <typeparam name="T">ParamT</typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamS. Also see C", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn2XmlDoc() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT. Also see <see cref="C"/></typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamT. Also see C", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(827031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827031")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn1XmlDocReferencingTypeParams() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS. Also see <see cref="T"/></typeparam> ''' <typeparam name="T">ParamT. Also see <see cref="S"/></typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamS. Also see T", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(827031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827031")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn2XmlDocReferencingTypeParams() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS. Also see <see cref="T"/></typeparam> ''' <typeparam name="T">ParamT. Also see <see cref="S"/></typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamT. Also see S", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Constraints on generic types" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsStructure() As Task Dim markup = <a><![CDATA[ Class G(Of S As Structure, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As Structure, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsClass() As Task Dim markup = <a><![CDATA[ Class G(Of S As Class, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As Class, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsNew() As Task Dim markup = <a><![CDATA[ Class G(Of S As New, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As New, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBase() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Class G(Of S As SomeBaseClass, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBaseGenericWithGeneric() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass(Of X) End Class Class G(Of S As SomeBaseClass(Of S), T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass(Of S), T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBaseGenericWithNonGeneric() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass(Of X) End Class Class G(Of S As SomeBaseClass(Of Integer), T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass(Of Integer), T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBaseGenericWithGenericNested() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass(Of X) End Class Class G(Of S As SomeBaseClass(Of SomeBaseClass(Of S)), T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass(Of SomeBaseClass(Of S)), T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsDeriveFromAnotherGenericParameter() As Task Dim markup = <a><![CDATA[ Class G(Of S As T, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As T, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsMixed1() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Class G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New}) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})", "SummaryG", "ParamS", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsMixed2() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Class G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New}) End Class Class C Sub Goo() Dim q As [|G(Of Bar, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})", "SummaryG", "ParamT", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Generic member invocation" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith1ParameterUnterminated() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of T)(arg As T) As T End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(arg As T) As T", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith1ParameterTerminated() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of T)(arg As T) As T End Function Sub Bar() [|Goo(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(arg As T) As T", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn1() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of S, T)(arg As T) As S End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As S", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn2() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of S, T)(arg As T) As T End Function Sub Bar() [|Goo(Of Integer, $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As T", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn1XmlDoc() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S, T)(arg As T) As S End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As S", "GooSummary", "ParamS", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn2XmlDoc() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S, T)(arg As T) As S End Function Sub Bar() [|Goo(Of Integer, $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As S", "GooSummary", "ParamT", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(544124, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544124")> <WorkItem(544123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544123")> <WorkItem(684631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684631")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestCallingGenericExtensionMethod() As Task Dim markup = <a><![CDATA[ Imports System Class D End Class Module ExtnMethods <Runtime.CompilerServices.Extension()> Function Goo(Of S, T)(ByRef dClass As D, objS as S, objT As T) As S End Function End Module Class C Sub Bar() Dim obj As D = Nothing obj.[|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem($"<{VBFeaturesResources.Extension}> D.Goo(Of S, T)(objS As S, objT As T) As S", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Constraints on generic methods" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodTypeWithConstraintsMixed1() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T", "GooSummary", "ParamS", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWithConstraintsMixed2() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T End Function Sub Bar() [|Goo(Of Bas, $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T", "GooSummary", "ParamT", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Trigger tests" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerSpace() As Task Dim markup = <a><![CDATA[ Class G(Of T) End Class Class C Sub Goo() Dim q As [|G(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerComma() As Task Dim markup = <a><![CDATA[ Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer,$$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestTriggerCharacters() Dim expectedTriggerCharacters() As Char = {","c, " "c} Dim unexpectedTriggerCharacters() As Char = {"["c, "<"c, "("c} VerifyTriggerCharacters(expectedTriggerCharacters, unexpectedTriggerCharacters) End Sub #End Region #Region "EditorBrowsable tests" <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub Goo(Of T)(x As T) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(Of T)(x As T) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Sub Goo(Of T)(x As T) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableMixed() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub Goo(Of T)(x As T) End Sub <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(Of T, U)(x As T, y As U) End Sub End Class ]]></Text>.Value Dim expectedOrderedItemsMetadataReference = New List(Of SignatureHelpTestItem)() expectedOrderedItemsMetadataReference.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Dim expectedOrderedItemsSameSolution = New List(Of SignatureHelpTestItem)() expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C.Goo(Of T, U)(x As T, y As U)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution:=expectedOrderedItemsSameSolution, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericType_BrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class C(Of T) End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericType_BrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class C(Of T) End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericType_BrowsableAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Class C(Of T) End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function #End Region End Class End Namespace
-1
dotnet/roslyn
55,448
MEF import completion providers in background
Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
genlu
2021-08-05T23:14:11Z
2021-08-06T00:33:20Z
75a39a2831b2ca2f91968ad4afedea41e457f3fb
0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad
MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321)
./src/Analyzers/VisualBasic/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests_FixAllTests.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.RemoveUnnecessaryCast Partial Public Class RemoveUnnecessaryCastTests <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInDocument() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = {|FixAllInDocument:CInt(0)|} Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) Dim prog = New Program Dim x = ((DirectCast(Prog, Program)).F) Dim x2 = ((DirectCast(Prog, Program)).F) End Sub End Class]]> </Document> <Document><![CDATA[ Imports System Class Program2 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) Dim prog = New Program Dim x = ((DirectCast(Prog, Program)).F) Dim x2 = ((DirectCast(Prog, Program)).F) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program3 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) Dim prog = New Program Dim x = ((DirectCast(Prog, Program)).F) Dim x2 = ((DirectCast(Prog, Program)).F) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private f As Char = "c"C Public Sub F(Optional x As Integer = 0) ' unnecessary casts Dim y As Integer = 0 Dim z As Boolean = True ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = CObj(If(z, s1, s2)) Dim prog = New Program Dim x = ((Prog).F) Dim x2 = ((Prog).F) End Sub End Class]]> </Document> <Document><![CDATA[ Imports System Class Program2 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) Dim prog = New Program Dim x = ((DirectCast(Prog, Program)).F) Dim x2 = ((DirectCast(Prog, Program)).F) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program3 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) Dim prog = New Program Dim x = ((DirectCast(Prog, Program)).F) Dim x2 = ((DirectCast(Prog, Program)).F) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInProject() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = {|FixAllInProject:CInt(0)|} Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> <Document><![CDATA[ Imports System Class Program2 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program3 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private f As Char = "c"C Public Sub F(Optional x As Integer = 0) ' unnecessary casts Dim y As Integer = 0 Dim z As Boolean = True ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = CObj(If(z, s1, s2)) End Sub End Class]]> </Document> <Document><![CDATA[ Imports System Class Program2 Private f As Char = "c"C Public Sub F(Optional x As Integer = 0) ' unnecessary casts Dim y As Integer = 0 Dim z As Boolean = True ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = CObj(If(z, s1, s2)) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program3 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInSolution() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = {|FixAllInSolution:CInt(0)|} Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> <Document><![CDATA[ Imports System Class Program2 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program3 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private f As Char = "c"C Public Sub F(Optional x As Integer = 0) ' unnecessary casts Dim y As Integer = 0 Dim z As Boolean = True ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = CObj(If(z, s1, s2)) End Sub End Class]]> </Document> <Document><![CDATA[ Imports System Class Program2 Private f As Char = "c"C Public Sub F(Optional x As Integer = 0) ' unnecessary casts Dim y As Integer = 0 Dim z As Boolean = True ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = CObj(If(z, s1, s2)) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program3 Private f As Char = "c"C Public Sub F(Optional x As Integer = 0) ' unnecessary casts Dim y As Integer = 0 Dim z As Boolean = True ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = CObj(If(z, s1, s2)) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnnecessaryCast Partial Public Class RemoveUnnecessaryCastTests <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInDocument() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = {|FixAllInDocument:CInt(0)|} Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) Dim prog = New Program Dim x = ((DirectCast(Prog, Program)).F) Dim x2 = ((DirectCast(Prog, Program)).F) End Sub End Class]]> </Document> <Document><![CDATA[ Imports System Class Program2 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) Dim prog = New Program Dim x = ((DirectCast(Prog, Program)).F) Dim x2 = ((DirectCast(Prog, Program)).F) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program3 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) Dim prog = New Program Dim x = ((DirectCast(Prog, Program)).F) Dim x2 = ((DirectCast(Prog, Program)).F) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private f As Char = "c"C Public Sub F(Optional x As Integer = 0) ' unnecessary casts Dim y As Integer = 0 Dim z As Boolean = True ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = CObj(If(z, s1, s2)) Dim prog = New Program Dim x = ((Prog).F) Dim x2 = ((Prog).F) End Sub End Class]]> </Document> <Document><![CDATA[ Imports System Class Program2 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) Dim prog = New Program Dim x = ((DirectCast(Prog, Program)).F) Dim x2 = ((DirectCast(Prog, Program)).F) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program3 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) Dim prog = New Program Dim x = ((DirectCast(Prog, Program)).F) Dim x2 = ((DirectCast(Prog, Program)).F) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInProject() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = {|FixAllInProject:CInt(0)|} Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> <Document><![CDATA[ Imports System Class Program2 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program3 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private f As Char = "c"C Public Sub F(Optional x As Integer = 0) ' unnecessary casts Dim y As Integer = 0 Dim z As Boolean = True ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = CObj(If(z, s1, s2)) End Sub End Class]]> </Document> <Document><![CDATA[ Imports System Class Program2 Private f As Char = "c"C Public Sub F(Optional x As Integer = 0) ' unnecessary casts Dim y As Integer = 0 Dim z As Boolean = True ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = CObj(If(z, s1, s2)) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program3 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInSolution() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = {|FixAllInSolution:CInt(0)|} Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> <Document><![CDATA[ Imports System Class Program2 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program3 Private f As Char = CChar("c"C) Public Sub F(Optional x As Integer = CInt(0)) ' unnecessary casts Dim y As Integer = CInt(0) Dim z As Boolean = CBool(True) ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = If(z, DirectCast(s1, Object), DirectCast(s2, Object)) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private f As Char = "c"C Public Sub F(Optional x As Integer = 0) ' unnecessary casts Dim y As Integer = 0 Dim z As Boolean = True ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = CObj(If(z, s1, s2)) End Sub End Class]]> </Document> <Document><![CDATA[ Imports System Class Program2 Private f As Char = "c"C Public Sub F(Optional x As Integer = 0) ' unnecessary casts Dim y As Integer = 0 Dim z As Boolean = True ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = CObj(If(z, s1, s2)) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program3 Private f As Char = "c"C Public Sub F(Optional x As Integer = 0) ' unnecessary casts Dim y As Integer = 0 Dim z As Boolean = True ' required cast Dim l As Long = 1 Dim ll = CInt(l) ' required cast after cast removal in same statement Dim s1 As String = Nothing, s2 As String = Nothing Dim s3 = CObj(If(z, s1, s2)) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function End Class End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/EditorFeatures/CSharpTest/CodeActions/ExtractMethod/ExtractLocalFunctionTests.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.CodeRefactorings.ExtractMethod; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ExtractMethod { public class ExtractLocalFunctionTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new ExtractMethodCodeRefactoringProvider(); private static int CodeActionIndexWhenExtractMethodMissing => 0; private static int CodeActionIndex => 1; private const string EditorConfigNaming_CamelCase = @"[*] # Naming rules dotnet_naming_rule.local_functions_should_be_camel_case.severity = suggestion dotnet_naming_rule.local_functions_should_be_camel_case.symbols = local_functions dotnet_naming_rule.local_functions_should_be_camel_case.style = camel_case # Symbol specifications dotnet_naming_symbols.local_functions.applicable_kinds = local_function dotnet_naming_symbols.local_functions.applicable_accessibilities = * # Naming styles dotnet_naming_style.camel_case.capitalization = camel_case"; private const string EditorConfigNaming_PascalCase = @"[*] # Naming rules dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions dotnet_naming_rule.local_functions_should_be_pascal_case.style = pascal_case # Symbol specifications dotnet_naming_symbols.local_functions.applicable_kinds = local_function dotnet_naming_symbols.local_functions.applicable_accessibilities = * dotnet_naming_symbols.local_functions.required_modifiers = # Naming styles dotnet_naming_style.pascal_case.capitalization = pascal_case"; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionTrue() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionFalse() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionDefault() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CSharpCodeStyleOptions.PreferStaticLocalFunction.DefaultValue))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseExpressionBodyWhenPossible() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) => b != true; } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) => b != true; } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine( [|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine( {|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) => b != true; } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b !=/* */true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) { return b !=/* */true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine3() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|"""" != @"" ""|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}() ? b = true : b = false); static bool NewMethod() { return """" != @"" ""; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestReadOfDataThatDoesNotFlowIn() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { int x = 1; object y = 0; [|int s = true ? fun(x) : fun(y);|] } private static T fun<T>(T t) { return t; } }", @"class Program { static void Main(string[] args) { int x = 1; object y = 0; {|Rename:NewMethod|}(x, y); static void NewMethod(int x, object y) { int s = true ? fun(x) : fun(y); } } private static T fun<T>(T t) { return t; } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnStatementAfterUnconditionalGoto() { await TestInRegularAndScript1Async( @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; [|return x * x;|] }; label2: return; } }", @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; return {|Rename:NewMethod|}(x); }; label2: return; static int NewMethod(int x) { return x * x; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnNamespace() { await TestInRegularAndScript1Async( @"class Program { void Main() { [|System|].Console.WriteLine(4); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); static void NewMethod() { System.Console.WriteLine(4); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnType() { await TestInRegularAndScript1Async( @"class Program { void Main() { [|System.Console|].WriteLine(4); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); static void NewMethod() { System.Console.WriteLine(4); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnBase() { await TestInRegularAndScript1Async( @"class Program { void Main() { [|base|].ToString(); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); void NewMethod() { base.ToString(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnActionInvocation() { await TestInRegularAndScript1Async( @"using System; class C { public static Action X { get; set; } } class Program { void Main() { [|C.X|](); } }", @"using System; class C { public static Action X { get; set; } } class Program { void Main() { {|Rename:GetX|}()(); static Action GetX() { return C.X; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task DisambiguateCallSiteIfNecessary1() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main() { byte z = 0; Goo([|x => 0|], y => 0, z, z); } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Goo({|Rename:NewMethod|}(), y => (byte)0, z, z); static Func<byte, byte> NewMethod() { return x => 0; } } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task DisambiguateCallSiteIfNecessary2() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main() { byte z = 0; Goo([|x => 0|], y => { return 0; }, z, z); } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Goo({|Rename:NewMethod|}(), y => { return (byte)0; }, z, z); static Func<byte, byte> NewMethod() { return x => 0; } } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task DontOverparenthesize() { await TestAsync( @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex(), y), - -1); } } static class E { public static void Ex(this int x) { } }", @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex(), y), (object)- -1); static string GetX(string x) { return x; } } } static class E { public static void Ex(this int x) { } }", parseOptions: Options.Regular, index: CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task DontOverparenthesizeGenerics() { await TestAsync( @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex<int>(), y), - -1); } } static class E { public static void Ex<T>(this int x) { } }", @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex<int>(), y), (object)- -1); static string GetX(string x) { return x; } } } static class E { public static void Ex<T>(this int x) { } }", parseOptions: Options.Regular, index: CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task PreserveCommentsBeforeDeclaration_1() { await TestInRegularAndScript1Async( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do();|] obj1.Do(); obj2.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2; {|Rename:NewMethod|}(out obj1, out obj2); obj1.Do(); obj2.Do(); static void NewMethod(out Construct obj1, out Construct obj2) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task PreserveCommentsBeforeDeclaration_2() { await TestInRegularAndScript1Async( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ Construct obj3 = new Construct(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ obj3 = new Construct(); obj3.Do(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task PreserveCommentsBeforeDeclaration_3() { await TestInRegularAndScript1Async( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(), obj3 = new Construct(); obj2.Do(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj3 = new Construct(); obj2.Do(); obj3.Do(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTuple() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int, int) x = (1, 2);|] System.Console.WriteLine(x.Item1); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); static (int, int) NewMethod() { return (1, 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleDeclarationWithNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int a, int b) x = (1, 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); static (int a, int b) NewMethod() { return (1, 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleDeclarationWithSomeNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int a, int) x = (1, 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); static (int a, int) NewMethod() { return (1, 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleWith1Arity() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { ValueTuple<int> y = ValueTuple.Create(1); [|y.Item1.ToString();|] } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"using System; class Program { static void Main(string[] args) { ValueTuple<int> y = ValueTuple.Create(1); {|Rename:NewMethod|}(y); static void NewMethod(ValueTuple<int> y) { y.Item1.ToString(); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleLiteralWithNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int, int) x = (a: 1, b: 2);|] System.Console.WriteLine(x.Item1); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); static (int, int) NewMethod() { return (a: 1, b: 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleDeclarationAndLiteralWithNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int a, int b) x = (c: 1, d: 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); static (int a, int b) NewMethod() { return (c: 1, d: 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleIntoVar() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|var x = (c: 1, d: 2);|] System.Console.WriteLine(x.c); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int c, int d) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); static (int c, int d) NewMethod() { return (c: 1, d: 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task RefactorWithoutSystemValueTuple() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|var x = (c: 1, d: 2);|] System.Console.WriteLine(x.c); } }", @"class Program { static void Main(string[] args) { (int c, int d) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); static (int c, int d) NewMethod() { return (c: 1, d: 2); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleWithNestedNamedTuple() { // This is not the best refactoring, but this is an edge case await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|var x = new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world""));|] System.Console.WriteLine(x.c); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int, int, int, int, int, int, string, string) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); static (int, int, int, int, int, int, int, string, string) NewMethod() { return new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world"")); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestDeconstruction() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { var (x, y) = [|(1, 2)|]; System.Console.WriteLine(x); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { var (x, y) = {|Rename:NewMethod|}(); System.Console.WriteLine(x); static (int, int) NewMethod() { return (1, 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestDeconstruction2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { var (x, y) = (1, 2); var z = [|3;|] System.Console.WriteLine(z); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { var (x, y) = (1, 2); int z = {|Rename:NewMethod|}(); System.Console.WriteLine(z); static int NewMethod() { return 3; } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] [CompilerTrait(CompilerFeature.OutVar)] public async Task TestOutVar() { await TestInRegularAndScript1Async( @"class C { static void M(int i) { int r; [|r = M1(out int y, i);|] System.Console.WriteLine(r + y); } }", @"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); static void NewMethod(int i, out int r, out int y) { r = M1(out y, i); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] [CompilerTrait(CompilerFeature.Patterns)] public async Task TestIsPattern() { await TestInRegularAndScript1Async( @"class C { static void M(int i) { int r; [|r = M1(3 is int y, i);|] System.Console.WriteLine(r + y); } }", @"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); static void NewMethod(int i, out int r, out int y) { r = M1(3 is int {|Conflict:y|}, i); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] [CompilerTrait(CompilerFeature.Patterns)] public async Task TestOutVarAndIsPattern() { await TestInRegularAndScript1Async( @"class C { static void M() { int r; [|r = M1(out /*out*/ int /*int*/ y /*y*/) + M2(3 is int z);|] System.Console.WriteLine(r + y + z); } } ", @"class C { static void M() { int r; int y, z; {|Rename:NewMethod|}(out r, out y, out z); System.Console.WriteLine(r + y + z); static void NewMethod(out int r, out int y, out int z) { r = M1(out /*out*/ /*int*/ y /*y*/) + M2(3 is int {|Conflict:z|}); } } } ", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] [CompilerTrait(CompilerFeature.Patterns)] public async Task ConflictingOutVarLocals() { await TestInRegularAndScript1Async( @"class C { static void M() { int r; [|r = M1(out int y); { M2(out int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } }", @"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); static void NewMethod(out int r, out int y) { r = M1(out y); { M2(out int y); System.Console.Write(y); } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] [CompilerTrait(CompilerFeature.Patterns)] public async Task ConflictingPatternLocals() { await TestInRegularAndScript1Async( @"class C { static void M() { int r; [|r = M1(1 is int y); { M2(2 is int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } }", @"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); static void NewMethod(out int r, out int y) { r = M1(1 is int {|Conflict:y|}); { M2(2 is int y); System.Console.Write(y); } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestCancellationTokenGoesLast() { await TestInRegularAndScript1Async( @"using System; using System.Threading; class C { void M(CancellationToken ct) { var v = 0; [|if (true) { ct.ThrowIfCancellationRequested(); Console.WriteLine(v); }|] } }", @"using System; using System.Threading; class C { void M(CancellationToken ct) { var v = 0; {|Rename:NewMethod|}(v, ct); static void NewMethod(int v, CancellationToken ct) { if (true) { ct.ThrowIfCancellationRequested(); Console.WriteLine(v); } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseVar1() { await TestInRegularAndScript1Async( @"using System; class C { void Goo(int i) { [|var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; }|] Console.WriteLine(v); } }", @"using System; class C { void Goo(int i) { var v = {|Rename:NewMethod|}(i); Console.WriteLine(v); static string NewMethod(int i) { var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; } return v; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSuggestionEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseVar2() { await TestInRegularAndScript1Async( @"using System; class C { void Goo(int i) { [|var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; }|] Console.WriteLine(v); } }", @"using System; class C { void Goo(int i) { string v = {|Rename:NewMethod|}(i); Console.WriteLine(v); static string NewMethod(int i) { var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; } return v; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSuggestionEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionCall() { var code = @" class C { public static void Main() { void Local() { } [|Local();|] } }"; var expectedCode = @" class C { public static void Main() { void Local() { } {|Rename:NewMethod|}(); void NewMethod() { Local(); } } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_local_function }); await TestInRegularAndScript1Async(code, expectedCode, CodeActionIndexWhenExtractMethodMissing); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionCall_2() { await TestInRegularAndScript1Async(@" class C { public static void Main() { [|void Local() { } Local();|] } }", @" class C { public static void Main() { {|Rename:NewMethod|}(); static void NewMethod() { void Local() { } Local(); } } }", CodeActionIndex); } [Fact, WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionCall_3() { await TestInRegularAndScript1Async(@" class C { public static void Main() { static void LocalParent() { [|void Local() { } Local();|] } } }", @" class C { public static void Main() { static void LocalParent() { {|Rename:NewMethod|}(); static void NewMethod() { void Local() { } Local(); } } } }", CodeActionIndex); } [Fact, WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractFunctionUnderLocalFunctionCall() { await TestInRegularAndScript1Async(@" class Test { int Testing; void ClassTest() { ExistingLocalFunction(); [|NewMethod();|] Testing = 5; void ExistingLocalFunction() { } } void NewMethod() { } }", @" class Test { int Testing; void ClassTest() { ExistingLocalFunction(); {|Rename:NewMethod1|}(); Testing = 5; void ExistingLocalFunction() { } void NewMethod1() { NewMethod(); } } void NewMethod() { } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionCallWithCapture() { var code = @" class C { public static void Main(string[] args) { bool Local() => args == null; [|Local();|] } }"; var expectedCode = @" class C { public static void Main(string[] args) { bool Local() => args == null; {|Rename:NewMethod|}(args); void NewMethod(string[] args) { Local(); } } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_local_function }); await TestInRegularAndScript1Async(code, expectedCode, CodeActionIndexWhenExtractMethodMissing); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionInterior() { await TestInRegularAndScript1Async(@" class C { public static void Main() { void Local() { [|int x = 0; x++;|] } Local(); } }", @" class C { public static void Main() { void Local() { {|Rename:NewMethod|}(); static void NewMethod() { int x = 0; x++; } } Local(); } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionWithinForLoop() { await TestInRegularAndScript1Async(@" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { [|v = v + i;|] } } } }", @" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { v = {|Rename:NewMethod|}(v, i); } static int NewMethod(int v, int i) { v = v + i; return v; } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionWithinForLoop2() { await TestInRegularAndScript1Async(@" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { [|v = v + i|]; } } } }", @" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { v = {|Rename:NewMethod|}(v, i); } static int NewMethod(int v, int i) { return v + i; } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionWithinForLoop3() { await TestInRegularAndScript1Async(@" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { [|i = v = v + i|]; } } } }", @" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { i = {|Rename:NewMethod|}(ref v, i); } static int NewMethod(ref int v, int i) { return v = v + i; } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestTupleWithInferredNames() { await TestAsync(@" class Program { void M() { int a = 1; var t = [|(a, b: 2)|]; System.Console.Write(t.a); } }", @" class Program { void M() { int a = 1; var t = {|Rename:GetT|}(a); System.Console.Write(t.a); (int a, int b) GetT(int a) { return (a, b: 2); } } }", TestOptions.Regular7_1, index: CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestDeconstruction4() { await TestAsync(@" class Program { void M() { [|var (x, y) = (1, 2);|] System.Console.Write(x + y); } }", @" class Program { void M() { int x, y; {|Rename:NewMethod|}(out x, out y); System.Console.Write(x + y); void NewMethod(out int x, out int y) { var (x, y) = (1, 2); } } }", TestOptions.Regular7_1, index: CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestDeconstruction5() { await TestAsync(@" class Program { void M() { [|(var x, var y) = (1, 2);|] System.Console.Write(x + y); } }", @" class Program { void M() { int x, y; {|Rename:NewMethod|}(out x, out y); System.Console.Write(x + y); void NewMethod(out int x, out int y) { (x, y) = (1, 2); } } }", TestOptions.Regular7_1, index: CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestIndexExpression() { await TestInRegularAndScript1Async(TestSources.Index + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|^1|]); } }", TestSources.Index + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); static System.Index NewMethod() { return ^1; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestRangeExpression_Empty() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|..|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); static System.Range NewMethod() { return ..; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestRangeExpression_Left() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|..1|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); static System.Range NewMethod() { return ..1; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestRangeExpression_Right() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|1..|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); static System.Range NewMethod() { return 1..; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestRangeExpression_Both() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|1..2|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); static System.Range NewMethod() { return 1..2; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestAnnotatedNullableReturn() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { [|string? x = null; x?.ToString();|] return x; } }", @"#nullable enable class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; static string? NewMethod() { string? x = null; x?.ToString(); return x; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestAnnotatedNullableParameters1() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { string? a = null; string? b = null; [|string? x = a?.Contains(b).ToString();|] return x; } }", @"#nullable enable class C { public string? M() { string? a = null; string? b = null; string? x = {|Rename:NewMethod|}(a, b); return x; static string? NewMethod(string? a, string? b) { return a?.Contains(b).ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestAnnotatedNullableParameters2() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; [|string x = (a + b + c).ToString();|] return x; } }", @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; string x = {|Rename:NewMethod|}(a, b, c); return x; static string NewMethod(string? a, string? b, int c) { return (a + b + c).ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestAnnotatedNullableParameters3() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; return [|(a + b + c).ToString()|]; } }", @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; return {|Rename:NewMethod|}(a, b, c); static string NewMethod(string? a, string? b, int c) { return (a + b + c).ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestAnnotatedNullableParameters4() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { string? a = null; string? b = null; return [|a?.Contains(b).ToString()|]; } }", @"#nullable enable class C { public string? M() { string? a = null; string? b = null; return {|Rename:NewMethod|}(a, b); static string? NewMethod(string? a, string? b) { return a?.Contains(b).ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters1() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; return [|(a + b + a).ToString()|]; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; return {|Rename:NewMethod|}(a, b); static string NewMethod(string a, string b) { return (a + b + a).ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters2() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { string? a = string.Empty; string? b = string.Empty; return [|(a + b + a).ToString()|]; } }", @"#nullable enable class C { public string? M() { string? a = string.Empty; string? b = string.Empty; return {|Rename:NewMethod|}(a, b); static string NewMethod(string a, string b) { return (a + b + a).ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters3() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = null; string? b = null; return [|(a + b + a)?.ToString()|] ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = null; string? b = null; return {|Rename:NewMethod|}(a, b) ?? string.Empty; static string? NewMethod(string? a, string? b) { return (a + b + a)?.ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters_MultipleStates() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|string? c = a + b; a = string.Empty; c += a; a = null; b = null; b = ""test""; c = a?.ToString();|] return c ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string? c = {|Rename:NewMethod|}(ref a, ref b); return c ?? string.Empty; static string? NewMethod(ref string? a, ref string? b) { string? c = a + b; a = string.Empty; c += a; a = null; b = null; b = ""test""; c = a?.ToString(); return c; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters_MultipleStatesNonNullReturn() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = null; c = a + b;|] return c ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string? c = {|Rename:NewMethod|}(ref a, ref b); return c ?? string.Empty; static string NewMethod(ref string? a, ref string? b) { string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = null; c = a + b; return c; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters_MultipleStatesNullReturn() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = a?.ToString();|] return c ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string? c = {|Rename:NewMethod|}(ref a, ref b); return c ?? string.Empty; static string? NewMethod(ref string? a, ref string? b) { string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = a?.ToString(); return c; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters_RefNotNull() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|var c = a + b; a = string.Empty; c += a; b = ""test""; c = a + b +c;|] return c; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string c = {|Rename:NewMethod|}(ref a, ref b); return c; static string NewMethod(ref string a, ref string b) { var c = a + b; a = string.Empty; c += a; b = ""test""; c = a + b + c; return c; } } }", CodeActionIndex); // There's a case below where flow state correctly asseses that the variable // 'x' is non-null when returned. It's wasn't obvious when writing, but that's // due to the fact the line above it being executed as 'x.ToString()' would throw // an exception and the return statement would never be hit. The only way the return // statement gets executed is if the `x.ToString()` call succeeds, thus suggesting // that the value is indeed not null. [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowNullableReturn_NotNull1() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { [|string? x = null; x.ToString();|] return x; } }", @"#nullable enable class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; static string NewMethod() { string? x = null; x.ToString(); return x; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowNullableReturn_NotNull2() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { [|string? x = null; x?.ToString(); x = string.Empty;|] return x; } }", @"#nullable enable class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; static string NewMethod() { string? x = null; x?.ToString(); x = string.Empty; return x; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowNullable_Lambda() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { public string? M() { [|string? x = null; Action modifyXToNonNull = () => { x += x; }; modifyXToNonNull();|] return x; } }", @"#nullable enable using System; class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; static string? NewMethod() { string? x = null; Action modifyXToNonNull = () => { x += x; }; modifyXToNonNull(); return x; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowNullable_LambdaWithReturn() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { public string? M() { [|string? x = null; Func<string?> returnNull = () => { return null; }; x = returnNull() ?? string.Empty;|] return x; } }", @"#nullable enable using System; class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; static string NewMethod() { string? x = null; Func<string?> returnNull = () => { return null; }; x = returnNull() ?? string.Empty; return x; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestExtractReadOnlyMethod() { await TestInRegularAndScript1Async( @"struct S1 { readonly int M1() => 42; void Main() { [|int i = M1() + M1()|]; } }", @"struct S1 { readonly int M1() => 42; void Main() { {|Rename:NewMethod|}(); readonly void NewMethod() { int i = M1() + M1(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestExtractReadOnlyMethodInReadOnlyStruct() { await TestInRegularAndScript1Async( @"readonly struct S1 { int M1() => 42; void Main() { [|int i = M1() + M1()|]; } }", @"readonly struct S1 { int M1() => 42; void Main() { {|Rename:NewMethod|}(); void NewMethod() { int i = M1() + M1(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestExtractNonReadOnlyMethodInReadOnlyMethod() { await TestInRegularAndScript1Async( @"struct S1 { int M1() => 42; readonly void Main() { [|int i = M1() + M1()|]; } }", @"struct S1 { int M1() => 42; readonly void Main() { {|Rename:NewMethod|}(); void NewMethod() { int i = M1() + M1(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNullableObjectWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = null; var s = (string?)[|o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = null; var s = (string?){|Rename:GetO|}(o); Console.WriteLine(s); static object? GetO(object? o) { return o; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNotNullableObjectWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = new object(); var s = (string)[|o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = new object(); var s = (string){|Rename:GetO|}(o); Console.WriteLine(s); static object GetO(object o) { return o; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNotNullableWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = new B(); var s = (A)[|b|]; } }", @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = new B(); var s = (A){|Rename:GetB|}(b); static B GetB(B b) { return b; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNullableWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = null; var s = (A)[|b|]; } }", @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = null; var s = (A){|Rename:GetB|}(b); static B? GetB(B? b) { return b; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNotNullableWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = new object(); var s = [|(string)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = new object(); var s = {|Rename:GetS|}(o); Console.WriteLine(s); static string GetS(object o) { return (string)o; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNullableWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = null; var s = [|(string?)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = null; var s = {|Rename:GetS|}(o); Console.WriteLine(s); static string? GetS(object? o) { return (string?)o; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNullableNonNullFlowWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = new object(); var s = [|(string?)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = new object(); var s = {|Rename:GetS|}(o); Console.WriteLine(s); static string? GetS(object o) { return (string?)o; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNullableToNonNullableWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = null; var s = [|(string)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = null; var s = {|Rename:GetS|}(o); Console.WriteLine(s); static string? GetS(object? o) { return (string)o; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestExtractLocalFunction_EnsureUniqueFunctionName() { await TestInRegularAndScript1Async( @"class Test { static void Main(string[] args) { [|var test = 1;|] static void NewMethod() { var test = 1; } } }", @"class Test { static void Main(string[] args) { {|Rename:NewMethod1|}(); static void NewMethod() { var test = 1; } static void NewMethod1() { var test = 1; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestExtractLocalFunctionWithinLocalFunction_EnsureUniqueFunctionName() { await TestInRegularAndScript1Async( @"class Test { static void Main(string[] args) { static void NewMethod() { var NewMethod2 = 0; [|var test = 1;|] static void NewMethod1() { var test = 1; } } } }", @"class Test { static void Main(string[] args) { static void NewMethod() { var NewMethod2 = 0; {|Rename:NewMethod3|}(); static void NewMethod1() { var test = 1; } static void NewMethod3() { var test = 1; } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestExtractNonStaticLocalMethod_WithDeclaration() { await TestInRegularAndScript1Async( @"class Test { static void Main(string[] args) { [|ExistingLocalFunction(); void ExistingLocalFunction() { }|] } }", @"class Test { static void Main(string[] args) { {|Rename:NewMethod|}(); static void NewMethod() { ExistingLocalFunction(); void ExistingLocalFunction() { } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ArgumentlessReturnWithConstIfExpression() { await TestInRegularAndScript1Async( @"using System; class Program { void Test() { if (true) [|if (true) return;|] Console.WriteLine(); } }", @"using System; class Program { void Test() { if (true) { {|Rename:NewMethod|}(); return; } Console.WriteLine(); static void NewMethod() { if (true) return; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionTrue_EarlierCSharpVersionShouldBeNonStatic() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_3))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionTrue_EarlierCSharpVersionShouldBeNonStatic2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionTrue_CSharp8AndLaterStaticSupported() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionTrue_CSharp8AndLaterStaticSupported2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInPropertyInitializer_Get() { await TestInRegularAndScript1Async( @"using System; class TimePeriod { private double _seconds; public double Hours { get { [|return _seconds / 3600;|] } set { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); _seconds = value * 3600; } } }", @"using System; class TimePeriod { private double _seconds; public double Hours { get { return {|Rename:NewMethod|}(); double NewMethod() { return _seconds / 3600; } } set { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); _seconds = value * 3600; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInPropertyInitializer_Get2() { await TestInRegularAndScript1Async( @"using System; class TimePeriod { private double _seconds; public double Hours { get { return [|_seconds / 3600;|] } set { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); _seconds = value * 3600; } } }", @"using System; class TimePeriod { private double _seconds; public double Hours { get { return {|Rename:NewMethod|}(); double NewMethod() { return _seconds / 3600; } } set { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); _seconds = value * 3600; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInPropertyInitializer_Set() { await TestInRegularAndScript1Async( @"using System; class TimePeriod { private double _seconds; public double Hours { get { return _seconds / 3600; } set { [|if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test"");|] _seconds = value * 3600; } } }", @"using System; class TimePeriod { private double _seconds; public double Hours { get { return _seconds / 3600; } set { {|Rename:NewMethod|}(value); _seconds = value * 3600; static void NewMethod(double value) { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); } } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInPropertyInitializer_Set2() { await TestInRegularAndScript1Async( @"using System; class TimePeriod { private double _seconds; public double Hours { get { return _seconds / 3600; } set { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); [|_seconds = value * 3600;|] } } }", @"using System; class TimePeriod { private double _seconds; public double Hours { get { return _seconds / 3600; } set { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); {|Rename:NewMethod|}(value); void NewMethod(double value) { _seconds = value * 3600; } } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInIndexer_Get() { await TestInRegularAndScript1Async( @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { [|if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test"");|] return testArr[index]; } set { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); testArr[index] = value; } } }", @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { {|Rename:NewMethod|}(index); return testArr[index]; void NewMethod(int index) { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); } } set { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); testArr[index] = value; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInIndexer_Get2() { await TestInRegularAndScript1Async( @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); [|return testArr[index];|] } set { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); testArr[index] = value; } } }", @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); return {|Rename:NewMethod|}(index); string NewMethod(int index) { return testArr[index]; } } set { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); testArr[index] = value; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInIndexer_Set() { await TestInRegularAndScript1Async( @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); return testArr[index]; } set { [|if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test"");|] testArr[index] = value; } } }", @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); return testArr[index]; } set { {|Rename:NewMethod|}(index); testArr[index] = value; void NewMethod(int index) { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); } } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInIndexer_Set2() { await TestInRegularAndScript1Async( @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); return testArr[index]; } set { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); [|testArr[index] = value;|] } } }", @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); return testArr[index]; } set { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); {|Rename:NewMethod|}(index, value); void NewMethod(int index, string value) { testArr[index] = value; } } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_CSharp5NotApplicable() { var code = @" class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }, new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_CSharp6NotApplicable() { var code = @" class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }, new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInIntegerExpression() { await TestInRegularAndScript1Async( @"class MethodExtraction { void TestMethod() { int a = [|1 + 1|]; } }", @"class MethodExtraction { void TestMethod() { int a = {|Rename:GetA|}(); static int GetA() { return 1 + 1; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInBaseIntegerParameter() { await TestInRegularAndScript1Async( @"class B { protected B(int test) { } } class C : B { public C(int test) : base([|1 + 1|]) { } }", @"class B { protected B(int test) { } } class C : B { public C(int test) : base({|Rename:NewMethod|}()) { static int NewMethod() { return 1 + 1; } } }", CodeActionIndex); } [Fact, WorkItem(40188, "https://github.com/dotnet/roslyn/issues/40188"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestEditorconfigSetting_StaticLocalFunction_True() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool test = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_prefer_static_local_function = true:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); static void NewMethod() { bool test = true; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_prefer_static_local_function = true:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40188, "https://github.com/dotnet/roslyn/issues/40188"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestEditorconfigSetting_StaticLocalFunction_False() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool test = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_prefer_static_local_function = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); void NewMethod() { bool test = true; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_prefer_static_local_function = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40188, "https://github.com/dotnet/roslyn/issues/40188"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_True() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_local_functions = true:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); static bool NewMethod() => true; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_local_functions = true:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40188, "https://github.com/dotnet/roslyn/issues/40188"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_False() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_local_functions = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); static bool NewMethod() { return true; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_local_functions = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestNaming_CamelCase() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:newMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); static bool newMethod() { return true; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestNaming_CamelCase_GetName() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class MethodExtraction { void TestMethod() { int a = [|1 + 1|]; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class MethodExtraction { void TestMethod() { int a = {|Rename:getA|}(); static int getA() { return 1 + 1; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestNaming_PascalCase() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_PascalCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); static bool NewMethod() { return true; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_PascalCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestNaming_PascalCase_GetName() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class MethodExtraction { void TestMethod() { int a = [|1 + 1|]; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_PascalCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class MethodExtraction { void TestMethod() { int a = {|Rename:GetA|}(); static int GetA() { return 1 + 1; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_PascalCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestNaming_CamelCase_DoesntApply() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_CamelCase + @" dotnet_naming_symbols.local_functions.required_modifiers = static </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); bool NewMethod() { return true; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_CamelCase + @" dotnet_naming_symbols.local_functions.required_modifiers = static </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSilentEnforcement))); } [WorkItem(40654, "https://github.com/dotnet/roslyn/issues/40654")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnInvalidUsingStatement_MultipleStatements() { var input = @" class C { void M() { [|var v = 0; using System;|] } }"; var expected = @" class C { void M() { {|Rename:NewMethod|}(); static void NewMethod() { var v = 0; using System; } } }"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [WorkItem(40555, "https://github.com/dotnet/roslyn/issues/40555")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnLocalFunctionHeader_Parameter() { var input = @" using System; class C { void M(Action a) { M(() => { void F(int [|x|]) { } }); } }"; var expected = @" using System; class C { void M(Action a) { M({|Rename:NewMethod|}()); static Action NewMethod() { return () => { void F(int x) { } }; } } }"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [WorkItem(40555, "https://github.com/dotnet/roslyn/issues/40555")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnLocalFunctionHeader_Parameter_ExpressionBody() { var input = @" using System; class C { void M(Action a) { M(() => { int F(int [|x|]) => 1; }); } }"; var expected = @" using System; class C { void M(Action a) { M({|Rename:NewMethod|}()); static Action NewMethod() { return () => { int F(int x) => 1; }; } } }"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [WorkItem(40555, "https://github.com/dotnet/roslyn/issues/40555")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnLocalFunctionHeader_Identifier() { var input = @" using System; class C { void M(Action a) { M(() => { void [|F|](int x) { } }); } }"; var expected = @" using System; class C { void M(Action a) { M({|Rename:NewMethod|}()); static Action NewMethod() { return () => { void F(int x) { } }; } } }"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [WorkItem(40555, "https://github.com/dotnet/roslyn/issues/40555")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnLocalFunctionHeader_Identifier_ExpressionBody() { var input = @" using System; class C { void M(Action a) { M(() => { int [|F|](int x) => 1; }); } }"; var expected = @" using System; class C { void M(Action a) { M({|Rename:NewMethod|}()); static Action NewMethod() { return () => { int F(int x) => 1; }; } } }"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [WorkItem(40654, "https://github.com/dotnet/roslyn/issues/40654")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingOnUsingStatement() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { void L() { [|using System;|] } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInLocalFunctionDeclaration_ExpressionBody() { await TestMissingInRegularAndScriptAsync(@" class C { public static void Main(string[] args) { [|bool Local() => args == null;|] Local(); } }", new TestParameters(index: CodeActionIndex)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInLocalFunctionDeclaration() { await TestMissingInRegularAndScriptAsync(@" class C { public static void Main(string[] args) { [|bool Local() { return args == null; }|] Local(); } }", new TestParameters(index: CodeActionIndex)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInGoto() { await TestMissingInRegularAndScriptAsync( @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { [|goto label2; return x * x;|] }; label2: return; } }", new TestParameters(index: CodeActionIndex)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInFieldInitializer() { await TestMissingInRegularAndScriptAsync( @"class C { [|int a = 10;|] int b = 5; static void Main(string[] args) { } }", new TestParameters(index: CodeActionIndex)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInFieldInitializer_2() { await TestMissingInRegularAndScriptAsync( @"class C { int [|a = 10;|] int b = 5; static void Main(string[] args) { } }", new TestParameters(index: CodeActionIndex)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInExpressionBodyProperty() { var code = @" class Program { int field; public int Blah => [|this.field|]; }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInExpressionBodyIndexer() { var code = @" class Program { int field; public int this[int i] => [|this.field|]; }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInExpressionBodyPropertyGetAccessor() { var code = @" class Program { int field; public int Blah { get => [|this.field|]; set => field = value; } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInExpressionBodyPropertySetAccessor() { var code = @" class Program { int field; public int Blah { get => this.field; set => field = [|value|]; } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInExpressionBodyIndexerGetAccessor() { var code = @" class Program { int field; public int this[int i] { get => [|this.field|]; set => field = value; } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInExpressionBodyIndexerSetAccessor() { var code = @" class Program { int field; public int this[int i] { get => this.field; set => field = [|value|]; } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInAttributeInitializer() { await TestMissingInRegularAndScriptAsync(@" using System; class C { [|[Serializable]|] public class SampleClass { // Objects of this type can be serialized. } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInAttributeInitializerParameter() { await TestMissingInRegularAndScriptAsync(@" using System.Runtime.InteropServices; class C { [ComVisible([|true|])] public class SampleClass { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInThisConstructorCall() { await TestMissingInRegularAndScriptAsync(@" class B { protected B(string message) { } } class C : B { public C(string message) : [|this(""test"", ""test2"")|] { } public C(string message, string message2) : base(message) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInBaseConstructorCall() { await TestMissingInRegularAndScriptAsync(@" class B { protected B(string message) { } } class C : B { public C(string message) : this(""test"", ""test2"") { } public C(string message, string message2) : [|base(message)|] { } }"); } [WorkItem(22150, "https://github.com/dotnet/roslyn/issues/22150")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionToLocalFunction() { var code = @" class C { static void Main(string[] args) { void Local() { } [|Local();|] } static void Local() => System.Console.WriteLine(); }"; var expected = @" class C { static void Main(string[] args) { void Local() { } {|Rename:NewMethod|}(); void NewMethod() { Local(); } } static void Local() => System.Console.WriteLine(); }"; await TestInRegularAndScript1Async(code, expected); } [WorkItem(44260, "https://github.com/dotnet/roslyn/issues/44260")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TopLevelStatement_ArgumentInInvocation() { var code = @" System.Console.WriteLine([|""string""|]); "; var expected = @" System.Console.WriteLine({|Rename:NewMethod|}()); static string NewMethod() { return ""string""; }"; await TestAsync(code, expected, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9), index: 1); } [WorkItem(44260, "https://github.com/dotnet/roslyn/issues/44260")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TopLevelStatement_InBlock_ArgumentInInvocation() { var code = @" { System.Console.WriteLine([|""string""|]); } "; var expected = @" { System.Console.WriteLine({|Rename:NewMethod|}()); static string NewMethod() { return ""string""; } } "; await TestInRegularAndScriptAsync(code, expected, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9), index: 1); } [WorkItem(44260, "https://github.com/dotnet/roslyn/issues/44260")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TopLevelStatement_ArgumentInInvocation_InInteractive() { var code = @" System.Console.WriteLine([|""string""|]); "; var expected = @"{ System.Console.WriteLine({|Rename:NewMethod|}()); static string NewMethod() { return ""string""; } }"; await TestAsync(code, expected, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp9), index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingOnExtractLocalFunctionInNamespace() { await TestMissingInRegularAndScriptAsync(@" namespace C { private bool TestMethod() => [|false|]; }", codeActionIndex: 1); } [WorkItem(45422, "https://github.com/dotnet/roslyn/issues/45422")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingOnExtractLocalFunction() { await TestMissingInRegularAndScriptAsync(@" class C { static void M() { if (true) { static void L() { [| static void L2() { var x = 1; }|] } } } }", codeActionIndex: 1); } [WorkItem(45422, "https://github.com/dotnet/roslyn/issues/45422")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingOnExtractLocalFunctionWithExtraBrace() { await TestMissingInRegularAndScriptAsync(@" class C { static void M() { if (true) { static void L() { [|static void L2() { var x = 1; } }|] } } }", codeActionIndex: 1); } } }
// 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.CodeRefactorings.ExtractMethod; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ExtractMethod { public class ExtractLocalFunctionTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new ExtractMethodCodeRefactoringProvider(); private static int CodeActionIndexWhenExtractMethodMissing => 0; private static int CodeActionIndex => 1; private const string EditorConfigNaming_CamelCase = @"[*] # Naming rules dotnet_naming_rule.local_functions_should_be_camel_case.severity = suggestion dotnet_naming_rule.local_functions_should_be_camel_case.symbols = local_functions dotnet_naming_rule.local_functions_should_be_camel_case.style = camel_case # Symbol specifications dotnet_naming_symbols.local_functions.applicable_kinds = local_function dotnet_naming_symbols.local_functions.applicable_accessibilities = * # Naming styles dotnet_naming_style.camel_case.capitalization = camel_case"; private const string EditorConfigNaming_PascalCase = @"[*] # Naming rules dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions dotnet_naming_rule.local_functions_should_be_pascal_case.style = pascal_case # Symbol specifications dotnet_naming_symbols.local_functions.applicable_kinds = local_function dotnet_naming_symbols.local_functions.applicable_accessibilities = * dotnet_naming_symbols.local_functions.required_modifiers = # Naming styles dotnet_naming_style.pascal_case.capitalization = pascal_case"; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionTrue() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionFalse() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionDefault() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CSharpCodeStyleOptions.PreferStaticLocalFunction.DefaultValue))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseExpressionBodyWhenPossible() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) => b != true; } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) => b != true; } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine( [|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine( {|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) => b != true; } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b !=/* */true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) { return b !=/* */true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine3() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|"""" != @"" ""|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}() ? b = true : b = false); static bool NewMethod() { return """" != @"" ""; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestReadOfDataThatDoesNotFlowIn() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { int x = 1; object y = 0; [|int s = true ? fun(x) : fun(y);|] } private static T fun<T>(T t) { return t; } }", @"class Program { static void Main(string[] args) { int x = 1; object y = 0; {|Rename:NewMethod|}(x, y); static void NewMethod(int x, object y) { int s = true ? fun(x) : fun(y); } } private static T fun<T>(T t) { return t; } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnStatementAfterUnconditionalGoto() { await TestInRegularAndScript1Async( @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; [|return x * x;|] }; label2: return; } }", @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; return {|Rename:NewMethod|}(x); }; label2: return; static int NewMethod(int x) { return x * x; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnNamespace() { await TestInRegularAndScript1Async( @"class Program { void Main() { [|System|].Console.WriteLine(4); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); static void NewMethod() { System.Console.WriteLine(4); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnType() { await TestInRegularAndScript1Async( @"class Program { void Main() { [|System.Console|].WriteLine(4); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); static void NewMethod() { System.Console.WriteLine(4); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnBase() { await TestInRegularAndScript1Async( @"class Program { void Main() { [|base|].ToString(); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); void NewMethod() { base.ToString(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnActionInvocation() { await TestInRegularAndScript1Async( @"using System; class C { public static Action X { get; set; } } class Program { void Main() { [|C.X|](); } }", @"using System; class C { public static Action X { get; set; } } class Program { void Main() { {|Rename:GetX|}()(); static Action GetX() { return C.X; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task DisambiguateCallSiteIfNecessary1() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main() { byte z = 0; Goo([|x => 0|], y => 0, z, z); } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Goo({|Rename:NewMethod|}(), y => (byte)0, z, z); static Func<byte, byte> NewMethod() { return x => 0; } } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task DisambiguateCallSiteIfNecessary2() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main() { byte z = 0; Goo([|x => 0|], y => { return 0; }, z, z); } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Goo({|Rename:NewMethod|}(), y => { return (byte)0; }, z, z); static Func<byte, byte> NewMethod() { return x => 0; } } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task DontOverparenthesize() { await TestAsync( @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex(), y), - -1); } } static class E { public static void Ex(this int x) { } }", @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex(), y), (object)- -1); static string GetX(string x) { return x; } } } static class E { public static void Ex(this int x) { } }", parseOptions: Options.Regular, index: CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task DontOverparenthesizeGenerics() { await TestAsync( @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex<int>(), y), - -1); } } static class E { public static void Ex<T>(this int x) { } }", @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex<int>(), y), (object)- -1); static string GetX(string x) { return x; } } } static class E { public static void Ex<T>(this int x) { } }", parseOptions: Options.Regular, index: CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task PreserveCommentsBeforeDeclaration_1() { await TestInRegularAndScript1Async( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do();|] obj1.Do(); obj2.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2; {|Rename:NewMethod|}(out obj1, out obj2); obj1.Do(); obj2.Do(); static void NewMethod(out Construct obj1, out Construct obj2) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task PreserveCommentsBeforeDeclaration_2() { await TestInRegularAndScript1Async( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ Construct obj3 = new Construct(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ obj3 = new Construct(); obj3.Do(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task PreserveCommentsBeforeDeclaration_3() { await TestInRegularAndScript1Async( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(), obj3 = new Construct(); obj2.Do(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj3 = new Construct(); obj2.Do(); obj3.Do(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTuple() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int, int) x = (1, 2);|] System.Console.WriteLine(x.Item1); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); static (int, int) NewMethod() { return (1, 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleDeclarationWithNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int a, int b) x = (1, 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); static (int a, int b) NewMethod() { return (1, 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleDeclarationWithSomeNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int a, int) x = (1, 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); static (int a, int) NewMethod() { return (1, 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleWith1Arity() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { ValueTuple<int> y = ValueTuple.Create(1); [|y.Item1.ToString();|] } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"using System; class Program { static void Main(string[] args) { ValueTuple<int> y = ValueTuple.Create(1); {|Rename:NewMethod|}(y); static void NewMethod(ValueTuple<int> y) { y.Item1.ToString(); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleLiteralWithNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int, int) x = (a: 1, b: 2);|] System.Console.WriteLine(x.Item1); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); static (int, int) NewMethod() { return (a: 1, b: 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleDeclarationAndLiteralWithNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int a, int b) x = (c: 1, d: 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); static (int a, int b) NewMethod() { return (c: 1, d: 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleIntoVar() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|var x = (c: 1, d: 2);|] System.Console.WriteLine(x.c); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int c, int d) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); static (int c, int d) NewMethod() { return (c: 1, d: 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task RefactorWithoutSystemValueTuple() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|var x = (c: 1, d: 2);|] System.Console.WriteLine(x.c); } }", @"class Program { static void Main(string[] args) { (int c, int d) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); static (int c, int d) NewMethod() { return (c: 1, d: 2); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestTupleWithNestedNamedTuple() { // This is not the best refactoring, but this is an edge case await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|var x = new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world""));|] System.Console.WriteLine(x.c); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int, int, int, int, int, int, string, string) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); static (int, int, int, int, int, int, int, string, string) NewMethod() { return new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world"")); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestDeconstruction() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { var (x, y) = [|(1, 2)|]; System.Console.WriteLine(x); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { var (x, y) = {|Rename:NewMethod|}(); System.Console.WriteLine(x); static (int, int) NewMethod() { return (1, 2); } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction), CompilerTrait(CompilerFeature.Tuples)] public async Task TestDeconstruction2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { var (x, y) = (1, 2); var z = [|3;|] System.Console.WriteLine(z); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { var (x, y) = (1, 2); int z = {|Rename:NewMethod|}(); System.Console.WriteLine(z); static int NewMethod() { return 3; } } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] [CompilerTrait(CompilerFeature.OutVar)] public async Task TestOutVar() { await TestInRegularAndScript1Async( @"class C { static void M(int i) { int r; [|r = M1(out int y, i);|] System.Console.WriteLine(r + y); } }", @"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); static void NewMethod(int i, out int r, out int y) { r = M1(out y, i); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] [CompilerTrait(CompilerFeature.Patterns)] public async Task TestIsPattern() { await TestInRegularAndScript1Async( @"class C { static void M(int i) { int r; [|r = M1(3 is int y, i);|] System.Console.WriteLine(r + y); } }", @"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); static void NewMethod(int i, out int r, out int y) { r = M1(3 is int {|Conflict:y|}, i); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] [CompilerTrait(CompilerFeature.Patterns)] public async Task TestOutVarAndIsPattern() { await TestInRegularAndScript1Async( @"class C { static void M() { int r; [|r = M1(out /*out*/ int /*int*/ y /*y*/) + M2(3 is int z);|] System.Console.WriteLine(r + y + z); } } ", @"class C { static void M() { int r; int y, z; {|Rename:NewMethod|}(out r, out y, out z); System.Console.WriteLine(r + y + z); static void NewMethod(out int r, out int y, out int z) { r = M1(out /*out*/ /*int*/ y /*y*/) + M2(3 is int {|Conflict:z|}); } } } ", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] [CompilerTrait(CompilerFeature.Patterns)] public async Task ConflictingOutVarLocals() { await TestInRegularAndScript1Async( @"class C { static void M() { int r; [|r = M1(out int y); { M2(out int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } }", @"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); static void NewMethod(out int r, out int y) { r = M1(out y); { M2(out int y); System.Console.Write(y); } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] [CompilerTrait(CompilerFeature.Patterns)] public async Task ConflictingPatternLocals() { await TestInRegularAndScript1Async( @"class C { static void M() { int r; [|r = M1(1 is int y); { M2(2 is int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } }", @"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); static void NewMethod(out int r, out int y) { r = M1(1 is int {|Conflict:y|}); { M2(2 is int y); System.Console.Write(y); } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestCancellationTokenGoesLast() { await TestInRegularAndScript1Async( @"using System; using System.Threading; class C { void M(CancellationToken ct) { var v = 0; [|if (true) { ct.ThrowIfCancellationRequested(); Console.WriteLine(v); }|] } }", @"using System; using System.Threading; class C { void M(CancellationToken ct) { var v = 0; {|Rename:NewMethod|}(v, ct); static void NewMethod(int v, CancellationToken ct) { if (true) { ct.ThrowIfCancellationRequested(); Console.WriteLine(v); } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseVar1() { await TestInRegularAndScript1Async( @"using System; class C { void Goo(int i) { [|var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; }|] Console.WriteLine(v); } }", @"using System; class C { void Goo(int i) { var v = {|Rename:NewMethod|}(i); Console.WriteLine(v); static string NewMethod(int i) { var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; } return v; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSuggestionEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestUseVar2() { await TestInRegularAndScript1Async( @"using System; class C { void Goo(int i) { [|var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; }|] Console.WriteLine(v); } }", @"using System; class C { void Goo(int i) { string v = {|Rename:NewMethod|}(i); Console.WriteLine(v); static string NewMethod(int i) { var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; } return v; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSuggestionEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionCall() { var code = @" class C { public static void Main() { void Local() { } [|Local();|] } }"; var expectedCode = @" class C { public static void Main() { void Local() { } {|Rename:NewMethod|}(); void NewMethod() { Local(); } } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_local_function }); await TestInRegularAndScript1Async(code, expectedCode, CodeActionIndexWhenExtractMethodMissing); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionCall_2() { await TestInRegularAndScript1Async(@" class C { public static void Main() { [|void Local() { } Local();|] } }", @" class C { public static void Main() { {|Rename:NewMethod|}(); static void NewMethod() { void Local() { } Local(); } } }", CodeActionIndex); } [Fact, WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionCall_3() { await TestInRegularAndScript1Async(@" class C { public static void Main() { static void LocalParent() { [|void Local() { } Local();|] } } }", @" class C { public static void Main() { static void LocalParent() { {|Rename:NewMethod|}(); static void NewMethod() { void Local() { } Local(); } } } }", CodeActionIndex); } [Fact, WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractFunctionUnderLocalFunctionCall() { await TestInRegularAndScript1Async(@" class Test { int Testing; void ClassTest() { ExistingLocalFunction(); [|NewMethod();|] Testing = 5; void ExistingLocalFunction() { } } void NewMethod() { } }", @" class Test { int Testing; void ClassTest() { ExistingLocalFunction(); {|Rename:NewMethod1|}(); Testing = 5; void ExistingLocalFunction() { } void NewMethod1() { NewMethod(); } } void NewMethod() { } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionCallWithCapture() { var code = @" class C { public static void Main(string[] args) { bool Local() => args == null; [|Local();|] } }"; var expectedCode = @" class C { public static void Main(string[] args) { bool Local() => args == null; {|Rename:NewMethod|}(args); void NewMethod(string[] args) { Local(); } } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_local_function }); await TestInRegularAndScript1Async(code, expectedCode, CodeActionIndexWhenExtractMethodMissing); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionInterior() { await TestInRegularAndScript1Async(@" class C { public static void Main() { void Local() { [|int x = 0; x++;|] } Local(); } }", @" class C { public static void Main() { void Local() { {|Rename:NewMethod|}(); static void NewMethod() { int x = 0; x++; } } Local(); } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionWithinForLoop() { await TestInRegularAndScript1Async(@" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { [|v = v + i;|] } } } }", @" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { v = {|Rename:NewMethod|}(v, i); } static int NewMethod(int v, int i) { v = v + i; return v; } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionWithinForLoop2() { await TestInRegularAndScript1Async(@" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { [|v = v + i|]; } } } }", @" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { v = {|Rename:NewMethod|}(v, i); } static int NewMethod(int v, int i) { return v + i; } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionWithinForLoop3() { await TestInRegularAndScript1Async(@" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { [|i = v = v + i|]; } } } }", @" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { i = {|Rename:NewMethod|}(ref v, i); } static int NewMethod(ref int v, int i) { return v = v + i; } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestTupleWithInferredNames() { await TestAsync(@" class Program { void M() { int a = 1; var t = [|(a, b: 2)|]; System.Console.Write(t.a); } }", @" class Program { void M() { int a = 1; var t = {|Rename:GetT|}(); System.Console.Write(t.a); (int a, int b) GetT() { return (a, b: 2); } } }", TestOptions.Regular7_1, index: CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestDeconstruction4() { await TestAsync(@" class Program { void M() { [|var (x, y) = (1, 2);|] System.Console.Write(x + y); } }", @" class Program { void M() { int x, y; {|Rename:NewMethod|}(); System.Console.Write(x + y); void NewMethod() { var (x, y) = (1, 2); } } }", TestOptions.Regular7_1, index: CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestDeconstruction5() { await TestAsync(@" class Program { void M() { [|(var x, var y) = (1, 2);|] System.Console.Write(x + y); } }", @" class Program { void M() { int x, y; {|Rename:NewMethod|}(); System.Console.Write(x + y); void NewMethod() { (x, y) = (1, 2); } } }", TestOptions.Regular7_1, index: CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestIndexExpression() { await TestInRegularAndScript1Async(TestSources.Index + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|^1|]); } }", TestSources.Index + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); static System.Index NewMethod() { return ^1; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestRangeExpression_Empty() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|..|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); static System.Range NewMethod() { return ..; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestRangeExpression_Left() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|..1|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); static System.Range NewMethod() { return ..1; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestRangeExpression_Right() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|1..|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); static System.Range NewMethod() { return 1..; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestRangeExpression_Both() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|1..2|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); static System.Range NewMethod() { return 1..2; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestAnnotatedNullableReturn() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { [|string? x = null; x?.ToString();|] return x; } }", @"#nullable enable class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; static string? NewMethod() { string? x = null; x?.ToString(); return x; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestAnnotatedNullableParameters1() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { string? a = null; string? b = null; [|string? x = a?.Contains(b).ToString();|] return x; } }", @"#nullable enable class C { public string? M() { string? a = null; string? b = null; string? x = {|Rename:NewMethod|}(a, b); return x; static string? NewMethod(string? a, string? b) { return a?.Contains(b).ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestAnnotatedNullableParameters2() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; [|string x = (a + b + c).ToString();|] return x; } }", @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; string x = {|Rename:NewMethod|}(a, b, c); return x; static string NewMethod(string? a, string? b, int c) { return (a + b + c).ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestAnnotatedNullableParameters3() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; return [|(a + b + c).ToString()|]; } }", @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; return {|Rename:NewMethod|}(a, b, c); static string NewMethod(string? a, string? b, int c) { return (a + b + c).ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestAnnotatedNullableParameters4() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { string? a = null; string? b = null; return [|a?.Contains(b).ToString()|]; } }", @"#nullable enable class C { public string? M() { string? a = null; string? b = null; return {|Rename:NewMethod|}(a, b); static string? NewMethod(string? a, string? b) { return a?.Contains(b).ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters1() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; return [|(a + b + a).ToString()|]; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; return {|Rename:NewMethod|}(a, b); static string NewMethod(string a, string b) { return (a + b + a).ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters2() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { string? a = string.Empty; string? b = string.Empty; return [|(a + b + a).ToString()|]; } }", @"#nullable enable class C { public string? M() { string? a = string.Empty; string? b = string.Empty; return {|Rename:NewMethod|}(a, b); static string NewMethod(string a, string b) { return (a + b + a).ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters3() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = null; string? b = null; return [|(a + b + a)?.ToString()|] ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = null; string? b = null; return {|Rename:NewMethod|}(a, b) ?? string.Empty; static string? NewMethod(string? a, string? b) { return (a + b + a)?.ToString(); } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters_MultipleStates() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|string? c = a + b; a = string.Empty; c += a; a = null; b = null; b = ""test""; c = a?.ToString();|] return c ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string? c = {|Rename:NewMethod|}(ref a, ref b); return c ?? string.Empty; static string? NewMethod(ref string? a, ref string? b) { string? c = a + b; a = string.Empty; c += a; a = null; b = null; b = ""test""; c = a?.ToString(); return c; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters_MultipleStatesNonNullReturn() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = null; c = a + b;|] return c ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string? c = {|Rename:NewMethod|}(ref a, ref b); return c ?? string.Empty; static string NewMethod(ref string? a, ref string? b) { string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = null; c = a + b; return c; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters_MultipleStatesNullReturn() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = a?.ToString();|] return c ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string? c = {|Rename:NewMethod|}(ref a, ref b); return c ?? string.Empty; static string? NewMethod(ref string? a, ref string? b) { string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = a?.ToString(); return c; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowStateNullableParameters_RefNotNull() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|var c = a + b; a = string.Empty; c += a; b = ""test""; c = a + b +c;|] return c; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string c = {|Rename:NewMethod|}(ref a, ref b); return c; static string NewMethod(ref string a, ref string b) { var c = a + b; a = string.Empty; c += a; b = ""test""; c = a + b + c; return c; } } }", CodeActionIndex); // There's a case below where flow state correctly asseses that the variable // 'x' is non-null when returned. It's wasn't obvious when writing, but that's // due to the fact the line above it being executed as 'x.ToString()' would throw // an exception and the return statement would never be hit. The only way the return // statement gets executed is if the `x.ToString()` call succeeds, thus suggesting // that the value is indeed not null. [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowNullableReturn_NotNull1() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { [|string? x = null; x.ToString();|] return x; } }", @"#nullable enable class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; static string NewMethod() { string? x = null; x.ToString(); return x; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowNullableReturn_NotNull2() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { [|string? x = null; x?.ToString(); x = string.Empty;|] return x; } }", @"#nullable enable class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; static string NewMethod() { string? x = null; x?.ToString(); x = string.Empty; return x; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowNullable_Lambda() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { public string? M() { [|string? x = null; Action modifyXToNonNull = () => { x += x; }; modifyXToNonNull();|] return x; } }", @"#nullable enable using System; class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; static string? NewMethod() { string? x = null; Action modifyXToNonNull = () => { x += x; }; modifyXToNonNull(); return x; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestFlowNullable_LambdaWithReturn() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { public string? M() { [|string? x = null; Func<string?> returnNull = () => { return null; }; x = returnNull() ?? string.Empty;|] return x; } }", @"#nullable enable using System; class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; static string NewMethod() { string? x = null; Func<string?> returnNull = () => { return null; }; x = returnNull() ?? string.Empty; return x; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestExtractReadOnlyMethod() { await TestInRegularAndScript1Async( @"struct S1 { readonly int M1() => 42; void Main() { [|int i = M1() + M1()|]; } }", @"struct S1 { readonly int M1() => 42; void Main() { {|Rename:NewMethod|}(); readonly void NewMethod() { int i = M1() + M1(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestExtractReadOnlyMethodInReadOnlyStruct() { await TestInRegularAndScript1Async( @"readonly struct S1 { int M1() => 42; void Main() { [|int i = M1() + M1()|]; } }", @"readonly struct S1 { int M1() => 42; void Main() { {|Rename:NewMethod|}(); void NewMethod() { int i = M1() + M1(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestExtractNonReadOnlyMethodInReadOnlyMethod() { await TestInRegularAndScript1Async( @"struct S1 { int M1() => 42; readonly void Main() { [|int i = M1() + M1()|]; } }", @"struct S1 { int M1() => 42; readonly void Main() { {|Rename:NewMethod|}(); void NewMethod() { int i = M1() + M1(); } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNullableObjectWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = null; var s = (string?)[|o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = null; var s = (string?){|Rename:GetO|}(o); Console.WriteLine(s); static object? GetO(object? o) { return o; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNotNullableObjectWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = new object(); var s = (string)[|o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = new object(); var s = (string){|Rename:GetO|}(o); Console.WriteLine(s); static object GetO(object o) { return o; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNotNullableWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = new B(); var s = (A)[|b|]; } }", @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = new B(); var s = (A){|Rename:GetB|}(b); static B GetB(B b) { return b; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNullableWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = null; var s = (A)[|b|]; } }", @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = null; var s = (A){|Rename:GetB|}(b); static B? GetB(B? b) { return b; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNotNullableWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = new object(); var s = [|(string)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = new object(); var s = {|Rename:GetS|}(o); Console.WriteLine(s); static string GetS(object o) { return (string)o; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNullableWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = null; var s = [|(string?)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = null; var s = {|Rename:GetS|}(o); Console.WriteLine(s); static string? GetS(object? o) { return (string?)o; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNullableNonNullFlowWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = new object(); var s = [|(string?)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = new object(); var s = {|Rename:GetS|}(o); Console.WriteLine(s); static string? GetS(object o) { return (string?)o; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public Task TestExtractNullableToNonNullableWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = null; var s = [|(string)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = null; var s = {|Rename:GetS|}(o); Console.WriteLine(s); static string? GetS(object? o) { return (string)o; } } }", CodeActionIndex); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestExtractLocalFunction_EnsureUniqueFunctionName() { await TestInRegularAndScript1Async( @"class Test { static void Main(string[] args) { [|var test = 1;|] static void NewMethod() { var test = 1; } } }", @"class Test { static void Main(string[] args) { {|Rename:NewMethod1|}(); static void NewMethod() { var test = 1; } static void NewMethod1() { var test = 1; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestExtractLocalFunctionWithinLocalFunction_EnsureUniqueFunctionName() { await TestInRegularAndScript1Async( @"class Test { static void Main(string[] args) { static void NewMethod() { var NewMethod2 = 0; [|var test = 1;|] static void NewMethod1() { var test = 1; } } } }", @"class Test { static void Main(string[] args) { static void NewMethod() { var NewMethod2 = 0; {|Rename:NewMethod3|}(); static void NewMethod1() { var test = 1; } static void NewMethod3() { var test = 1; } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestExtractNonStaticLocalMethod_WithDeclaration() { await TestInRegularAndScript1Async( @"class Test { static void Main(string[] args) { [|ExistingLocalFunction(); void ExistingLocalFunction() { }|] } }", @"class Test { static void Main(string[] args) { {|Rename:NewMethod|}(); static void NewMethod() { ExistingLocalFunction(); void ExistingLocalFunction() { } } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ArgumentlessReturnWithConstIfExpression() { await TestInRegularAndScript1Async( @"using System; class Program { void Test() { if (true) [|if (true) return;|] Console.WriteLine(); } }", @"using System; class Program { void Test() { if (true) { {|Rename:NewMethod|}(); return; } Console.WriteLine(); static void NewMethod() { if (true) return; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionTrue_EarlierCSharpVersionShouldBeNonStatic() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}() ? b = true : b = false); bool NewMethod() { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_3))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionTrue_EarlierCSharpVersionShouldBeNonStatic2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}() ? b = true : b = false); bool NewMethod() { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionTrue_CSharp8AndLaterStaticSupported() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_StaticOptionTrue_CSharp8AndLaterStaticSupported2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); static bool NewMethod(bool b) { return b != true; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInPropertyInitializer_Get() { await TestInRegularAndScript1Async( @"using System; class TimePeriod { private double _seconds; public double Hours { get { [|return _seconds / 3600;|] } set { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); _seconds = value * 3600; } } }", @"using System; class TimePeriod { private double _seconds; public double Hours { get { return {|Rename:NewMethod|}(); double NewMethod() { return _seconds / 3600; } } set { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); _seconds = value * 3600; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInPropertyInitializer_Get2() { await TestInRegularAndScript1Async( @"using System; class TimePeriod { private double _seconds; public double Hours { get { return [|_seconds / 3600;|] } set { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); _seconds = value * 3600; } } }", @"using System; class TimePeriod { private double _seconds; public double Hours { get { return {|Rename:NewMethod|}(); double NewMethod() { return _seconds / 3600; } } set { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); _seconds = value * 3600; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInPropertyInitializer_Set() { await TestInRegularAndScript1Async( @"using System; class TimePeriod { private double _seconds; public double Hours { get { return _seconds / 3600; } set { [|if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test"");|] _seconds = value * 3600; } } }", @"using System; class TimePeriod { private double _seconds; public double Hours { get { return _seconds / 3600; } set { {|Rename:NewMethod|}(value); _seconds = value * 3600; static void NewMethod(double value) { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); } } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInPropertyInitializer_Set2() { await TestInRegularAndScript1Async( @"using System; class TimePeriod { private double _seconds; public double Hours { get { return _seconds / 3600; } set { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); [|_seconds = value * 3600;|] } } }", @"using System; class TimePeriod { private double _seconds; public double Hours { get { return _seconds / 3600; } set { if (value < 0 || value > 24) throw new ArgumentOutOfRangeException(""test""); {|Rename:NewMethod|}(value); void NewMethod(double value) { _seconds = value * 3600; } } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInIndexer_Get() { await TestInRegularAndScript1Async( @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { [|if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test"");|] return testArr[index]; } set { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); testArr[index] = value; } } }", @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { {|Rename:NewMethod|}(index); return testArr[index]; void NewMethod(int index) { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); } } set { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); testArr[index] = value; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInIndexer_Get2() { await TestInRegularAndScript1Async( @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); [|return testArr[index];|] } set { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); testArr[index] = value; } } }", @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); return {|Rename:NewMethod|}(index); string NewMethod(int index) { return testArr[index]; } } set { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); testArr[index] = value; } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInIndexer_Set() { await TestInRegularAndScript1Async( @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); return testArr[index]; } set { [|if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test"");|] testArr[index] = value; } } }", @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); return testArr[index]; } set { {|Rename:NewMethod|}(index); testArr[index] = value; void NewMethod(int index) { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); } } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInIndexer_Set2() { await TestInRegularAndScript1Async( @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); return testArr[index]; } set { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); [|testArr[index] = value;|] } } }", @"using System; class Indexer { private readonly string[] testArr = new string[1]; public string this[int index] { get { if (index < 0 && index >= testArr.Length) throw new IndexOutOfRangeException(""test""); return testArr[index]; } set { if (index < 0 || index >= testArr.Length) throw new IndexOutOfRangeException(""test""); {|Rename:NewMethod|}(index, value); void NewMethod(int index, string value) { testArr[index] = value; } } } }", CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_CSharp5NotApplicable() { var code = @" class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }, new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestPartialSelection_CSharp6NotApplicable() { var code = @" class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }, new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInIntegerExpression() { await TestInRegularAndScript1Async( @"class MethodExtraction { void TestMethod() { int a = [|1 + 1|]; } }", @"class MethodExtraction { void TestMethod() { int a = {|Rename:GetA|}(); static int GetA() { return 1 + 1; } } }", CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestInBaseIntegerParameter() { await TestInRegularAndScript1Async( @"class B { protected B(int test) { } } class C : B { public C(int test) : base([|1 + 1|]) { } }", @"class B { protected B(int test) { } } class C : B { public C(int test) : base({|Rename:NewMethod|}()) { static int NewMethod() { return 1 + 1; } } }", CodeActionIndex); } [Fact, WorkItem(40188, "https://github.com/dotnet/roslyn/issues/40188"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestEditorconfigSetting_StaticLocalFunction_True() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool test = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_prefer_static_local_function = true:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); static void NewMethod() { bool test = true; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_prefer_static_local_function = true:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40188, "https://github.com/dotnet/roslyn/issues/40188"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestEditorconfigSetting_StaticLocalFunction_False() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool test = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_prefer_static_local_function = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); void NewMethod() { bool test = true; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_prefer_static_local_function = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40188, "https://github.com/dotnet/roslyn/issues/40188"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_True() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_local_functions = true:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); static bool NewMethod() => true; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_local_functions = true:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40188, "https://github.com/dotnet/roslyn/issues/40188"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_False() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_local_functions = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); static bool NewMethod() { return true; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_local_functions = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestNaming_CamelCase() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:newMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); static bool newMethod() { return true; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestNaming_CamelCase_GetName() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class MethodExtraction { void TestMethod() { int a = [|1 + 1|]; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class MethodExtraction { void TestMethod() { int a = {|Rename:getA|}(); static int getA() { return 1 + 1; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestNaming_PascalCase() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_PascalCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); static bool NewMethod() { return true; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_PascalCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestNaming_PascalCase_GetName() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class MethodExtraction { void TestMethod() { int a = [|1 + 1|]; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_PascalCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class MethodExtraction { void TestMethod() { int a = {|Rename:GetA|}(); static int GetA() { return 1 + 1; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_PascalCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestNaming_CamelCase_DoesntApply() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_CamelCase + @" dotnet_naming_symbols.local_functions.required_modifiers = static </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); bool NewMethod() { return true; } } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_CamelCase + @" dotnet_naming_symbols.local_functions.required_modifiers = static </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSilentEnforcement))); } [WorkItem(40654, "https://github.com/dotnet/roslyn/issues/40654")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnInvalidUsingStatement_MultipleStatements() { var input = @" class C { void M() { [|var v = 0; using System;|] } }"; var expected = @" class C { void M() { {|Rename:NewMethod|}(); static void NewMethod() { var v = 0; using System; } } }"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [WorkItem(40555, "https://github.com/dotnet/roslyn/issues/40555")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnLocalFunctionHeader_Parameter() { var input = @" using System; class C { void M(Action a) { M(() => { void F(int [|x|]) { } }); } }"; var expected = @" using System; class C { void M(Action a) { M({|Rename:NewMethod|}()); static Action NewMethod() { return () => { void F(int x) { } }; } } }"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [WorkItem(40555, "https://github.com/dotnet/roslyn/issues/40555")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnLocalFunctionHeader_Parameter_ExpressionBody() { var input = @" using System; class C { void M(Action a) { M(() => { int F(int [|x|]) => 1; }); } }"; var expected = @" using System; class C { void M(Action a) { M({|Rename:NewMethod|}()); static Action NewMethod() { return () => { int F(int x) => 1; }; } } }"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [WorkItem(40555, "https://github.com/dotnet/roslyn/issues/40555")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnLocalFunctionHeader_Identifier() { var input = @" using System; class C { void M(Action a) { M(() => { void [|F|](int x) { } }); } }"; var expected = @" using System; class C { void M(Action a) { M({|Rename:NewMethod|}()); static Action NewMethod() { return () => { void F(int x) { } }; } } }"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [WorkItem(40555, "https://github.com/dotnet/roslyn/issues/40555")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestOnLocalFunctionHeader_Identifier_ExpressionBody() { var input = @" using System; class C { void M(Action a) { M(() => { int [|F|](int x) => 1; }); } }"; var expected = @" using System; class C { void M(Action a) { M({|Rename:NewMethod|}()); static Action NewMethod() { return () => { int F(int x) => 1; }; } } }"; await TestInRegularAndScript1Async(input, expected, CodeActionIndex); } [WorkItem(40654, "https://github.com/dotnet/roslyn/issues/40654")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingOnUsingStatement() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { void L() { [|using System;|] } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInLocalFunctionDeclaration_ExpressionBody() { await TestMissingInRegularAndScriptAsync(@" class C { public static void Main(string[] args) { [|bool Local() => args == null;|] Local(); } }", new TestParameters(index: CodeActionIndex)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInLocalFunctionDeclaration() { await TestMissingInRegularAndScriptAsync(@" class C { public static void Main(string[] args) { [|bool Local() { return args == null; }|] Local(); } }", new TestParameters(index: CodeActionIndex)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInGoto() { await TestMissingInRegularAndScriptAsync( @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { [|goto label2; return x * x;|] }; label2: return; } }", new TestParameters(index: CodeActionIndex)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInFieldInitializer() { await TestMissingInRegularAndScriptAsync( @"class C { [|int a = 10;|] int b = 5; static void Main(string[] args) { } }", new TestParameters(index: CodeActionIndex)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInFieldInitializer_2() { await TestMissingInRegularAndScriptAsync( @"class C { int [|a = 10;|] int b = 5; static void Main(string[] args) { } }", new TestParameters(index: CodeActionIndex)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInExpressionBodyProperty() { var code = @" class Program { int field; public int Blah => [|this.field|]; }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInExpressionBodyIndexer() { var code = @" class Program { int field; public int this[int i] => [|this.field|]; }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInExpressionBodyPropertyGetAccessor() { var code = @" class Program { int field; public int Blah { get => [|this.field|]; set => field = value; } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInExpressionBodyPropertySetAccessor() { var code = @" class Program { int field; public int Blah { get => this.field; set => field = [|value|]; } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInExpressionBodyIndexerGetAccessor() { var code = @" class Program { int field; public int this[int i] { get => [|this.field|]; set => field = value; } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInExpressionBodyIndexerSetAccessor() { var code = @" class Program { int field; public int this[int i] { get => this.field; set => field = [|value|]; } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_method }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInAttributeInitializer() { await TestMissingInRegularAndScriptAsync(@" using System; class C { [|[Serializable]|] public class SampleClass { // Objects of this type can be serialized. } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInAttributeInitializerParameter() { await TestMissingInRegularAndScriptAsync(@" using System.Runtime.InteropServices; class C { [ComVisible([|true|])] public class SampleClass { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInThisConstructorCall() { await TestMissingInRegularAndScriptAsync(@" class B { protected B(string message) { } } class C : B { public C(string message) : [|this(""test"", ""test2"")|] { } public C(string message, string message2) : base(message) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingInBaseConstructorCall() { await TestMissingInRegularAndScriptAsync(@" class B { protected B(string message) { } } class C : B { public C(string message) : this(""test"", ""test2"") { } public C(string message, string message2) : [|base(message)|] { } }"); } [WorkItem(22150, "https://github.com/dotnet/roslyn/issues/22150")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task ExtractLocalFunctionToLocalFunction() { var code = @" class C { static void Main(string[] args) { void Local() { } [|Local();|] } static void Local() => System.Console.WriteLine(); }"; var expected = @" class C { static void Main(string[] args) { void Local() { } {|Rename:NewMethod|}(); void NewMethod() { Local(); } } static void Local() => System.Console.WriteLine(); }"; await TestInRegularAndScript1Async(code, expected); } [WorkItem(44260, "https://github.com/dotnet/roslyn/issues/44260")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TopLevelStatement_ArgumentInInvocation() { var code = @" System.Console.WriteLine([|""string""|]); "; var expected = @" System.Console.WriteLine({|Rename:NewMethod|}()); static string NewMethod() { return ""string""; }"; await TestAsync(code, expected, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9), index: 1); } [WorkItem(44260, "https://github.com/dotnet/roslyn/issues/44260")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TopLevelStatement_InBlock_ArgumentInInvocation() { var code = @" { System.Console.WriteLine([|""string""|]); } "; var expected = @" { System.Console.WriteLine({|Rename:NewMethod|}()); static string NewMethod() { return ""string""; } } "; await TestInRegularAndScriptAsync(code, expected, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp9), index: 1); } [WorkItem(44260, "https://github.com/dotnet/roslyn/issues/44260")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TopLevelStatement_ArgumentInInvocation_InInteractive() { var code = @" System.Console.WriteLine([|""string""|]); "; var expected = @"{ System.Console.WriteLine({|Rename:NewMethod|}()); static string NewMethod() { return ""string""; } }"; await TestAsync(code, expected, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp9), index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingOnExtractLocalFunctionInNamespace() { await TestMissingInRegularAndScriptAsync(@" namespace C { private bool TestMethod() => [|false|]; }", codeActionIndex: 1); } [WorkItem(45422, "https://github.com/dotnet/roslyn/issues/45422")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingOnExtractLocalFunction() { await TestMissingInRegularAndScriptAsync(@" class C { static void M() { if (true) { static void L() { [| static void L2() { var x = 1; }|] } } } }", codeActionIndex: 1); } [WorkItem(45422, "https://github.com/dotnet/roslyn/issues/45422")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] public async Task TestMissingOnExtractLocalFunctionWithExtraBrace() { await TestMissingInRegularAndScriptAsync(@" class C { static void M() { if (true) { static void L() { [|static void L2() { var x = 1; } }|] } } }", codeActionIndex: 1); } [WorkItem(55031, "https://github.com/dotnet/roslyn/issues/55031")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractLocalConst_CSharp7() { var code = @" using NUnit.Framework; public class Tests { public string SomeOtherMethod(int k) { return ""; } int j = 2; [Test] public void Test1() { const string NAME = ""SOMETEXT""; [|Assert.AreEqual(string.Format(NAME, 0, 0), SomeOtherMethod(j));|] } }"; var expected = @" using NUnit.Framework; public class Tests { public string SomeOtherMethod(int k) { return ""; } int j = 2; [Test] public void Test1() { const string NAME = ""SOMETEXT""; {|Rename:NewMethod|}(); void NewMethod() { Assert.AreEqual(string.Format(NAME, 0, 0), SomeOtherMethod(j)); } } }"; await TestAsync(code, expected, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp7), index: CodeActionIndex); } [WorkItem(55031, "https://github.com/dotnet/roslyn/issues/55031")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractParameter_CSharp7() { var code = @" using NUnit.Framework; public class Tests { public string SomeOtherMethod(int k) { return ""; } int j = 2; [Test] public void Test1(string NAME) { [|Assert.AreEqual(string.Format(NAME, 0, 0), SomeOtherMethod(j));|] } }"; var expected = @" using NUnit.Framework; public class Tests { public string SomeOtherMethod(int k) { return ""; } int j = 2; [Test] public void Test1(string NAME) { {|Rename:NewMethod|}(); void NewMethod() { Assert.AreEqual(string.Format(NAME, 0, 0), SomeOtherMethod(j)); } } }"; await TestAsync(code, expected, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp7), index: CodeActionIndex); } [WorkItem(55031, "https://github.com/dotnet/roslyn/issues/55031")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractLocal_CSharp7() { var code = @" using NUnit.Framework; public class Tests { public string SomeOtherMethod(int k) { return ""; } int j = 2; [Test] public void Test1() { var NAME = ""SOMETEXT""; [|Assert.AreEqual(string.Format(NAME, 0, 0), SomeOtherMethod(j));|] } }"; var expected = @" using NUnit.Framework; public class Tests { public string SomeOtherMethod(int k) { return ""; } int j = 2; [Test] public void Test1() { var NAME = ""SOMETEXT""; {|Rename:NewMethod|}(); void NewMethod() { Assert.AreEqual(string.Format(NAME, 0, 0), SomeOtherMethod(j)); } } }"; await TestAsync(code, expected, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp7), index: CodeActionIndex); } [WorkItem(55031, "https://github.com/dotnet/roslyn/issues/55031")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractRangeVariable_CSharp7() { var code = @" using System.Linq; public class Class { public void M() { _ = from a in new object[0] select [|a.ToString()|]; } }"; var expected = @" using System.Linq; public class Class { public void M() { _ = from a in new object[0] select {|Rename:NewMethod|}(a); string NewMethod(object a) { return a.ToString(); } } }"; await TestAsync(code, expected, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp7), index: CodeActionIndex); } } }
1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/EditorFeatures/CSharpTest/CodeActions/ExtractMethod/ExtractMethodTests.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.CodeRefactorings.ExtractMethod; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ExtractMethod { public class ExtractMethodTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new ExtractMethodCodeRefactoringProvider(); private const string EditorConfigNaming_LocalFunctions_CamelCase = @"[*] # Naming rules dotnet_naming_rule.local_functions_should_be_camel_case.severity = suggestion dotnet_naming_rule.local_functions_should_be_camel_case.symbols = local_functions dotnet_naming_rule.local_functions_should_be_camel_case.style = camel_case # Symbol specifications dotnet_naming_symbols.local_functions.applicable_kinds = local_function dotnet_naming_symbols.local_functions.applicable_accessibilities = * dotnet_naming_symbols.local_functions.required_modifiers = # Naming styles dotnet_naming_style.camel_case.capitalization = camel_case"; [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public async Task LocalFuncExtract() { await TestInRegularAndScript1Async(@" class C { int Testing; void M() { local(); [|NewMethod();|] Testing = 5; void local() { } } void NewMethod() { } }", @" class C { int Testing; void M() { local(); {|Rename:NewMethod1|}(); Testing = 5; void local() { } } private void NewMethod1() { NewMethod(); } void NewMethod() { } }"); } [WorkItem(540799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestPartialSelection() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) { return b != true; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestSelectionOfSwitchExpressionArm() { await TestInRegularAndScript1Async( @"class Program { int Foo(int x) => x switch { 1 => 1, _ => [|1 + x|] }; }", @"class Program { int Foo(int x) => x switch { 1 => 1, _ => {|Rename:NewMethod|}(x) }; private static int NewMethod(int x) => 1 + x; }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestSelectionOfSwitchExpressionArmContainingVariables() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class TestClass { public static T RecursiveExample<T>(IEnumerable<T> sequence) => sequence switch { Array { Length: 0 } => default(T), Array { Length: 1 } array => [|(T)array.GetValue(0)|], Array { Length: 2 } array => (T)array.GetValue(1), Array array => (T)array.GetValue(2), _ => throw new NotImplementedException(), }; }", @"using System; using System.Collections.Generic; class TestClass { public static T RecursiveExample<T>(IEnumerable<T> sequence) => sequence switch { Array { Length: 0 } => default(T), Array { Length: 1 } array => {|Rename:NewMethod|}<T>(array), Array { Length: 2 } array => (T)array.GetValue(1), Array array => (T)array.GetValue(2), _ => throw new NotImplementedException(), }; private static T NewMethod<T>(Array array) => (T)array.GetValue(0); }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseExpressionBodyWhenPossible() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) => b != true; }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) => b != true; }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine( [|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine( {|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) => b != true; }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) { return b != true; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b !=/* */true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) { return b !=/* */true; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine3() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|"""" != @"" ""|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}() ? b = true : b = false); } private static bool NewMethod() { return """" != @"" ""; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [WorkItem(540796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540796")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestReadOfDataThatDoesNotFlowIn() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { int x = 1; object y = 0; [|int s = true ? fun(x) : fun(y);|] } private static T fun<T>(T t) { return t; } }", @"class Program { static void Main(string[] args) { int x = 1; object y = 0; {|Rename:NewMethod|}(x, y); } private static void NewMethod(int x, object y) { int s = true ? fun(x) : fun(y); } private static T fun<T>(T t) { return t; } }"); } [WorkItem(540819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnGoto() { await TestMissingInRegularAndScriptAsync( @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { [|goto label2; return x * x;|] }; label2: return; } }"); } [WorkItem(540819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOnStatementAfterUnconditionalGoto() { await TestInRegularAndScript1Async( @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; [|return x * x;|] }; label2: return; } }", @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; return {|Rename:NewMethod|}(x); }; label2: return; } private static int NewMethod(int x) { return x * x; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnNamespace() { await TestInRegularAndScript1Async( @"class Program { void Main() { [|System|].Console.WriteLine(4); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); } private static void NewMethod() { System.Console.WriteLine(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnType() { await TestInRegularAndScript1Async( @"class Program { void Main() { [|System.Console|].WriteLine(4); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); } private static void NewMethod() { System.Console.WriteLine(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnBase() { await TestInRegularAndScript1Async( @"class Program { void Main() { [|base|].ToString(); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); } private void NewMethod() { base.ToString(); } }"); } [WorkItem(545623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545623")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOnActionInvocation() { await TestInRegularAndScript1Async( @"using System; class C { public static Action X { get; set; } } class Program { void Main() { [|C.X|](); } }", @"using System; class C { public static Action X { get; set; } } class Program { void Main() { {|Rename:GetX|}()(); } private static Action GetX() { return C.X; } }"); } [WorkItem(529841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem(714632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DisambiguateCallSiteIfNecessary1() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main() { byte z = 0; Goo([|x => 0|], y => 0, z, z); } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Goo({|Rename:NewMethod|}(), y => (byte)0, z, z); } private static Func<byte, byte> NewMethod() { return x => 0; } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }"); } [WorkItem(529841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem(714632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DisambiguateCallSiteIfNecessary2() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main() { byte z = 0; Goo([|x => 0|], y => { return 0; }, z, z); } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Goo({|Rename:NewMethod|}(), y => { return (byte)0; }, z, z); } private static Func<byte, byte> NewMethod() { return x => 0; } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }"); } [WorkItem(530709, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530709")] [WorkItem(632182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DontOverparenthesize() { await TestAsync( @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex(), y), - -1); } } static class E { public static void Ex(this int x) { } }", @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex(), y), (object)- -1); } private static string GetX(string x) { return x; } } static class E { public static void Ex(this int x) { } }", parseOptions: Options.Regular); } [WorkItem(632182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DontOverparenthesizeGenerics() { await TestAsync( @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex<int>(), y), - -1); } } static class E { public static void Ex<T>(this int x) { } }", @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex<int>(), y), (object)- -1); } private static string GetX(string x) { return x; } } static class E { public static void Ex<T>(this int x) { } }", parseOptions: Options.Regular); } [WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_1() { await TestInRegularAndScript1Async( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do();|] obj1.Do(); obj2.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2; {|Rename:NewMethod|}(out obj1, out obj2); obj1.Do(); obj2.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); } }"); } [WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_2() { await TestInRegularAndScript1Async( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ Construct obj3 = new Construct(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ obj3 = new Construct(); obj3.Do(); } }"); } [WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_3() { await TestInRegularAndScript1Async( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(), obj3 = new Construct(); obj2.Do(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj3 = new Construct(); obj2.Do(); obj3.Do(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTuple() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int, int) x = (1, 2);|] System.Console.WriteLine(x.Item1); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); } private static (int, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleDeclarationWithNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int a, int b) x = (1, 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int b) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleDeclarationWithSomeNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int a, int) x = (1, 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] public async Task TestTupleWith1Arity() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { ValueTuple<int> y = ValueTuple.Create(1); [|y.Item1.ToString();|] } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"using System; class Program { static void Main(string[] args) { ValueTuple<int> y = ValueTuple.Create(1); {|Rename:NewMethod|}(y); } private static void NewMethod(ValueTuple<int> y) { y.Item1.ToString(); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleLiteralWithNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int, int) x = (a: 1, b: 2);|] System.Console.WriteLine(x.Item1); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); } private static (int, int) NewMethod() { return (a: 1, b: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleDeclarationAndLiteralWithNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int a, int b) x = (c: 1, d: 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int b) NewMethod() { return (c: 1, d: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleIntoVar() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|var x = (c: 1, d: 2);|] System.Console.WriteLine(x.c); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int c, int d) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static (int c, int d) NewMethod() { return (c: 1, d: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task RefactorWithoutSystemValueTuple() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|var x = (c: 1, d: 2);|] System.Console.WriteLine(x.c); } }", @"class Program { static void Main(string[] args) { (int c, int d) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static (int c, int d) NewMethod() { return (c: 1, d: 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleWithNestedNamedTuple() { // This is not the best refactoring, but this is an edge case await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|var x = new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world""));|] System.Console.WriteLine(x.c); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int, int, int, int, int, int, string, string) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static (int, int, int, int, int, int, int, string, string) NewMethod() { return new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world"")); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] public async Task TestDeconstruction() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { var (x, y) = [|(1, 2)|]; System.Console.WriteLine(x); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { var (x, y) = {|Rename:NewMethod|}(); System.Console.WriteLine(x); } private static (int, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] public async Task TestDeconstruction2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { var (x, y) = (1, 2); var z = [|3;|] System.Console.WriteLine(z); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { var (x, y) = (1, 2); int z = {|Rename:NewMethod|}(); System.Console.WriteLine(z); } private static int NewMethod() { return 3; } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [CompilerTrait(CompilerFeature.OutVar)] public async Task TestOutVar() { await TestInRegularAndScript1Async( @"class C { static void M(int i) { int r; [|r = M1(out int y, i);|] System.Console.WriteLine(r + y); } }", @"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(int i, out int r, out int y) { r = M1(out y, i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [CompilerTrait(CompilerFeature.Patterns)] public async Task TestIsPattern() { await TestInRegularAndScript1Async( @"class C { static void M(int i) { int r; [|r = M1(3 is int y, i);|] System.Console.WriteLine(r + y); } }", @"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(int i, out int r, out int y) { r = M1(3 is int {|Conflict:y|}, i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [CompilerTrait(CompilerFeature.Patterns)] public async Task TestOutVarAndIsPattern() { await TestInRegularAndScript1Async( @"class C { static void M() { int r; [|r = M1(out /*out*/ int /*int*/ y /*y*/) + M2(3 is int z);|] System.Console.WriteLine(r + y + z); } } ", @"class C { static void M() { int r; int y, z; {|Rename:NewMethod|}(out r, out y, out z); System.Console.WriteLine(r + y + z); } private static void NewMethod(out int r, out int y, out int z) { r = M1(out /*out*/ /*int*/ y /*y*/) + M2(3 is int {|Conflict:z|}); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [CompilerTrait(CompilerFeature.Patterns)] public async Task ConflictingOutVarLocals() { await TestInRegularAndScript1Async( @"class C { static void M() { int r; [|r = M1(out int y); { M2(out int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } }", @"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(out int r, out int y) { r = M1(out y); { M2(out int y); System.Console.Write(y); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [CompilerTrait(CompilerFeature.Patterns)] public async Task ConflictingPatternLocals() { await TestInRegularAndScript1Async( @"class C { static void M() { int r; [|r = M1(1 is int y); { M2(2 is int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } }", @"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(out int r, out int y) { r = M1(1 is int {|Conflict:y|}); { M2(2 is int y); System.Console.Write(y); } } }"); } [WorkItem(15218, "https://github.com/dotnet/roslyn/issues/15218")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestCancellationTokenGoesLast() { await TestInRegularAndScript1Async( @"using System; using System.Threading; class C { void M(CancellationToken ct) { var v = 0; [|if (true) { ct.ThrowIfCancellationRequested(); Console.WriteLine(v); }|] } }", @"using System; using System.Threading; class C { void M(CancellationToken ct) { var v = 0; {|Rename:NewMethod|}(v, ct); } private static void NewMethod(int v, CancellationToken ct) { if (true) { ct.ThrowIfCancellationRequested(); Console.WriteLine(v); } } }"); } [WorkItem(15219, "https://github.com/dotnet/roslyn/issues/15219")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseVar1() { await TestInRegularAndScript1Async( @"using System; class C { void Goo(int i) { [|var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; }|] Console.WriteLine(v); } }", @"using System; class C { void Goo(int i) { var v = {|Rename:NewMethod|}(i); Console.WriteLine(v); } private static string NewMethod(int i) { var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; } return v; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSuggestionEnforcement))); } [WorkItem(15219, "https://github.com/dotnet/roslyn/issues/15219")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseVar2() { await TestInRegularAndScript1Async( @"using System; class C { void Goo(int i) { [|var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; }|] Console.WriteLine(v); } }", @"using System; class C { void Goo(int i) { string v = {|Rename:NewMethod|}(i); Console.WriteLine(v); } private static string NewMethod(int i) { var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; } return v; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSuggestionEnforcement))); } [Fact] [WorkItem(15532, "https://github.com/dotnet/roslyn/issues/15532")] public async Task ExtractLocalFunctionCall() { var code = @" class C { public static void Main() { void Local() { } [|Local();|] } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_local_function }); } [Fact] public async Task ExtractLocalFunctionCall_2() { await TestInRegularAndScript1Async(@" class C { public static void Main() { [|void Local() { } Local();|] } }", @" class C { public static void Main() { {|Rename:NewMethod|}(); } private static void NewMethod() { void Local() { } Local(); } }"); } [Fact] [WorkItem(15532, "https://github.com/dotnet/roslyn/issues/15532")] public async Task ExtractLocalFunctionCallWithCapture() { var code = @" class C { public static void Main(string[] args) { bool Local() => args == null; [|Local();|] } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_local_function }); } [Fact] [WorkItem(15532, "https://github.com/dotnet/roslyn/issues/15532")] public async Task ExtractLocalFunctionDeclaration() { await TestMissingInRegularAndScriptAsync(@" class C { public static void Main() { [|bool Local() => args == null;|] Local(); } }"); } [Fact] [WorkItem(15532, "https://github.com/dotnet/roslyn/issues/15532")] public async Task ExtractLocalFunctionInterior() { await TestInRegularAndScript1Async(@" class C { public static void Main() { void Local() { [|int x = 0; x++;|] } Local(); } }", @" class C { public static void Main() { void Local() { {|Rename:NewMethod|}(); } Local(); } private static void NewMethod() { int x = 0; x++; } }"); } [WorkItem(538229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538229")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task Bug3790() { await TestInRegularAndScript1Async(@" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { [|v = v + i;|] } } } }", @" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { v = {|Rename:NewMethod|}(v, i); } } } private static int NewMethod(int v, int i) { v = v + i; return v; } }"); } [WorkItem(538229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538229")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task Bug3790_1() { await TestInRegularAndScript1Async(@" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { [|v = v + i|]; } } } }", @" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { v = {|Rename:NewMethod|}(v, i); } } } private static int NewMethod(int v, int i) { return v + i; } }"); } [WorkItem(538229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538229")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task Bug3790_2() { await TestInRegularAndScript1Async(@" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { [|i = v = v + i|]; } } } }", @" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { i = {|Rename:NewMethod|}(ref v, i); } } } private static int NewMethod(ref int v, int i) { return v = v + i; } }"); } [WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExpressionBodyProperty() { await TestInRegularAndScript1Async(@" class Program { int field; public int Blah => [|this.field|]; }", @" class Program { int field; public int Blah => {|Rename:GetField|}(); private int GetField() { return this.field; } }"); } [WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExpressionBodyIndexer() { await TestInRegularAndScript1Async(@" class Program { int field; public int this[int i] => [|this.field|]; }", @" class Program { int field; public int this[int i] => {|Rename:GetField|}(); private int GetField() { return this.field; } }"); } [WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExpressionBodyPropertyGetAccessor() { await TestInRegularAndScript1Async(@" class Program { int field; public int Blah { get => [|this.field|]; set => field = value; } }", @" class Program { int field; public int Blah { get => {|Rename:GetField|}(); set => field = value; } private int GetField() { return this.field; } }"); } [WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExpressionBodyPropertySetAccessor() { await TestInRegularAndScript1Async(@" class Program { int field; public int Blah { get => this.field; set => field = [|value|]; } }", @" class Program { int field; public int Blah { get => this.field; set => field = {|Rename:GetValue|}(value); } private static int GetValue(int value) { return value; } }"); } [WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExpressionBodyIndexerGetAccessor() { await TestInRegularAndScript1Async(@" class Program { int field; public int this[int i] { get => [|this.field|]; set => field = value; } }", @" class Program { int field; public int this[int i] { get => {|Rename:GetField|}(); set => field = value; } private int GetField() { return this.field; } }"); } [WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExpressionBodyIndexerSetAccessor() { await TestInRegularAndScript1Async(@" class Program { int field; public int this[int i] { get => this.field; set => field = [|value|]; } }", @" class Program { int field; public int this[int i] { get => this.field; set => field = {|Rename:GetValue|}(value); } private static int GetValue(int value) { return value; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestTupleWithInferredNames() { await TestAsync(@" class Program { void M() { int a = 1; var t = [|(a, b: 2)|]; System.Console.Write(t.a); } }", @" class Program { void M() { int a = 1; var t = {|Rename:GetT|}(a); System.Console.Write(t.a); } private static (int a, int b) GetT(int a) { return (a, b: 2); } }", TestOptions.Regular7_1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestDeconstruction4() { await TestAsync(@" class Program { void M() { [|var (x, y) = (1, 2);|] System.Console.Write(x + y); } }", @" class Program { void M() { int x, y; {|Rename:NewMethod|}(out x, out y); System.Console.Write(x + y); } private static void NewMethod(out int x, out int y) { var (x, y) = (1, 2); } }", TestOptions.Regular7_1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestDeconstruction5() { await TestAsync(@" class Program { void M() { [|(var x, var y) = (1, 2);|] System.Console.Write(x + y); } }", @" class Program { void M() { int x, y; {|Rename:NewMethod|}(out x, out y); System.Console.Write(x + y); } private static void NewMethod(out int x, out int y) { (x, y) = (1, 2); } }", TestOptions.Regular7_1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestIndexExpression() { await TestInRegularAndScript1Async(TestSources.Index + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|^1|]); } }", TestSources.Index + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); } private static System.Index NewMethod() { return ^1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestRangeExpression_Empty() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|..|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); } private static System.Range NewMethod() { return ..; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestRangeExpression_Left() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|..1|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); } private static System.Range NewMethod() { return ..1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestRangeExpression_Right() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|1..|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); } private static System.Range NewMethod() { return 1..; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestRangeExpression_Both() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|1..2|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); } private static System.Range NewMethod() { return 1..2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestAnnotatedNullableReturn() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { [|string? x = null; x?.ToString();|] return x; } }", @"#nullable enable class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; } private static string? NewMethod() { string? x = null; x?.ToString(); return x; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestAnnotatedNullableParameters1() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { string? a = null; string? b = null; [|string? x = a?.Contains(b).ToString();|] return x; } }", @"#nullable enable class C { public string? M() { string? a = null; string? b = null; string? x = {|Rename:NewMethod|}(a, b); return x; } private static string? NewMethod(string? a, string? b) { return a?.Contains(b).ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestAnnotatedNullableParameters2() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; [|string x = (a + b + c).ToString();|] return x; } }", @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; string x = {|Rename:NewMethod|}(a, b, c); return x; } private static string NewMethod(string? a, string? b, int c) { return (a + b + c).ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestAnnotatedNullableParameters3() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; return [|(a + b + c).ToString()|]; } }", @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; return {|Rename:NewMethod|}(a, b, c); } private static string NewMethod(string? a, string? b, int c) { return (a + b + c).ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestAnnotatedNullableParameters4() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { string? a = null; string? b = null; return [|a?.Contains(b).ToString()|]; } }", @"#nullable enable class C { public string? M() { string? a = null; string? b = null; return {|Rename:NewMethod|}(a, b); } private static string? NewMethod(string? a, string? b) { return a?.Contains(b).ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters1() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; return [|(a + b + a).ToString()|]; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; return {|Rename:NewMethod|}(a, b); } private static string NewMethod(string a, string b) { return (a + b + a).ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters2() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { string? a = string.Empty; string? b = string.Empty; return [|(a + b + a).ToString()|]; } }", @"#nullable enable class C { public string? M() { string? a = string.Empty; string? b = string.Empty; return {|Rename:NewMethod|}(a, b); } private static string NewMethod(string a, string b) { return (a + b + a).ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters3() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = null; string? b = null; return [|(a + b + a)?.ToString()|] ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = null; string? b = null; return {|Rename:NewMethod|}(a, b) ?? string.Empty; } private static string? NewMethod(string? a, string? b) { return (a + b + a)?.ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters_MultipleStates() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|string? c = a + b; a = string.Empty; c += a; a = null; b = null; b = ""test""; c = a?.ToString();|] return c ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string? c = {|Rename:NewMethod|}(ref a, ref b); return c ?? string.Empty; } private static string? NewMethod(ref string? a, ref string? b) { string? c = a + b; a = string.Empty; c += a; a = null; b = null; b = ""test""; c = a?.ToString(); return c; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters_MultipleStatesNonNullReturn() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = null; c = a + b;|] return c ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string? c = {|Rename:NewMethod|}(ref a, ref b); return c ?? string.Empty; } private static string NewMethod(ref string? a, ref string? b) { string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = null; c = a + b; return c; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters_MultipleStatesNullReturn() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = a?.ToString();|] return c ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string? c = {|Rename:NewMethod|}(ref a, ref b); return c ?? string.Empty; } private static string? NewMethod(ref string? a, ref string? b) { string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = a?.ToString(); return c; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters_RefNotNull() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|var c = a + b; a = string.Empty; c += a; b = ""test""; c = a + b +c;|] return c; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string c = {|Rename:NewMethod|}(ref a, ref b); return c; } private static string NewMethod(ref string a, ref string b) { var c = a + b; a = string.Empty; c += a; b = ""test""; c = a + b + c; return c; } }"); // There's a case below where flow state correctly asseses that the variable // 'x' is non-null when returned. It's wasn't obvious when writing, but that's // due to the fact the line above it being executed as 'x.ToString()' would throw // an exception and the return statement would never be hit. The only way the return // statement gets executed is if the `x.ToString()` call succeeds, thus suggesting // that the value is indeed not null. [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowNullableReturn_NotNull1() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { [|string? x = null; x.ToString();|] return x; } }", @"#nullable enable class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; } private static string NewMethod() { string? x = null; x.ToString(); return x; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowNullableReturn_NotNull2() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { [|string? x = null; x?.ToString(); x = string.Empty;|] return x; } }", @"#nullable enable class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; } private static string NewMethod() { string? x = null; x?.ToString(); x = string.Empty; return x; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowNullable_Lambda() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { public string? M() { [|string? x = null; Action modifyXToNonNull = () => { x += x; }; modifyXToNonNull();|] return x; } }", @"#nullable enable using System; class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; } private static string? NewMethod() { string? x = null; Action modifyXToNonNull = () => { x += x; }; modifyXToNonNull(); return x; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowNullable_LambdaWithReturn() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { public string? M() { [|string? x = null; Func<string?> returnNull = () => { return null; }; x = returnNull() ?? string.Empty;|] return x; } }", @"#nullable enable using System; class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; } private static string NewMethod() { string? x = null; Func<string?> returnNull = () => { return null; }; x = returnNull() ?? string.Empty; return x; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractReadOnlyMethod() { await TestInRegularAndScript1Async( @"struct S1 { readonly int M1() => 42; void Main() { [|int i = M1() + M1()|]; } }", @"struct S1 { readonly int M1() => 42; void Main() { {|Rename:NewMethod|}(); } private readonly void NewMethod() { int i = M1() + M1(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractReadOnlyMethodInReadOnlyStruct() { await TestInRegularAndScript1Async( @"readonly struct S1 { int M1() => 42; void Main() { [|int i = M1() + M1()|]; } }", @"readonly struct S1 { int M1() => 42; void Main() { {|Rename:NewMethod|}(); } private void NewMethod() { int i = M1() + M1(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractNonReadOnlyMethodInReadOnlyMethod() { await TestInRegularAndScript1Async( @"struct S1 { int M1() => 42; readonly void Main() { [|int i = M1() + M1()|]; } }", @"struct S1 { int M1() => 42; readonly void Main() { {|Rename:NewMethod|}(); } private void NewMethod() { int i = M1() + M1(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNullableObjectWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = null; var s = (string?)[|o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = null; var s = (string?){|Rename:GetO|}(o); Console.WriteLine(s); } private static object? GetO(object? o) { return o; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNotNullableObjectWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = new object(); var s = (string)[|o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = new object(); var s = (string){|Rename:GetO|}(o); Console.WriteLine(s); } private static object GetO(object o) { return o; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNotNullableWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = new B(); var s = (A)[|b|]; } }", @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = new B(); var s = (A){|Rename:GetB|}(b); } private static B GetB(B b) { return b; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNullableWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = null; var s = (A)[|b|]; } }", @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = null; var s = (A){|Rename:GetB|}(b); } private static B? GetB(B? b) { return b; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNotNullableWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = new object(); var s = [|(string)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = new object(); var s = {|Rename:GetS|}(o); Console.WriteLine(s); } private static string GetS(object o) { return (string)o; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNullableWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = null; var s = [|(string?)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = null; var s = {|Rename:GetS|}(o); Console.WriteLine(s); } private static string? GetS(object? o) { return (string?)o; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNullableNonNullFlowWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = new object(); var s = [|(string?)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = new object(); var s = {|Rename:GetS|}(o); Console.WriteLine(s); } private static string? GetS(object o) { return (string?)o; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNullableToNonNullableWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = null; var s = [|(string)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = null; var s = {|Rename:GetS|}(o); Console.WriteLine(s); } private static string? GetS(object? o) { return (string)o; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task EnsureStaticLocalFunctionOptionHasNoEffect() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) { return b != true; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSuggestionEnforcement))); } [Fact, WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task ExtractLocalFunctionCallAndDeclaration() { await TestInRegularAndScript1Async(@" class C { public static void Main() { static void LocalParent() { [|void Local() { } Local();|] } } }", @" class C { public static void Main() { static void LocalParent() { {|Rename:NewMethod|}(); } } private static void NewMethod() { void Local() { } Local(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingWhenOnlyLocalFunctionCallSelected() { var code = @" class Program { static void Main(string[] args) { [|Local();|] static void Local() { } } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_local_function }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOfferedWhenBothLocalFunctionCallAndDeclarationSelected() { await TestInRegularAndScript1Async(@" class Program { static void Main(string[] args) { [|Local(); var test = 5; static void Local() { }|] } }", @" class Program { static void Main(string[] args) { {|Rename:NewMethod|}(); } private static void NewMethod() { Local(); var test = 5; static void Local() { } } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractNonAsyncMethodWithAsyncLocalFunction() { await TestInRegularAndScript1Async( @"class C { void M() { [|F(); async void F() => await Task.Delay(0);|] } }", @"class C { void M() { {|Rename:NewMethod|}(); } private static void NewMethod() { F(); async void F() => await Task.Delay(0); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitFalse() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(false)|]; } }", @"class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration).ConfigureAwait(false); } private static async System.Threading.Tasks.Task<object> NewMethod(TimeSpan duration) { return await Task.Delay(duration).ConfigureAwait(false); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitFalseNamedParameter() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(continueOnCapturedContext: false)|]; } }", @"class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration).ConfigureAwait(false); } private static async System.Threading.Tasks.Task<object> NewMethod(TimeSpan duration) { return await Task.Delay(duration).ConfigureAwait(continueOnCapturedContext: false); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitFalseOnNonTask() { await TestInRegularAndScript1Async( @"using System.Threading.Tasks class C { async Task MyDelay() { [|await new ValueTask<int>(0).ConfigureAwait(false)|]; } }", @"using System.Threading.Tasks class C { async Task MyDelay() { await {|Rename:NewMethod|}().ConfigureAwait(false); } private static async Task<object> NewMethod() { return await new ValueTask<int>(0).ConfigureAwait(false); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitTrue() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(true)|]; } }", @"class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration); } private static async System.Threading.Tasks.Task<object> NewMethod(TimeSpan duration) { return await Task.Delay(duration).ConfigureAwait(true); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitNonLiteral() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(M())|]; } }", @"class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration); } private static async System.Threading.Tasks.Task<object> NewMethod(TimeSpan duration) { return await Task.Delay(duration).ConfigureAwait(M()); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithNoConfigureAwait() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration)|]; } }", @"class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration); } private static async System.Threading.Tasks.Task<object> NewMethod(TimeSpan duration) { return await Task.Delay(duration); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitFalseInLambda() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Run(async () => await Task.Delay(duration).ConfigureAwait(false))|]; } }", @"class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration); } private static async System.Threading.Tasks.Task<object> NewMethod(TimeSpan duration) { return await Task.Run(async () => await Task.Delay(duration).ConfigureAwait(false)); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitFalseInLocalMethod() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Run(F()); async Task F() => await Task.Delay(duration).ConfigureAwait(false);|] } }", @"using System.Threading.Tasks; class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration); } private static async Task NewMethod(TimeSpan duration) { await Task.Run(F()); async Task F() => await Task.Delay(duration).ConfigureAwait(false); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitMixture1() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(false); await Task.Delay(duration).ConfigureAwait(true);|] } }", @"using System.Threading.Tasks; class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration).ConfigureAwait(false); } private static async Task NewMethod(TimeSpan duration) { await Task.Delay(duration).ConfigureAwait(false); await Task.Delay(duration).ConfigureAwait(true); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitMixture2() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(true); await Task.Delay(duration).ConfigureAwait(false);|] } }", @"using System.Threading.Tasks; class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration).ConfigureAwait(false); } private static async Task NewMethod(TimeSpan duration) { await Task.Delay(duration).ConfigureAwait(true); await Task.Delay(duration).ConfigureAwait(false); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitMixture3() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(M()); await Task.Delay(duration).ConfigureAwait(false);|] } }", @"using System.Threading.Tasks; class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration).ConfigureAwait(false); } private static async Task NewMethod(TimeSpan duration) { await Task.Delay(duration).ConfigureAwait(M()); await Task.Delay(duration).ConfigureAwait(false); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitFalseOutsideSelection() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { await Task.Delay(duration).ConfigureAwait(false); [|await Task.Delay(duration).ConfigureAwait(true);|] } }", @"using System.Threading.Tasks; class C { async Task MyDelay(TimeSpan duration) { await Task.Delay(duration).ConfigureAwait(false); await {|Rename:NewMethod|}(duration); } private static async Task NewMethod(TimeSpan duration) { await Task.Delay(duration).ConfigureAwait(true); } }"); } [Fact, WorkItem(40188, "https://github.com/dotnet/roslyn/issues/40188"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_True() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = true:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); } private static bool NewMethod() => true; } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = true:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected); } [Fact, WorkItem(40188, "https://github.com/dotnet/roslyn/issues/40188"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_False() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); } private static bool NewMethod() { return true; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestNaming_CamelCase_VerifyLocalFunctionSettingsDontApply() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_LocalFunctions_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); } private static bool NewMethod() { return true; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_LocalFunctions_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestNaming_CamelCase_VerifyLocalFunctionSettingsDontApply_GetName() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class MethodExtraction { void TestMethod() { int a = [|1 + 1|]; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_LocalFunctions_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class MethodExtraction { void TestMethod() { int a = {|Rename:GetA|}(); } private static int GetA() { return 1 + 1; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_LocalFunctions_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected); } [WorkItem(40654, "https://github.com/dotnet/roslyn/issues/40654")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOnInvalidUsingStatement_MultipleStatements() { var input = @" class C { void M() { [|var v = 0; using System;|] } }"; var expected = @" class C { void M() { {|Rename:NewMethod|}(); } private static void NewMethod() { var v = 0; using System; } }"; await TestInRegularAndScript1Async(input, expected); } [WorkItem(40654, "https://github.com/dotnet/roslyn/issues/40654")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnInvalidUsingStatement() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|using System;|] } }"); } [Fact, WorkItem(19461, "https://github.com/dotnet/roslyn/issues/19461")] public async Task TestLocalFunction() { await TestInRegularAndScript1Async(@" using System; class Program { void M() { int y = 0; [|var x = local(); int local() { return y; }|] } }", @" using System; class Program { void M() { int y = 0; {|Rename:NewMethod|}(y); } private static void NewMethod(int y) { var x = local(); int local() { return y; } } }"); } [Fact, WorkItem(43834, "https://github.com/dotnet/roslyn/issues/43834")] public async Task TestRecursivePatternRewrite() { await TestInRegularAndScript1Async(@" using System; namespace N { class Context { } class C { public void DoAction(Action<Context> action) { } private void Recursive(object context) { DoAction(context => { if (context is Context { }) { DoAction( [|context =>|] context.ToString()); } }); } } }", @" using System; namespace N { class Context { } class C { public void DoAction(Action<Context> action) { } private void Recursive(object context) { DoAction(context => { if (context is Context { }) { DoAction( {|Rename:NewMethod|}()); } }); } private static Action<Context> NewMethod() { return context => context.ToString(); } } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess1() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?.[|ToString|](); } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static string NewMethod(List<int> b) { return b?.ToString(); } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess2() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?.[|ToString|]().Length; } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static int? NewMethod(List<int> b) { return b?.ToString().Length; } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess3() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?.Count.[|ToString|](); } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static string NewMethod(List<int> b) { return b?.Count.ToString(); } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess4() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?.[|Count|].ToString(); } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static string NewMethod(List<int> b) { return b?.Count.ToString(); } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess5() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?.[|ToString|]()?.ToString(); } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static string NewMethod(List<int> b) { return b?.ToString()?.ToString(); } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess6() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?.ToString()?.[|ToString|](); } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static string NewMethod(List<int> b) { return b?.ToString()?.ToString(); } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess7() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?[|[0]|]; } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static int? NewMethod(List<int> b) { return b?[0]; } }"); } [WorkItem(48453, "https://github.com/dotnet/roslyn/issues/48453")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [InlineData("record")] [InlineData("record class")] public async Task TestInRecord(string record) { await TestInRegularAndScript1Async($@" {record} Program {{ int field; public int this[int i] => [|this.field|]; }}", $@" {record} Program {{ int field; public int this[int i] => {{|Rename:GetField|}}(); private int GetField() {{ return this.field; }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestInRecordStruct() { await TestInRegularAndScript1Async(@" record struct Program { int field; public int this[int i] => [|this.field|]; }", @" record struct Program { int field; public int this[int i] => {|Rename:GetField|}(); private readonly int GetField() { return this.field; } }"); } [WorkItem(53031, "https://github.com/dotnet/roslyn/issues/53031")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMethodInNamespace() { await TestMissingInRegularAndScriptAsync(@" namespace TestNamespace { private bool TestMethod() => [|false|]; }"); } [WorkItem(53031, "https://github.com/dotnet/roslyn/issues/53031")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMethodInInterface() { await TestInRegularAndScript1Async(@" interface TestInterface { bool TestMethod() => [|false|]; }", @" interface TestInterface { bool TestMethod() => {|Rename:NewMethod|}(); bool NewMethod() { return 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.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeRefactorings.ExtractMethod; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ExtractMethod { public class ExtractMethodTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new ExtractMethodCodeRefactoringProvider(); private const string EditorConfigNaming_LocalFunctions_CamelCase = @"[*] # Naming rules dotnet_naming_rule.local_functions_should_be_camel_case.severity = suggestion dotnet_naming_rule.local_functions_should_be_camel_case.symbols = local_functions dotnet_naming_rule.local_functions_should_be_camel_case.style = camel_case # Symbol specifications dotnet_naming_symbols.local_functions.applicable_kinds = local_function dotnet_naming_symbols.local_functions.applicable_accessibilities = * dotnet_naming_symbols.local_functions.required_modifiers = # Naming styles dotnet_naming_style.camel_case.capitalization = camel_case"; [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public async Task LocalFuncExtract() { await TestInRegularAndScript1Async(@" class C { int Testing; void M() { local(); [|NewMethod();|] Testing = 5; void local() { } } void NewMethod() { } }", @" class C { int Testing; void M() { local(); {|Rename:NewMethod1|}(); Testing = 5; void local() { } } private void NewMethod1() { NewMethod(); } void NewMethod() { } }"); } [WorkItem(540799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestPartialSelection() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) { return b != true; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestSelectionOfSwitchExpressionArm() { await TestInRegularAndScript1Async( @"class Program { int Foo(int x) => x switch { 1 => 1, _ => [|1 + x|] }; }", @"class Program { int Foo(int x) => x switch { 1 => 1, _ => {|Rename:NewMethod|}(x) }; private static int NewMethod(int x) => 1 + x; }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestSelectionOfSwitchExpressionArmContainingVariables() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class TestClass { public static T RecursiveExample<T>(IEnumerable<T> sequence) => sequence switch { Array { Length: 0 } => default(T), Array { Length: 1 } array => [|(T)array.GetValue(0)|], Array { Length: 2 } array => (T)array.GetValue(1), Array array => (T)array.GetValue(2), _ => throw new NotImplementedException(), }; }", @"using System; using System.Collections.Generic; class TestClass { public static T RecursiveExample<T>(IEnumerable<T> sequence) => sequence switch { Array { Length: 0 } => default(T), Array { Length: 1 } array => {|Rename:NewMethod|}<T>(array), Array { Length: 2 } array => (T)array.GetValue(1), Array array => (T)array.GetValue(2), _ => throw new NotImplementedException(), }; private static T NewMethod<T>(Array array) => (T)array.GetValue(0); }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseExpressionBodyWhenPossible() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) => b != true; }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) => b != true; }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseExpressionWhenOnSingleLine_AndIsOnSingleLine2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine( [|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine( {|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) => b != true; }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) { return b != true; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b !=/* */true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) { return b !=/* */true; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseExpressionWhenOnSingleLine_AndNotIsOnSingleLine3() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|"""" != @"" ""|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}() ? b = true : b = false); } private static bool NewMethod() { return """" != @"" ""; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement))); } [WorkItem(540796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540796")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestReadOfDataThatDoesNotFlowIn() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { int x = 1; object y = 0; [|int s = true ? fun(x) : fun(y);|] } private static T fun<T>(T t) { return t; } }", @"class Program { static void Main(string[] args) { int x = 1; object y = 0; {|Rename:NewMethod|}(x, y); } private static void NewMethod(int x, object y) { int s = true ? fun(x) : fun(y); } private static T fun<T>(T t) { return t; } }"); } [WorkItem(540819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnGoto() { await TestMissingInRegularAndScriptAsync( @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { [|goto label2; return x * x;|] }; label2: return; } }"); } [WorkItem(540819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOnStatementAfterUnconditionalGoto() { await TestInRegularAndScript1Async( @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; [|return x * x;|] }; label2: return; } }", @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; return {|Rename:NewMethod|}(x); }; label2: return; } private static int NewMethod(int x) { return x * x; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnNamespace() { await TestInRegularAndScript1Async( @"class Program { void Main() { [|System|].Console.WriteLine(4); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); } private static void NewMethod() { System.Console.WriteLine(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnType() { await TestInRegularAndScript1Async( @"class Program { void Main() { [|System.Console|].WriteLine(4); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); } private static void NewMethod() { System.Console.WriteLine(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnBase() { await TestInRegularAndScript1Async( @"class Program { void Main() { [|base|].ToString(); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); } private void NewMethod() { base.ToString(); } }"); } [WorkItem(545623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545623")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOnActionInvocation() { await TestInRegularAndScript1Async( @"using System; class C { public static Action X { get; set; } } class Program { void Main() { [|C.X|](); } }", @"using System; class C { public static Action X { get; set; } } class Program { void Main() { {|Rename:GetX|}()(); } private static Action GetX() { return C.X; } }"); } [WorkItem(529841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem(714632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DisambiguateCallSiteIfNecessary1() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main() { byte z = 0; Goo([|x => 0|], y => 0, z, z); } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Goo({|Rename:NewMethod|}(), y => (byte)0, z, z); } private static Func<byte, byte> NewMethod() { return x => 0; } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }"); } [WorkItem(529841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem(714632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DisambiguateCallSiteIfNecessary2() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main() { byte z = 0; Goo([|x => 0|], y => { return 0; }, z, z); } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Goo({|Rename:NewMethod|}(), y => { return (byte)0; }, z, z); } private static Func<byte, byte> NewMethod() { return x => 0; } static void Goo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Goo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }"); } [WorkItem(530709, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530709")] [WorkItem(632182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DontOverparenthesize() { await TestAsync( @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex(), y), - -1); } } static class E { public static void Ex(this int x) { } }", @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex(), y), (object)- -1); } private static string GetX(string x) { return x; } } static class E { public static void Ex(this int x) { } }", parseOptions: Options.Regular); } [WorkItem(632182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DontOverparenthesizeGenerics() { await TestAsync( @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex<int>(), y), - -1); } } static class E { public static void Ex<T>(this int x) { } }", @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex<int>(), y), (object)- -1); } private static string GetX(string x) { return x; } } static class E { public static void Ex<T>(this int x) { } }", parseOptions: Options.Regular); } [WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_1() { await TestInRegularAndScript1Async( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do();|] obj1.Do(); obj2.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2; {|Rename:NewMethod|}(out obj1, out obj2); obj1.Do(); obj2.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); } }"); } [WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_2() { await TestInRegularAndScript1Async( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ Construct obj3 = new Construct(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ obj3 = new Construct(); obj3.Do(); } }"); } [WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_3() { await TestInRegularAndScript1Async( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(), obj3 = new Construct(); obj2.Do(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj3 = new Construct(); obj2.Do(); obj3.Do(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTuple() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int, int) x = (1, 2);|] System.Console.WriteLine(x.Item1); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); } private static (int, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleDeclarationWithNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int a, int b) x = (1, 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int b) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleDeclarationWithSomeNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int a, int) x = (1, 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] public async Task TestTupleWith1Arity() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { ValueTuple<int> y = ValueTuple.Create(1); [|y.Item1.ToString();|] } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"using System; class Program { static void Main(string[] args) { ValueTuple<int> y = ValueTuple.Create(1); {|Rename:NewMethod|}(y); } private static void NewMethod(ValueTuple<int> y) { y.Item1.ToString(); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleLiteralWithNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int, int) x = (a: 1, b: 2);|] System.Console.WriteLine(x.Item1); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); } private static (int, int) NewMethod() { return (a: 1, b: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleDeclarationAndLiteralWithNames() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|(int a, int b) x = (c: 1, d: 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int b) NewMethod() { return (c: 1, d: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleIntoVar() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|var x = (c: 1, d: 2);|] System.Console.WriteLine(x.c); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int c, int d) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static (int c, int d) NewMethod() { return (c: 1, d: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task RefactorWithoutSystemValueTuple() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|var x = (c: 1, d: 2);|] System.Console.WriteLine(x.c); } }", @"class Program { static void Main(string[] args) { (int c, int d) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static (int c, int d) NewMethod() { return (c: 1, d: 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleWithNestedNamedTuple() { // This is not the best refactoring, but this is an edge case await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { [|var x = new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world""));|] System.Console.WriteLine(x.c); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int, int, int, int, int, int, string, string) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static (int, int, int, int, int, int, int, string, string) NewMethod() { return new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world"")); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] public async Task TestDeconstruction() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { var (x, y) = [|(1, 2)|]; System.Console.WriteLine(x); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { var (x, y) = {|Rename:NewMethod|}(); System.Console.WriteLine(x); } private static (int, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), CompilerTrait(CompilerFeature.Tuples)] public async Task TestDeconstruction2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { var (x, y) = (1, 2); var z = [|3;|] System.Console.WriteLine(z); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { var (x, y) = (1, 2); int z = {|Rename:NewMethod|}(); System.Console.WriteLine(z); } private static int NewMethod() { return 3; } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [CompilerTrait(CompilerFeature.OutVar)] public async Task TestOutVar() { await TestInRegularAndScript1Async( @"class C { static void M(int i) { int r; [|r = M1(out int y, i);|] System.Console.WriteLine(r + y); } }", @"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(int i, out int r, out int y) { r = M1(out y, i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [CompilerTrait(CompilerFeature.Patterns)] public async Task TestIsPattern() { await TestInRegularAndScript1Async( @"class C { static void M(int i) { int r; [|r = M1(3 is int y, i);|] System.Console.WriteLine(r + y); } }", @"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(int i, out int r, out int y) { r = M1(3 is int {|Conflict:y|}, i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [CompilerTrait(CompilerFeature.Patterns)] public async Task TestOutVarAndIsPattern() { await TestInRegularAndScript1Async( @"class C { static void M() { int r; [|r = M1(out /*out*/ int /*int*/ y /*y*/) + M2(3 is int z);|] System.Console.WriteLine(r + y + z); } } ", @"class C { static void M() { int r; int y, z; {|Rename:NewMethod|}(out r, out y, out z); System.Console.WriteLine(r + y + z); } private static void NewMethod(out int r, out int y, out int z) { r = M1(out /*out*/ /*int*/ y /*y*/) + M2(3 is int {|Conflict:z|}); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [CompilerTrait(CompilerFeature.Patterns)] public async Task ConflictingOutVarLocals() { await TestInRegularAndScript1Async( @"class C { static void M() { int r; [|r = M1(out int y); { M2(out int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } }", @"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(out int r, out int y) { r = M1(out y); { M2(out int y); System.Console.Write(y); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [CompilerTrait(CompilerFeature.Patterns)] public async Task ConflictingPatternLocals() { await TestInRegularAndScript1Async( @"class C { static void M() { int r; [|r = M1(1 is int y); { M2(2 is int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } }", @"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(out int r, out int y) { r = M1(1 is int {|Conflict:y|}); { M2(2 is int y); System.Console.Write(y); } } }"); } [WorkItem(15218, "https://github.com/dotnet/roslyn/issues/15218")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestCancellationTokenGoesLast() { await TestInRegularAndScript1Async( @"using System; using System.Threading; class C { void M(CancellationToken ct) { var v = 0; [|if (true) { ct.ThrowIfCancellationRequested(); Console.WriteLine(v); }|] } }", @"using System; using System.Threading; class C { void M(CancellationToken ct) { var v = 0; {|Rename:NewMethod|}(v, ct); } private static void NewMethod(int v, CancellationToken ct) { if (true) { ct.ThrowIfCancellationRequested(); Console.WriteLine(v); } } }"); } [WorkItem(15219, "https://github.com/dotnet/roslyn/issues/15219")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseVar1() { await TestInRegularAndScript1Async( @"using System; class C { void Goo(int i) { [|var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; }|] Console.WriteLine(v); } }", @"using System; class C { void Goo(int i) { var v = {|Rename:NewMethod|}(i); Console.WriteLine(v); } private static string NewMethod(int i) { var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; } return v; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSuggestionEnforcement))); } [WorkItem(15219, "https://github.com/dotnet/roslyn/issues/15219")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseVar2() { await TestInRegularAndScript1Async( @"using System; class C { void Goo(int i) { [|var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; }|] Console.WriteLine(v); } }", @"using System; class C { void Goo(int i) { string v = {|Rename:NewMethod|}(i); Console.WriteLine(v); } private static string NewMethod(int i) { var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; } return v; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSuggestionEnforcement))); } [Fact] [WorkItem(15532, "https://github.com/dotnet/roslyn/issues/15532")] public async Task ExtractLocalFunctionCall() { var code = @" class C { public static void Main() { void Local() { } [|Local();|] } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_local_function }); } [Fact] public async Task ExtractLocalFunctionCall_2() { await TestInRegularAndScript1Async(@" class C { public static void Main() { [|void Local() { } Local();|] } }", @" class C { public static void Main() { {|Rename:NewMethod|}(); } private static void NewMethod() { void Local() { } Local(); } }"); } [Fact] [WorkItem(15532, "https://github.com/dotnet/roslyn/issues/15532")] public async Task ExtractLocalFunctionCallWithCapture() { var code = @" class C { public static void Main(string[] args) { bool Local() => args == null; [|Local();|] } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_local_function }); } [Fact] [WorkItem(15532, "https://github.com/dotnet/roslyn/issues/15532")] public async Task ExtractLocalFunctionDeclaration() { await TestMissingInRegularAndScriptAsync(@" class C { public static void Main() { [|bool Local() => args == null;|] Local(); } }"); } [Fact] [WorkItem(15532, "https://github.com/dotnet/roslyn/issues/15532")] public async Task ExtractLocalFunctionInterior() { await TestInRegularAndScript1Async(@" class C { public static void Main() { void Local() { [|int x = 0; x++;|] } Local(); } }", @" class C { public static void Main() { void Local() { {|Rename:NewMethod|}(); } Local(); } private static void NewMethod() { int x = 0; x++; } }"); } [WorkItem(538229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538229")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task Bug3790() { await TestInRegularAndScript1Async(@" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { [|v = v + i;|] } } } }", @" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { v = {|Rename:NewMethod|}(v, i); } } } private static int NewMethod(int v, int i) { v = v + i; return v; } }"); } [WorkItem(538229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538229")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task Bug3790_1() { await TestInRegularAndScript1Async(@" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { [|v = v + i|]; } } } }", @" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { v = {|Rename:NewMethod|}(v, i); } } } private static int NewMethod(int v, int i) { return v + i; } }"); } [WorkItem(538229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538229")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task Bug3790_2() { await TestInRegularAndScript1Async(@" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { [|i = v = v + i|]; } } } }", @" class Test { void method() { static void Main(string[] args) { int v = 0; for(int i=0 ; i<5; i++) { i = {|Rename:NewMethod|}(ref v, i); } } } private static int NewMethod(ref int v, int i) { return v = v + i; } }"); } [WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExpressionBodyProperty() { await TestInRegularAndScript1Async(@" class Program { int field; public int Blah => [|this.field|]; }", @" class Program { int field; public int Blah => {|Rename:GetField|}(); private int GetField() { return this.field; } }"); } [WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExpressionBodyIndexer() { await TestInRegularAndScript1Async(@" class Program { int field; public int this[int i] => [|this.field|]; }", @" class Program { int field; public int this[int i] => {|Rename:GetField|}(); private int GetField() { return this.field; } }"); } [WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExpressionBodyPropertyGetAccessor() { await TestInRegularAndScript1Async(@" class Program { int field; public int Blah { get => [|this.field|]; set => field = value; } }", @" class Program { int field; public int Blah { get => {|Rename:GetField|}(); set => field = value; } private int GetField() { return this.field; } }"); } [WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExpressionBodyPropertySetAccessor() { await TestInRegularAndScript1Async(@" class Program { int field; public int Blah { get => this.field; set => field = [|value|]; } }", @" class Program { int field; public int Blah { get => this.field; set => field = {|Rename:GetValue|}(value); } private static int GetValue(int value) { return value; } }"); } [WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExpressionBodyIndexerGetAccessor() { await TestInRegularAndScript1Async(@" class Program { int field; public int this[int i] { get => [|this.field|]; set => field = value; } }", @" class Program { int field; public int this[int i] { get => {|Rename:GetField|}(); set => field = value; } private int GetField() { return this.field; } }"); } [WorkItem(392560, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=392560")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExpressionBodyIndexerSetAccessor() { await TestInRegularAndScript1Async(@" class Program { int field; public int this[int i] { get => this.field; set => field = [|value|]; } }", @" class Program { int field; public int this[int i] { get => this.field; set => field = {|Rename:GetValue|}(value); } private static int GetValue(int value) { return value; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestTupleWithInferredNames() { await TestAsync(@" class Program { void M() { int a = 1; var t = [|(a, b: 2)|]; System.Console.Write(t.a); } }", @" class Program { void M() { int a = 1; var t = {|Rename:GetT|}(a); System.Console.Write(t.a); } private static (int a, int b) GetT(int a) { return (a, b: 2); } }", TestOptions.Regular7_1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestDeconstruction4() { await TestAsync(@" class Program { void M() { [|var (x, y) = (1, 2);|] System.Console.Write(x + y); } }", @" class Program { void M() { int x, y; {|Rename:NewMethod|}(out x, out y); System.Console.Write(x + y); } private static void NewMethod(out int x, out int y) { var (x, y) = (1, 2); } }", TestOptions.Regular7_1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestDeconstruction5() { await TestAsync(@" class Program { void M() { [|(var x, var y) = (1, 2);|] System.Console.Write(x + y); } }", @" class Program { void M() { int x, y; {|Rename:NewMethod|}(out x, out y); System.Console.Write(x + y); } private static void NewMethod(out int x, out int y) { (x, y) = (1, 2); } }", TestOptions.Regular7_1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestIndexExpression() { await TestInRegularAndScript1Async(TestSources.Index + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|^1|]); } }", TestSources.Index + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); } private static System.Index NewMethod() { return ^1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestRangeExpression_Empty() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|..|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); } private static System.Range NewMethod() { return ..; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestRangeExpression_Left() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|..1|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); } private static System.Range NewMethod() { return ..1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestRangeExpression_Right() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|1..|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); } private static System.Range NewMethod() { return 1..; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestRangeExpression_Both() { await TestInRegularAndScript1Async(TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine([|1..2|]); } }", TestSources.Index + TestSources.Range + @" class Program { static void Main(string[] args) { System.Console.WriteLine({|Rename:NewMethod|}()); } private static System.Range NewMethod() { return 1..2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestAnnotatedNullableReturn() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { [|string? x = null; x?.ToString();|] return x; } }", @"#nullable enable class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; } private static string? NewMethod() { string? x = null; x?.ToString(); return x; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestAnnotatedNullableParameters1() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { string? a = null; string? b = null; [|string? x = a?.Contains(b).ToString();|] return x; } }", @"#nullable enable class C { public string? M() { string? a = null; string? b = null; string? x = {|Rename:NewMethod|}(a, b); return x; } private static string? NewMethod(string? a, string? b) { return a?.Contains(b).ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestAnnotatedNullableParameters2() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; [|string x = (a + b + c).ToString();|] return x; } }", @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; string x = {|Rename:NewMethod|}(a, b, c); return x; } private static string NewMethod(string? a, string? b, int c) { return (a + b + c).ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestAnnotatedNullableParameters3() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; return [|(a + b + c).ToString()|]; } }", @"#nullable enable class C { public string M() { string? a = null; string? b = null; int c = 0; return {|Rename:NewMethod|}(a, b, c); } private static string NewMethod(string? a, string? b, int c) { return (a + b + c).ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestAnnotatedNullableParameters4() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { string? a = null; string? b = null; return [|a?.Contains(b).ToString()|]; } }", @"#nullable enable class C { public string? M() { string? a = null; string? b = null; return {|Rename:NewMethod|}(a, b); } private static string? NewMethod(string? a, string? b) { return a?.Contains(b).ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters1() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; return [|(a + b + a).ToString()|]; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; return {|Rename:NewMethod|}(a, b); } private static string NewMethod(string a, string b) { return (a + b + a).ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters2() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { string? a = string.Empty; string? b = string.Empty; return [|(a + b + a).ToString()|]; } }", @"#nullable enable class C { public string? M() { string? a = string.Empty; string? b = string.Empty; return {|Rename:NewMethod|}(a, b); } private static string NewMethod(string a, string b) { return (a + b + a).ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters3() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = null; string? b = null; return [|(a + b + a)?.ToString()|] ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = null; string? b = null; return {|Rename:NewMethod|}(a, b) ?? string.Empty; } private static string? NewMethod(string? a, string? b) { return (a + b + a)?.ToString(); } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters_MultipleStates() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|string? c = a + b; a = string.Empty; c += a; a = null; b = null; b = ""test""; c = a?.ToString();|] return c ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string? c = {|Rename:NewMethod|}(ref a, ref b); return c ?? string.Empty; } private static string? NewMethod(ref string? a, ref string? b) { string? c = a + b; a = string.Empty; c += a; a = null; b = null; b = ""test""; c = a?.ToString(); return c; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters_MultipleStatesNonNullReturn() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = null; c = a + b;|] return c ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string? c = {|Rename:NewMethod|}(ref a, ref b); return c ?? string.Empty; } private static string NewMethod(ref string? a, ref string? b) { string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = null; c = a + b; return c; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters_MultipleStatesNullReturn() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = a?.ToString();|] return c ?? string.Empty; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string? c = {|Rename:NewMethod|}(ref a, ref b); return c ?? string.Empty; } private static string? NewMethod(ref string? a, ref string? b) { string? c = a + b; a = string.Empty; b = string.Empty; a = null; b = null; c = a?.ToString(); return c; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowStateNullableParameters_RefNotNull() => TestInRegularAndScript1Async( @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; [|var c = a + b; a = string.Empty; c += a; b = ""test""; c = a + b +c;|] return c; } }", @"#nullable enable class C { public string M() { string? a = string.Empty; string? b = string.Empty; string c = {|Rename:NewMethod|}(ref a, ref b); return c; } private static string NewMethod(ref string a, ref string b) { var c = a + b; a = string.Empty; c += a; b = ""test""; c = a + b + c; return c; } }"); // There's a case below where flow state correctly asseses that the variable // 'x' is non-null when returned. It's wasn't obvious when writing, but that's // due to the fact the line above it being executed as 'x.ToString()' would throw // an exception and the return statement would never be hit. The only way the return // statement gets executed is if the `x.ToString()` call succeeds, thus suggesting // that the value is indeed not null. [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowNullableReturn_NotNull1() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { [|string? x = null; x.ToString();|] return x; } }", @"#nullable enable class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; } private static string NewMethod() { string? x = null; x.ToString(); return x; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowNullableReturn_NotNull2() => TestInRegularAndScript1Async( @"#nullable enable class C { public string? M() { [|string? x = null; x?.ToString(); x = string.Empty;|] return x; } }", @"#nullable enable class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; } private static string NewMethod() { string? x = null; x?.ToString(); x = string.Empty; return x; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowNullable_Lambda() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { public string? M() { [|string? x = null; Action modifyXToNonNull = () => { x += x; }; modifyXToNonNull();|] return x; } }", @"#nullable enable using System; class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; } private static string? NewMethod() { string? x = null; Action modifyXToNonNull = () => { x += x; }; modifyXToNonNull(); return x; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestFlowNullable_LambdaWithReturn() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { public string? M() { [|string? x = null; Func<string?> returnNull = () => { return null; }; x = returnNull() ?? string.Empty;|] return x; } }", @"#nullable enable using System; class C { public string? M() { string? x = {|Rename:NewMethod|}(); return x; } private static string NewMethod() { string? x = null; Func<string?> returnNull = () => { return null; }; x = returnNull() ?? string.Empty; return x; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractReadOnlyMethod() { await TestInRegularAndScript1Async( @"struct S1 { readonly int M1() => 42; void Main() { [|int i = M1() + M1()|]; } }", @"struct S1 { readonly int M1() => 42; void Main() { {|Rename:NewMethod|}(); } private readonly void NewMethod() { int i = M1() + M1(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractReadOnlyMethodInReadOnlyStruct() { await TestInRegularAndScript1Async( @"readonly struct S1 { int M1() => 42; void Main() { [|int i = M1() + M1()|]; } }", @"readonly struct S1 { int M1() => 42; void Main() { {|Rename:NewMethod|}(); } private void NewMethod() { int i = M1() + M1(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractNonReadOnlyMethodInReadOnlyMethod() { await TestInRegularAndScript1Async( @"struct S1 { int M1() => 42; readonly void Main() { [|int i = M1() + M1()|]; } }", @"struct S1 { int M1() => 42; readonly void Main() { {|Rename:NewMethod|}(); } private void NewMethod() { int i = M1() + M1(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNullableObjectWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = null; var s = (string?)[|o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = null; var s = (string?){|Rename:GetO|}(o); Console.WriteLine(s); } private static object? GetO(object? o) { return o; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNotNullableObjectWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = new object(); var s = (string)[|o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = new object(); var s = (string){|Rename:GetO|}(o); Console.WriteLine(s); } private static object GetO(object o) { return o; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNotNullableWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = new B(); var s = (A)[|b|]; } }", @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = new B(); var s = (A){|Rename:GetB|}(b); } private static B GetB(B b) { return b; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNullableWithExplicitCast() => TestInRegularAndScript1Async( @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = null; var s = (A)[|b|]; } }", @"#nullable enable using System; class A { } class B : A { } class C { void M() { B? b = null; var s = (A){|Rename:GetB|}(b); } private static B? GetB(B? b) { return b; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNotNullableWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = new object(); var s = [|(string)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = new object(); var s = {|Rename:GetS|}(o); Console.WriteLine(s); } private static string GetS(object o) { return (string)o; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNullableWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = null; var s = [|(string?)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = null; var s = {|Rename:GetS|}(o); Console.WriteLine(s); } private static string? GetS(object? o) { return (string?)o; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNullableNonNullFlowWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = new object(); var s = [|(string?)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = new object(); var s = {|Rename:GetS|}(o); Console.WriteLine(s); } private static string? GetS(object o) { return (string?)o; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public Task TestExtractNullableToNonNullableWithExplicitCastSelected() => TestInRegularAndScript1Async( @"#nullable enable using System; class C { void M() { object? o = null; var s = [|(string)o|]; Console.WriteLine(s); } }", @"#nullable enable using System; class C { void M() { object? o = null; var s = {|Rename:GetS|}(o); Console.WriteLine(s); } private static string? GetS(object? o) { return (string)o; } }"); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task EnsureStaticLocalFunctionOptionHasNoEffect() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) { return b != true; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSuggestionEnforcement))); } [Fact, WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task ExtractLocalFunctionCallAndDeclaration() { await TestInRegularAndScript1Async(@" class C { public static void Main() { static void LocalParent() { [|void Local() { } Local();|] } } }", @" class C { public static void Main() { static void LocalParent() { {|Rename:NewMethod|}(); } } private static void NewMethod() { void Local() { } Local(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingWhenOnlyLocalFunctionCallSelected() { var code = @" class Program { static void Main(string[] args) { [|Local();|] static void Local() { } } }"; await TestExactActionSetOfferedAsync(code, new[] { FeaturesResources.Extract_local_function }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOfferedWhenBothLocalFunctionCallAndDeclarationSelected() { await TestInRegularAndScript1Async(@" class Program { static void Main(string[] args) { [|Local(); var test = 5; static void Local() { }|] } }", @" class Program { static void Main(string[] args) { {|Rename:NewMethod|}(); } private static void NewMethod() { Local(); var test = 5; static void Local() { } } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractNonAsyncMethodWithAsyncLocalFunction() { await TestInRegularAndScript1Async( @"class C { void M() { [|F(); async void F() => await Task.Delay(0);|] } }", @"class C { void M() { {|Rename:NewMethod|}(); } private static void NewMethod() { F(); async void F() => await Task.Delay(0); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitFalse() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(false)|]; } }", @"class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration).ConfigureAwait(false); } private static async System.Threading.Tasks.Task<object> NewMethod(TimeSpan duration) { return await Task.Delay(duration).ConfigureAwait(false); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitFalseNamedParameter() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(continueOnCapturedContext: false)|]; } }", @"class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration).ConfigureAwait(false); } private static async System.Threading.Tasks.Task<object> NewMethod(TimeSpan duration) { return await Task.Delay(duration).ConfigureAwait(continueOnCapturedContext: false); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitFalseOnNonTask() { await TestInRegularAndScript1Async( @"using System.Threading.Tasks class C { async Task MyDelay() { [|await new ValueTask<int>(0).ConfigureAwait(false)|]; } }", @"using System.Threading.Tasks class C { async Task MyDelay() { await {|Rename:NewMethod|}().ConfigureAwait(false); } private static async Task<object> NewMethod() { return await new ValueTask<int>(0).ConfigureAwait(false); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitTrue() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(true)|]; } }", @"class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration); } private static async System.Threading.Tasks.Task<object> NewMethod(TimeSpan duration) { return await Task.Delay(duration).ConfigureAwait(true); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitNonLiteral() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(M())|]; } }", @"class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration); } private static async System.Threading.Tasks.Task<object> NewMethod(TimeSpan duration) { return await Task.Delay(duration).ConfigureAwait(M()); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithNoConfigureAwait() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration)|]; } }", @"class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration); } private static async System.Threading.Tasks.Task<object> NewMethod(TimeSpan duration) { return await Task.Delay(duration); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitFalseInLambda() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Run(async () => await Task.Delay(duration).ConfigureAwait(false))|]; } }", @"class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration); } private static async System.Threading.Tasks.Task<object> NewMethod(TimeSpan duration) { return await Task.Run(async () => await Task.Delay(duration).ConfigureAwait(false)); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitFalseInLocalMethod() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Run(F()); async Task F() => await Task.Delay(duration).ConfigureAwait(false);|] } }", @"using System.Threading.Tasks; class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration); } private static async Task NewMethod(TimeSpan duration) { await Task.Run(F()); async Task F() => await Task.Delay(duration).ConfigureAwait(false); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitMixture1() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(false); await Task.Delay(duration).ConfigureAwait(true);|] } }", @"using System.Threading.Tasks; class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration).ConfigureAwait(false); } private static async Task NewMethod(TimeSpan duration) { await Task.Delay(duration).ConfigureAwait(false); await Task.Delay(duration).ConfigureAwait(true); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitMixture2() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(true); await Task.Delay(duration).ConfigureAwait(false);|] } }", @"using System.Threading.Tasks; class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration).ConfigureAwait(false); } private static async Task NewMethod(TimeSpan duration) { await Task.Delay(duration).ConfigureAwait(true); await Task.Delay(duration).ConfigureAwait(false); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitMixture3() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { [|await Task.Delay(duration).ConfigureAwait(M()); await Task.Delay(duration).ConfigureAwait(false);|] } }", @"using System.Threading.Tasks; class C { async Task MyDelay(TimeSpan duration) { await {|Rename:NewMethod|}(duration).ConfigureAwait(false); } private static async Task NewMethod(TimeSpan duration) { await Task.Delay(duration).ConfigureAwait(M()); await Task.Delay(duration).ConfigureAwait(false); } }"); } [Fact, WorkItem(38529, "https://github.com/dotnet/roslyn/issues/38529"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestExtractAsyncMethodWithConfigureAwaitFalseOutsideSelection() { await TestInRegularAndScript1Async( @"class C { async Task MyDelay(TimeSpan duration) { await Task.Delay(duration).ConfigureAwait(false); [|await Task.Delay(duration).ConfigureAwait(true);|] } }", @"using System.Threading.Tasks; class C { async Task MyDelay(TimeSpan duration) { await Task.Delay(duration).ConfigureAwait(false); await {|Rename:NewMethod|}(duration); } private static async Task NewMethod(TimeSpan duration) { await Task.Delay(duration).ConfigureAwait(true); } }"); } [Fact, WorkItem(40188, "https://github.com/dotnet/roslyn/issues/40188"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_True() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = true:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); } private static bool NewMethod() => true; } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = true:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected); } [Fact, WorkItem(40188, "https://github.com/dotnet/roslyn/issues/40188"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestEditorconfigSetting_ExpressionBodiedLocalFunction_False() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); } private static bool NewMethod() { return true; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestNaming_CamelCase_VerifyLocalFunctionSettingsDontApply() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class Program1 { static void Main() { [|bool b = true;|] System.Console.WriteLine(b != true ? b = true : b = false); } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_LocalFunctions_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { bool b = {|Rename:NewMethod|}(); System.Console.WriteLine(b != true ? b = true : b = false); } private static bool NewMethod() { return true; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_LocalFunctions_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected); } [Fact, WorkItem(40209, "https://github.com/dotnet/roslyn/issues/40209"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestNaming_CamelCase_VerifyLocalFunctionSettingsDontApply_GetName() { var input = @" <Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> class MethodExtraction { void TestMethod() { int a = [|1 + 1|]; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_LocalFunctions_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class MethodExtraction { void TestMethod() { int a = {|Rename:GetA|}(); } private static int GetA() { return 1 + 1; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">" + EditorConfigNaming_LocalFunctions_CamelCase + @" </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScript1Async(input, expected); } [WorkItem(40654, "https://github.com/dotnet/roslyn/issues/40654")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOnInvalidUsingStatement_MultipleStatements() { var input = @" class C { void M() { [|var v = 0; using System;|] } }"; var expected = @" class C { void M() { {|Rename:NewMethod|}(); } private static void NewMethod() { var v = 0; using System; } }"; await TestInRegularAndScript1Async(input, expected); } [WorkItem(40654, "https://github.com/dotnet/roslyn/issues/40654")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnInvalidUsingStatement() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|using System;|] } }"); } [Fact, WorkItem(19461, "https://github.com/dotnet/roslyn/issues/19461")] public async Task TestLocalFunction() { await TestInRegularAndScript1Async(@" using System; class Program { void M() { int y = 0; [|var x = local(); int local() { return y; }|] } }", @" using System; class Program { void M() { int y = 0; {|Rename:NewMethod|}(y); } private static void NewMethod(int y) { var x = local(); int local() { return y; } } }"); } [Fact, WorkItem(43834, "https://github.com/dotnet/roslyn/issues/43834")] public async Task TestRecursivePatternRewrite() { await TestInRegularAndScript1Async(@" using System; namespace N { class Context { } class C { public void DoAction(Action<Context> action) { } private void Recursive(object context) { DoAction(context => { if (context is Context { }) { DoAction( [|context =>|] context.ToString()); } }); } } }", @" using System; namespace N { class Context { } class C { public void DoAction(Action<Context> action) { } private void Recursive(object context) { DoAction(context => { if (context is Context { }) { DoAction( {|Rename:NewMethod|}()); } }); } private static Action<Context> NewMethod() { return context => context.ToString(); } } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess1() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?.[|ToString|](); } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static string NewMethod(List<int> b) { return b?.ToString(); } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess2() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?.[|ToString|]().Length; } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static int? NewMethod(List<int> b) { return b?.ToString().Length; } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess3() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?.Count.[|ToString|](); } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static string NewMethod(List<int> b) { return b?.Count.ToString(); } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess4() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?.[|Count|].ToString(); } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static string NewMethod(List<int> b) { return b?.Count.ToString(); } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess5() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?.[|ToString|]()?.ToString(); } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static string NewMethod(List<int> b) { return b?.ToString()?.ToString(); } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess6() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?.ToString()?.[|ToString|](); } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static string NewMethod(List<int> b) { return b?.ToString()?.ToString(); } }"); } [Fact, WorkItem(41895, "https://github.com/dotnet/roslyn/issues/41895")] public async Task TestConditionalAccess7() { await TestInRegularAndScript1Async(@" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = b?[|[0]|]; } }", @" using System; using System.Collections.Generic; class C { void Test() { List<int> b = null; b?.Clear(); _ = {|Rename:NewMethod|}(b); } private static int? NewMethod(List<int> b) { return b?[0]; } }"); } [WorkItem(48453, "https://github.com/dotnet/roslyn/issues/48453")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [InlineData("record")] [InlineData("record class")] public async Task TestInRecord(string record) { await TestInRegularAndScript1Async($@" {record} Program {{ int field; public int this[int i] => [|this.field|]; }}", $@" {record} Program {{ int field; public int this[int i] => {{|Rename:GetField|}}(); private int GetField() {{ return this.field; }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestInRecordStruct() { await TestInRegularAndScript1Async(@" record struct Program { int field; public int this[int i] => [|this.field|]; }", @" record struct Program { int field; public int this[int i] => {|Rename:GetField|}(); private readonly int GetField() { return this.field; } }"); } [WorkItem(53031, "https://github.com/dotnet/roslyn/issues/53031")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMethodInNamespace() { await TestMissingInRegularAndScriptAsync(@" namespace TestNamespace { private bool TestMethod() => [|false|]; }"); } [WorkItem(53031, "https://github.com/dotnet/roslyn/issues/53031")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMethodInInterface() { await TestInRegularAndScript1Async(@" interface TestInterface { bool TestMethod() => [|false|]; }", @" interface TestInterface { bool TestMethod() => {|Rename:NewMethod|}(); bool NewMethod() { return false; } }"); } } }
1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode> { private readonly SyntaxToken _methodName; private const string NewMethodPascalCaseStr = "NewMethod"; private const string NewMethodCamelCaseStr = "newMethod"; public static Task<GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult, options, localFunction); return codeGenerator.GenerateAsync(cancellationToken); } private static CSharpCodeGenerator Create( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) { if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult)) { return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult)) { return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult)) { return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } throw ExceptionUtilities.UnexpectedValue(selectionResult); } protected CSharpCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) : base(insertionPoint, selectionResult, analyzerResult, options, localFunction) { Contract.ThrowIfFalse(SemanticDocument == selectionResult.SemanticDocument); var nameToken = CreateMethodName(); _methodName = nameToken.WithAdditionalAnnotations(MethodNameAnnotation); } private CSharpSelectionResult CSharpSelectionResult { get { return (CSharpSelectionResult)SelectionResult; } } protected override SyntaxNode GetPreviousMember(SemanticDocument document) { var node = InsertionPoint.With(document).GetContext(); return (node.Parent is GlobalStatementSyntax) ? node.Parent : node; } protected override OperationStatus<IMethodSymbol> GenerateMethodDefinition(bool localFunction, CancellationToken cancellationToken) { var result = CreateMethodBody(cancellationToken); var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Private, modifiers: CreateMethodModifiers(), returnType: AnalyzerResult.ReturnType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: _methodName.ToString(), typeParameters: CreateMethodTypeParameters(), parameters: CreateMethodParameters(), statements: result.Data, methodKind: localFunction ? MethodKind.LocalFunction : MethodKind.Ordinary); return result.With( MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))); } protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken) { var container = GetOutermostCallSiteContainerToProcess(cancellationToken); var variableMapToRemove = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken); var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite(); var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite(); Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent); var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false); var callSiteGenerator = new CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert); return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation); } private async Task<ImmutableArray<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken) { var selectedNode = GetFirstStatementOrInitializerSelectedAtCallSite(); // field initializer, constructor initializer, expression bodied member case if (selectedNode is ConstructorInitializerSyntax || selectedNode is FieldDeclarationSyntax || IsExpressionBodiedMember(selectedNode) || IsExpressionBodiedAccessor(selectedNode)) { var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken).ConfigureAwait(false); return ImmutableArray.Create(statement); } // regular case var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(cancellationToken); statements = postProcessor.MergeDeclarationStatements(statements); statements = AddAssignmentStatementToCallSite(statements, cancellationToken); statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = AddReturnIfUnreachable(statements); return statements.CastArray<SyntaxNode>(); } private static bool IsExpressionBodiedMember(SyntaxNode node) => node is MemberDeclarationSyntax member && member.GetExpressionBody() != null; private static bool IsExpressionBodiedAccessor(SyntaxNode node) => node is AccessorDeclarationSyntax accessor && accessor.ExpressionBody != null; private SimpleNameSyntax CreateMethodNameForInvocation() { return AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0 ? (SimpleNameSyntax)SyntaxFactory.IdentifierName(_methodName) : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables())); } private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables() { Contract.ThrowIfTrue(AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0); // propagate any type variable used in extracted code var typeVariables = new List<TypeSyntax>(); foreach (var methodTypeParameter in AnalyzerResult.MethodTypeParametersInDeclaration) { typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name)); } return SyntaxFactory.SeparatedList(typeVariables); } protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken) { var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken); if (outmostVariable == null) { return null; } var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(SemanticDocument); var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>(); Contract.ThrowIfNull(declStatement); Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()); return declStatement.Parent; } private DeclarationModifiers CreateMethodModifiers() { var isUnsafe = CSharpSelectionResult.ShouldPutUnsafeModifier(); var isAsync = CSharpSelectionResult.ShouldPutAsyncModifier(); var isStatic = !AnalyzerResult.UseInstanceMember; var isReadOnly = AnalyzerResult.ShouldBeReadOnly; // Static local functions are only supported in C# 8.0 and later var languageVersion = ((CSharpParseOptions)SemanticDocument.SyntaxTree.Options).LanguageVersion; if (LocalFunction && (!Options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction).Value || languageVersion < LanguageVersion.CSharp8)) { isStatic = false; } return new DeclarationModifiers( isUnsafe: isUnsafe, isAsync: isAsync, isStatic: isStatic, isReadOnly: isReadOnly); } private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? SyntaxKind.RefKeyword : parameterBehavior == ParameterBehavior.Out ? SyntaxKind.OutKeyword : SyntaxKind.None; } private OperationStatus<ImmutableArray<SyntaxNode>> CreateMethodBody(CancellationToken cancellationToken) { var statements = GetInitialStatementsForMethodDefinitions(); statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken); statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken); statements = AppendReturnStatementIfNeeded(statements); statements = CleanupCode(statements); // set output so that we can use it in negative preview var wrapped = WrapInCheckStatementIfNeeded(statements); return CheckActiveStatements(statements).With(wrapped.ToImmutableArray<SyntaxNode>()); } private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements) { var kind = CSharpSelectionResult.UnderCheckedStatementContext(); if (kind == SyntaxKind.None) { return statements; } if (statements.Skip(1).Any()) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } if (statements.Single() is BlockSyntax block) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block)); } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } private static ImmutableArray<StatementSyntax> CleanupCode(ImmutableArray<StatementSyntax> statements) { statements = PostProcessor.RemoveRedundantBlock(statements); statements = PostProcessor.RemoveDeclarationAssignmentPattern(statements); statements = PostProcessor.RemoveInitializedDeclarationAndReturnPattern(statements); return statements; } private static OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements) { var count = statements.Count(); if (count == 0) { return OperationStatus.NoActiveStatement; } if (count == 1) { if (statements.Single() is ReturnStatementSyntax returnStatement && returnStatement.Expression == null) { return OperationStatus.NoActiveStatement; } } foreach (var statement in statements) { if (!(statement is LocalDeclarationStatementSyntax declStatement)) { return OperationStatus.Succeeded; } foreach (var variable in declStatement.Declaration.Variables) { if (variable.Initializer != null) { // found one return OperationStatus.Succeeded; } } } return OperationStatus.NoActiveStatement; } private ImmutableArray<StatementSyntax> MoveDeclarationOutFromMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { using var _ = ArrayBuilder<StatementSyntax>.GetInstance(out var result); var variableToRemoveMap = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken); statements = statements.SelectAsArray(s => FixDeclarationExpressionsAndDeclarationPatterns(s, variableToRemoveMap)); foreach (var statement in statements) { if (!(statement is LocalDeclarationStatementSyntax declarationStatement) || declarationStatement.Declaration.Variables.FullSpan.IsEmpty) { // if given statement is not decl statement. result.Add(statement); continue; } var expressionStatements = new List<StatementSyntax>(); var list = new List<VariableDeclaratorSyntax>(); var triviaList = new List<SyntaxTrivia>(); // When we modify the declaration to an initialization we have to preserve the leading trivia var firstVariableToAttachTrivia = true; // go through each var decls in decl statement, and create new assignment if // variable is initialized at decl. foreach (var variableDeclaration in declarationStatement.Declaration.Variables) { if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration)) { if (variableDeclaration.Initializer != null) { var identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration); // move comments with the variable here expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value)); } else { // we don't remove trivia around tokens we remove triviaList.AddRange(variableDeclaration.GetLeadingTrivia()); triviaList.AddRange(variableDeclaration.GetTrailingTrivia()); } firstVariableToAttachTrivia = false; continue; } // Prepend the trivia from the declarations without initialization to the next persisting variable declaration if (triviaList.Count > 0) { list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); firstVariableToAttachTrivia = false; continue; } firstVariableToAttachTrivia = false; list.Add(variableDeclaration); } if (list.Count == 0 && triviaList.Count > 0) { // well, there are trivia associated with the node. // we can't just delete the node since then, we will lose // the trivia. unfortunately, it is not easy to attach the trivia // to next token. for now, create an empty statement and associate the // trivia to the statement // TODO : think about a way to trivia attached to next token result.Add(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)))); triviaList.Clear(); } // return survived var decls if (list.Count > 0) { result.Add(SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, SyntaxFactory.VariableDeclaration( declarationStatement.Declaration.Type, SyntaxFactory.SeparatedList(list)), declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList))); triviaList.Clear(); } // return any expression statement if there was any result.AddRange(expressionStatements); } return result.ToImmutable(); } /// <summary> /// If the statement has an <c>out var</c> declaration expression for a variable which /// needs to be removed, we need to turn it into a plain <c>out</c> parameter, so that /// it doesn't declare a duplicate variable. /// If the statement has a pattern declaration (such as <c>3 is int i</c>) for a variable /// which needs to be removed, we will annotate it as a conflict, since we don't have /// a better refactoring. /// </summary> private static StatementSyntax FixDeclarationExpressionsAndDeclarationPatterns(StatementSyntax statement, HashSet<SyntaxAnnotation> variablesToRemove) { var replacements = new Dictionary<SyntaxNode, SyntaxNode>(); var declarations = statement.DescendantNodes() .Where(n => n.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.DeclarationPattern)); foreach (var node in declarations) { switch (node.Kind()) { case SyntaxKind.DeclarationExpression: { var declaration = (DeclarationExpressionSyntax)node; if (declaration.Designation.Kind() != SyntaxKind.SingleVariableDesignation) { break; } var designation = (SingleVariableDesignationSyntax)declaration.Designation; var name = designation.Identifier.ValueText; if (variablesToRemove.HasSyntaxAnnotation(designation)) { var newLeadingTrivia = new SyntaxTriviaList(); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetLeadingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetTrailingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(designation.GetLeadingTrivia()); replacements.Add(declaration, SyntaxFactory.IdentifierName(designation.Identifier) .WithLeadingTrivia(newLeadingTrivia)); } break; } case SyntaxKind.DeclarationPattern: { var pattern = (DeclarationPatternSyntax)node; if (!variablesToRemove.HasSyntaxAnnotation(pattern)) { break; } // We don't have a good refactoring for this, so we just annotate the conflict // For instance, when a local declared by a pattern declaration (`3 is int i`) is // used outside the block we're trying to extract. if (!(pattern.Designation is SingleVariableDesignationSyntax designation)) { break; } var identifier = designation.Identifier; var annotation = ConflictAnnotation.Create(CSharpFeaturesResources.Conflict_s_detected); var newIdentifier = identifier.WithAdditionalAnnotations(annotation); var newDesignation = designation.WithIdentifier(newIdentifier); replacements.Add(pattern, pattern.WithDesignation(newDesignation)); break; } } } return statement.ReplaceNodes(replacements.Keys, (orig, partiallyReplaced) => replacements[orig]); } private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable) { var identifier = variable.Identifier; var typeSyntax = declarationStatement.Declaration.Type; if (firstVariableToAttachTrivia && typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia); } return identifier; } private ImmutableArray<StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken); declStatements = postProcessor.MergeDeclarationStatements(declStatements); return declStatements.Concat(statements); } private static ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(identifier), rvalue); } protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() { var lastStatement = GetLastStatementOrInitializerSelectedAtCallSite(); var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { // case such as field initializer return false; } var blockBody = container.GetBlockBody(); if (blockBody == null) { // such as expression lambda. there is no statement return false; } // check whether it is last statement except return statement var statements = blockBody.Statements; if (statements.Last() == lastStatement) { return true; } var index = statements.IndexOf((StatementSyntax)lastStatement); return statements[index + 1].Kind() == SyntaxKind.ReturnStatement; } protected override SyntaxToken CreateIdentifier(string name) => SyntaxFactory.Identifier(name); protected override StatementSyntax CreateReturnStatement(string identifierName = null) { return string.IsNullOrEmpty(identifierName) ? SyntaxFactory.ReturnStatement() : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName)); } protected override ExpressionSyntax CreateCallSignature() { var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation); var arguments = new List<ArgumentSyntax>(); foreach (var argument in AnalyzerResult.MethodParameters) { var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier); var refOrOut = modifier == SyntaxKind.None ? default : SyntaxFactory.Token(modifier); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut)); } var invocation = SyntaxFactory.InvocationExpression(methodName, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); var shouldPutAsyncModifier = CSharpSelectionResult.ShouldPutAsyncModifier(); if (!shouldPutAsyncModifier) { return invocation; } if (CSharpSelectionResult.ShouldCallConfigureAwaitFalse()) { if (AnalyzerResult.ReturnType.GetMembers().Any(x => x is IMethodSymbol { Name: nameof(Task.ConfigureAwait), Parameters: { Length: 1 } parameters } && parameters[0].Type.SpecialType == SpecialType.System_Boolean)) { invocation = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, invocation, SyntaxFactory.IdentifierName(nameof(Task.ConfigureAwait))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression))))); } } return SyntaxFactory.AwaitExpression(invocation); } protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue) => SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); protected override StatementSyntax CreateDeclarationStatement( VariableInfo variable, ExpressionSyntax initialValue, CancellationToken cancellationToken) { var type = variable.GetVariableType(SemanticDocument); var typeNode = type.GenerateTypeSyntax(); var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue); return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(typeNode) .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause))); } protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { if (status.Succeeded()) { // in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. // here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out // indentation of inserted statements (from users code) with user code style preserved var root = newDocument.Root; var methodDefinition = root.GetAnnotatedNodes<SyntaxNode>(MethodDefinitionAnnotation).First(); #pragma warning disable IDE0007 // Use implicit type (False positive: https://github.com/dotnet/roslyn/issues/44507) SyntaxNode newMethodDefinition = methodDefinition switch #pragma warning restore IDE0007 // Use implicit type { MethodDeclarationSyntax method => TweakNewLinesInMethod(method), LocalFunctionStatementSyntax localFunction => TweakNewLinesInMethod(localFunction), _ => throw new NotSupportedException("SyntaxNode expected to be MethodDeclarationSyntax or LocalFunctionStatementSyntax."), }; newDocument = await newDocument.WithSyntaxRootAsync( root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false); } return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false); } private static MethodDeclarationSyntax TweakNewLinesInMethod(MethodDeclarationSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static LocalFunctionStatementSyntax TweakNewLinesInMethod(LocalFunctionStatementSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static TDeclarationNode TweakNewLinesInMethod<TDeclarationNode>(TDeclarationNode method, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody) where TDeclarationNode : SyntaxNode { if (body != null) { return method.ReplaceToken( body.OpenBraceToken, body.OpenBraceToken.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else if (expressionBody != null) { return method.ReplaceToken( expressionBody.ArrowToken, expressionBody.ArrowToken.WithPrependedLeadingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else { return method; } } protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker() { var callSignature = CreateCallSignature(); if (AnalyzerResult.HasReturnType) { Contract.ThrowIfTrue(AnalyzerResult.HasVariableToUseAsReturnValue); return SyntaxFactory.ReturnStatement(callSignature); } return SyntaxFactory.ExpressionStatement(callSignature); } protected override async Task<SemanticDocument> UpdateMethodAfterGenerationAsync( SemanticDocument originalDocument, OperationStatus<IMethodSymbol> methodSymbolResult, CancellationToken cancellationToken) { // Only need to update for nullable reference types in return if (methodSymbolResult.Data.ReturnType.NullableAnnotation != NullableAnnotation.Annotated) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var syntaxNode = originalDocument.Root.GetAnnotatedNodesAndTokens(MethodDefinitionAnnotation).FirstOrDefault().AsNode(); var nodeIsMethodOrLocalFunction = syntaxNode is MethodDeclarationSyntax || syntaxNode is LocalFunctionStatementSyntax; if (!nodeIsMethodOrLocalFunction) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var nullableReturnOperations = await CheckReturnOperations(syntaxNode, methodSymbolResult, originalDocument, cancellationToken).ConfigureAwait(false); if (nullableReturnOperations is object) { return nullableReturnOperations; } var returnType = syntaxNode is MethodDeclarationSyntax method ? method.ReturnType : ((LocalFunctionStatementSyntax)syntaxNode).ReturnType; var newDocument = await GenerateNewDocument(methodSymbolResult, returnType, originalDocument, cancellationToken).ConfigureAwait(false); return await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); static bool ReturnOperationBelongsToMethod(SyntaxNode returnOperationSyntax, SyntaxNode methodSyntax) { var enclosingMethod = returnOperationSyntax.FirstAncestorOrSelf<SyntaxNode>(n => n switch { BaseMethodDeclarationSyntax _ => true, AnonymousFunctionExpressionSyntax _ => true, LocalFunctionStatementSyntax _ => true, _ => false }); return enclosingMethod == methodSyntax; } async Task<SemanticDocument> CheckReturnOperations( SyntaxNode node, OperationStatus<IMethodSymbol> methodSymbolResult, SemanticDocument originalDocument, CancellationToken cancellationToken) { var semanticModel = originalDocument.SemanticModel; var methodOperation = semanticModel.GetOperation(node, cancellationToken); var returnOperations = methodOperation.DescendantsAndSelf().OfType<IReturnOperation>(); foreach (var returnOperation in returnOperations) { // If the return statement is located in a nested local function or lambda it // shouldn't contribute to the nullability of the extracted method's return type if (!ReturnOperationBelongsToMethod(returnOperation.Syntax, methodOperation.Syntax)) { continue; } var syntax = returnOperation.ReturnedValue?.Syntax ?? returnOperation.Syntax; var returnTypeInfo = semanticModel.GetTypeInfo(syntax, cancellationToken); if (returnTypeInfo.Nullability.FlowState == NullableFlowState.MaybeNull) { // Flow state shows that return is correctly nullable return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } } return null; } static async Task<Document> GenerateNewDocument( OperationStatus<IMethodSymbol> methodSymbolResult, TypeSyntax returnType, SemanticDocument originalDocument, CancellationToken cancellationToken) { // Return type can be updated to not be null var newType = methodSymbolResult.Data.ReturnType.WithNullableAnnotation(NullableAnnotation.NotAnnotated); var oldRoot = await originalDocument.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = oldRoot.ReplaceNode(returnType, newType.GenerateTypeSyntax()); return originalDocument.Document.WithSyntaxRoot(newRoot); } } protected SyntaxToken GenerateMethodNameForStatementGenerators() { var semanticModel = SemanticDocument.SemanticModel; var nameGenerator = new UniqueNameGenerator(semanticModel); var scope = CSharpSelectionResult.GetContainingScope(); // If extracting a local function, we want to ensure all local variables are considered when generating a unique name. if (LocalFunction) { scope = CSharpSelectionResult.GetFirstTokenInSelection().Parent; } return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(scope, GenerateMethodNameFromUserPreference())); } protected string GenerateMethodNameFromUserPreference() { var methodName = NewMethodPascalCaseStr; if (!LocalFunction) { return methodName; } // For local functions, pascal case and camel case should be the most common and therefore we only consider those cases. var namingPreferences = Options.GetOption(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp); var localFunctionPreferences = namingPreferences.SymbolSpecifications.Where(symbol => symbol.AppliesTo(new SymbolKindOrTypeKind(MethodKind.LocalFunction), CreateMethodModifiers(), null)); var namingRules = namingPreferences.Rules.NamingRules; var localFunctionKind = new SymbolKindOrTypeKind(MethodKind.LocalFunction); if (LocalFunction) { if (namingRules.Any(rule => rule.NamingStyle.CapitalizationScheme.Equals(Capitalization.CamelCase) && rule.SymbolSpecification.AppliesTo(localFunctionKind, CreateMethodModifiers(), null))) { methodName = NewMethodCamelCaseStr; } } // We default to pascal case. return methodName; } } } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode> { private readonly SyntaxToken _methodName; private const string NewMethodPascalCaseStr = "NewMethod"; private const string NewMethodCamelCaseStr = "newMethod"; public static Task<GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult, options, localFunction); return codeGenerator.GenerateAsync(cancellationToken); } private static CSharpCodeGenerator Create( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) { if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult)) { return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult)) { return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult)) { return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } throw ExceptionUtilities.UnexpectedValue(selectionResult); } protected CSharpCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) : base(insertionPoint, selectionResult, analyzerResult, options, localFunction) { Contract.ThrowIfFalse(SemanticDocument == selectionResult.SemanticDocument); var nameToken = CreateMethodName(); _methodName = nameToken.WithAdditionalAnnotations(MethodNameAnnotation); } private CSharpSelectionResult CSharpSelectionResult { get { return (CSharpSelectionResult)SelectionResult; } } protected override SyntaxNode GetPreviousMember(SemanticDocument document) { var node = InsertionPoint.With(document).GetContext(); return (node.Parent is GlobalStatementSyntax) ? node.Parent : node; } protected override OperationStatus<IMethodSymbol> GenerateMethodDefinition(bool localFunction, CancellationToken cancellationToken) { var result = CreateMethodBody(cancellationToken); var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Private, modifiers: CreateMethodModifiers(), returnType: AnalyzerResult.ReturnType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: _methodName.ToString(), typeParameters: CreateMethodTypeParameters(), parameters: CreateMethodParameters(), statements: result.Data, methodKind: localFunction ? MethodKind.LocalFunction : MethodKind.Ordinary); return result.With( MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))); } protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken) { var container = GetOutermostCallSiteContainerToProcess(cancellationToken); var variableMapToRemove = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken); var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite(); var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite(); Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent); var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false); var callSiteGenerator = new CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert); return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation); } private async Task<ImmutableArray<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken) { var selectedNode = GetFirstStatementOrInitializerSelectedAtCallSite(); // field initializer, constructor initializer, expression bodied member case if (selectedNode is ConstructorInitializerSyntax || selectedNode is FieldDeclarationSyntax || IsExpressionBodiedMember(selectedNode) || IsExpressionBodiedAccessor(selectedNode)) { var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken).ConfigureAwait(false); return ImmutableArray.Create(statement); } // regular case var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(cancellationToken); statements = postProcessor.MergeDeclarationStatements(statements); statements = AddAssignmentStatementToCallSite(statements, cancellationToken); statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = AddReturnIfUnreachable(statements); return statements.CastArray<SyntaxNode>(); } protected override bool ShouldLocalFunctionCaptureParameter(SyntaxNode node) => ((CSharpParseOptions)node.SyntaxTree.Options).LanguageVersion < LanguageVersion.CSharp8; private static bool IsExpressionBodiedMember(SyntaxNode node) => node is MemberDeclarationSyntax member && member.GetExpressionBody() != null; private static bool IsExpressionBodiedAccessor(SyntaxNode node) => node is AccessorDeclarationSyntax accessor && accessor.ExpressionBody != null; private SimpleNameSyntax CreateMethodNameForInvocation() { return AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0 ? (SimpleNameSyntax)SyntaxFactory.IdentifierName(_methodName) : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables())); } private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables() { Contract.ThrowIfTrue(AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0); // propagate any type variable used in extracted code var typeVariables = new List<TypeSyntax>(); foreach (var methodTypeParameter in AnalyzerResult.MethodTypeParametersInDeclaration) { typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name)); } return SyntaxFactory.SeparatedList(typeVariables); } protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken) { var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken); if (outmostVariable == null) { return null; } var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(SemanticDocument); var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>(); Contract.ThrowIfNull(declStatement); Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()); return declStatement.Parent; } private DeclarationModifiers CreateMethodModifiers() { var isUnsafe = CSharpSelectionResult.ShouldPutUnsafeModifier(); var isAsync = CSharpSelectionResult.ShouldPutAsyncModifier(); var isStatic = !AnalyzerResult.UseInstanceMember; var isReadOnly = AnalyzerResult.ShouldBeReadOnly; // Static local functions are only supported in C# 8.0 and later var languageVersion = ((CSharpParseOptions)SemanticDocument.SyntaxTree.Options).LanguageVersion; if (LocalFunction && (!Options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction).Value || languageVersion < LanguageVersion.CSharp8)) { isStatic = false; } return new DeclarationModifiers( isUnsafe: isUnsafe, isAsync: isAsync, isStatic: isStatic, isReadOnly: isReadOnly); } private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? SyntaxKind.RefKeyword : parameterBehavior == ParameterBehavior.Out ? SyntaxKind.OutKeyword : SyntaxKind.None; } private OperationStatus<ImmutableArray<SyntaxNode>> CreateMethodBody(CancellationToken cancellationToken) { var statements = GetInitialStatementsForMethodDefinitions(); statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken); statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken); statements = AppendReturnStatementIfNeeded(statements); statements = CleanupCode(statements); // set output so that we can use it in negative preview var wrapped = WrapInCheckStatementIfNeeded(statements); return CheckActiveStatements(statements).With(wrapped.ToImmutableArray<SyntaxNode>()); } private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements) { var kind = CSharpSelectionResult.UnderCheckedStatementContext(); if (kind == SyntaxKind.None) { return statements; } if (statements.Skip(1).Any()) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } if (statements.Single() is BlockSyntax block) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block)); } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } private static ImmutableArray<StatementSyntax> CleanupCode(ImmutableArray<StatementSyntax> statements) { statements = PostProcessor.RemoveRedundantBlock(statements); statements = PostProcessor.RemoveDeclarationAssignmentPattern(statements); statements = PostProcessor.RemoveInitializedDeclarationAndReturnPattern(statements); return statements; } private static OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements) { var count = statements.Count(); if (count == 0) { return OperationStatus.NoActiveStatement; } if (count == 1) { if (statements.Single() is ReturnStatementSyntax returnStatement && returnStatement.Expression == null) { return OperationStatus.NoActiveStatement; } } foreach (var statement in statements) { if (!(statement is LocalDeclarationStatementSyntax declStatement)) { return OperationStatus.Succeeded; } foreach (var variable in declStatement.Declaration.Variables) { if (variable.Initializer != null) { // found one return OperationStatus.Succeeded; } } } return OperationStatus.NoActiveStatement; } private ImmutableArray<StatementSyntax> MoveDeclarationOutFromMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { using var _ = ArrayBuilder<StatementSyntax>.GetInstance(out var result); var variableToRemoveMap = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken); statements = statements.SelectAsArray(s => FixDeclarationExpressionsAndDeclarationPatterns(s, variableToRemoveMap)); foreach (var statement in statements) { if (!(statement is LocalDeclarationStatementSyntax declarationStatement) || declarationStatement.Declaration.Variables.FullSpan.IsEmpty) { // if given statement is not decl statement. result.Add(statement); continue; } var expressionStatements = new List<StatementSyntax>(); var list = new List<VariableDeclaratorSyntax>(); var triviaList = new List<SyntaxTrivia>(); // When we modify the declaration to an initialization we have to preserve the leading trivia var firstVariableToAttachTrivia = true; // go through each var decls in decl statement, and create new assignment if // variable is initialized at decl. foreach (var variableDeclaration in declarationStatement.Declaration.Variables) { if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration)) { if (variableDeclaration.Initializer != null) { var identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration); // move comments with the variable here expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value)); } else { // we don't remove trivia around tokens we remove triviaList.AddRange(variableDeclaration.GetLeadingTrivia()); triviaList.AddRange(variableDeclaration.GetTrailingTrivia()); } firstVariableToAttachTrivia = false; continue; } // Prepend the trivia from the declarations without initialization to the next persisting variable declaration if (triviaList.Count > 0) { list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); firstVariableToAttachTrivia = false; continue; } firstVariableToAttachTrivia = false; list.Add(variableDeclaration); } if (list.Count == 0 && triviaList.Count > 0) { // well, there are trivia associated with the node. // we can't just delete the node since then, we will lose // the trivia. unfortunately, it is not easy to attach the trivia // to next token. for now, create an empty statement and associate the // trivia to the statement // TODO : think about a way to trivia attached to next token result.Add(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)))); triviaList.Clear(); } // return survived var decls if (list.Count > 0) { result.Add(SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, SyntaxFactory.VariableDeclaration( declarationStatement.Declaration.Type, SyntaxFactory.SeparatedList(list)), declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList))); triviaList.Clear(); } // return any expression statement if there was any result.AddRange(expressionStatements); } return result.ToImmutable(); } /// <summary> /// If the statement has an <c>out var</c> declaration expression for a variable which /// needs to be removed, we need to turn it into a plain <c>out</c> parameter, so that /// it doesn't declare a duplicate variable. /// If the statement has a pattern declaration (such as <c>3 is int i</c>) for a variable /// which needs to be removed, we will annotate it as a conflict, since we don't have /// a better refactoring. /// </summary> private static StatementSyntax FixDeclarationExpressionsAndDeclarationPatterns(StatementSyntax statement, HashSet<SyntaxAnnotation> variablesToRemove) { var replacements = new Dictionary<SyntaxNode, SyntaxNode>(); var declarations = statement.DescendantNodes() .Where(n => n.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.DeclarationPattern)); foreach (var node in declarations) { switch (node.Kind()) { case SyntaxKind.DeclarationExpression: { var declaration = (DeclarationExpressionSyntax)node; if (declaration.Designation.Kind() != SyntaxKind.SingleVariableDesignation) { break; } var designation = (SingleVariableDesignationSyntax)declaration.Designation; var name = designation.Identifier.ValueText; if (variablesToRemove.HasSyntaxAnnotation(designation)) { var newLeadingTrivia = new SyntaxTriviaList(); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetLeadingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetTrailingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(designation.GetLeadingTrivia()); replacements.Add(declaration, SyntaxFactory.IdentifierName(designation.Identifier) .WithLeadingTrivia(newLeadingTrivia)); } break; } case SyntaxKind.DeclarationPattern: { var pattern = (DeclarationPatternSyntax)node; if (!variablesToRemove.HasSyntaxAnnotation(pattern)) { break; } // We don't have a good refactoring for this, so we just annotate the conflict // For instance, when a local declared by a pattern declaration (`3 is int i`) is // used outside the block we're trying to extract. if (!(pattern.Designation is SingleVariableDesignationSyntax designation)) { break; } var identifier = designation.Identifier; var annotation = ConflictAnnotation.Create(CSharpFeaturesResources.Conflict_s_detected); var newIdentifier = identifier.WithAdditionalAnnotations(annotation); var newDesignation = designation.WithIdentifier(newIdentifier); replacements.Add(pattern, pattern.WithDesignation(newDesignation)); break; } } } return statement.ReplaceNodes(replacements.Keys, (orig, partiallyReplaced) => replacements[orig]); } private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable) { var identifier = variable.Identifier; var typeSyntax = declarationStatement.Declaration.Type; if (firstVariableToAttachTrivia && typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia); } return identifier; } private ImmutableArray<StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken); declStatements = postProcessor.MergeDeclarationStatements(declStatements); return declStatements.Concat(statements); } private static ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(identifier), rvalue); } protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() { var lastStatement = GetLastStatementOrInitializerSelectedAtCallSite(); var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { // case such as field initializer return false; } var blockBody = container.GetBlockBody(); if (blockBody == null) { // such as expression lambda. there is no statement return false; } // check whether it is last statement except return statement var statements = blockBody.Statements; if (statements.Last() == lastStatement) { return true; } var index = statements.IndexOf((StatementSyntax)lastStatement); return statements[index + 1].Kind() == SyntaxKind.ReturnStatement; } protected override SyntaxToken CreateIdentifier(string name) => SyntaxFactory.Identifier(name); protected override StatementSyntax CreateReturnStatement(string identifierName = null) { return string.IsNullOrEmpty(identifierName) ? SyntaxFactory.ReturnStatement() : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName)); } protected override ExpressionSyntax CreateCallSignature() { var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation); var arguments = new List<ArgumentSyntax>(); var isLocalFunction = LocalFunction && ShouldLocalFunctionCaptureParameter(SemanticDocument.Root); foreach (var argument in AnalyzerResult.MethodParameters) { if (!isLocalFunction || !argument.CanBeCapturedByLocalFunction) { var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier); var refOrOut = modifier == SyntaxKind.None ? default : SyntaxFactory.Token(modifier); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut)); } } var invocation = SyntaxFactory.InvocationExpression(methodName, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); var shouldPutAsyncModifier = CSharpSelectionResult.ShouldPutAsyncModifier(); if (!shouldPutAsyncModifier) { return invocation; } if (CSharpSelectionResult.ShouldCallConfigureAwaitFalse()) { if (AnalyzerResult.ReturnType.GetMembers().Any(x => x is IMethodSymbol { Name: nameof(Task.ConfigureAwait), Parameters: { Length: 1 } parameters } && parameters[0].Type.SpecialType == SpecialType.System_Boolean)) { invocation = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, invocation, SyntaxFactory.IdentifierName(nameof(Task.ConfigureAwait))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression))))); } } return SyntaxFactory.AwaitExpression(invocation); } protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue) => SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); protected override StatementSyntax CreateDeclarationStatement( VariableInfo variable, ExpressionSyntax initialValue, CancellationToken cancellationToken) { var type = variable.GetVariableType(SemanticDocument); var typeNode = type.GenerateTypeSyntax(); var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue); return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(typeNode) .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause))); } protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { if (status.Succeeded()) { // in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. // here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out // indentation of inserted statements (from users code) with user code style preserved var root = newDocument.Root; var methodDefinition = root.GetAnnotatedNodes<SyntaxNode>(MethodDefinitionAnnotation).First(); #pragma warning disable IDE0007 // Use implicit type (False positive: https://github.com/dotnet/roslyn/issues/44507) SyntaxNode newMethodDefinition = methodDefinition switch #pragma warning restore IDE0007 // Use implicit type { MethodDeclarationSyntax method => TweakNewLinesInMethod(method), LocalFunctionStatementSyntax localFunction => TweakNewLinesInMethod(localFunction), _ => throw new NotSupportedException("SyntaxNode expected to be MethodDeclarationSyntax or LocalFunctionStatementSyntax."), }; newDocument = await newDocument.WithSyntaxRootAsync( root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false); } return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false); } private static MethodDeclarationSyntax TweakNewLinesInMethod(MethodDeclarationSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static LocalFunctionStatementSyntax TweakNewLinesInMethod(LocalFunctionStatementSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static TDeclarationNode TweakNewLinesInMethod<TDeclarationNode>(TDeclarationNode method, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody) where TDeclarationNode : SyntaxNode { if (body != null) { return method.ReplaceToken( body.OpenBraceToken, body.OpenBraceToken.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else if (expressionBody != null) { return method.ReplaceToken( expressionBody.ArrowToken, expressionBody.ArrowToken.WithPrependedLeadingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else { return method; } } protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker() { var callSignature = CreateCallSignature(); if (AnalyzerResult.HasReturnType) { Contract.ThrowIfTrue(AnalyzerResult.HasVariableToUseAsReturnValue); return SyntaxFactory.ReturnStatement(callSignature); } return SyntaxFactory.ExpressionStatement(callSignature); } protected override async Task<SemanticDocument> UpdateMethodAfterGenerationAsync( SemanticDocument originalDocument, OperationStatus<IMethodSymbol> methodSymbolResult, CancellationToken cancellationToken) { // Only need to update for nullable reference types in return if (methodSymbolResult.Data.ReturnType.NullableAnnotation != NullableAnnotation.Annotated) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var syntaxNode = originalDocument.Root.GetAnnotatedNodesAndTokens(MethodDefinitionAnnotation).FirstOrDefault().AsNode(); var nodeIsMethodOrLocalFunction = syntaxNode is MethodDeclarationSyntax || syntaxNode is LocalFunctionStatementSyntax; if (!nodeIsMethodOrLocalFunction) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var nullableReturnOperations = await CheckReturnOperations(syntaxNode, methodSymbolResult, originalDocument, cancellationToken).ConfigureAwait(false); if (nullableReturnOperations is object) { return nullableReturnOperations; } var returnType = syntaxNode is MethodDeclarationSyntax method ? method.ReturnType : ((LocalFunctionStatementSyntax)syntaxNode).ReturnType; var newDocument = await GenerateNewDocument(methodSymbolResult, returnType, originalDocument, cancellationToken).ConfigureAwait(false); return await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); static bool ReturnOperationBelongsToMethod(SyntaxNode returnOperationSyntax, SyntaxNode methodSyntax) { var enclosingMethod = returnOperationSyntax.FirstAncestorOrSelf<SyntaxNode>(n => n switch { BaseMethodDeclarationSyntax _ => true, AnonymousFunctionExpressionSyntax _ => true, LocalFunctionStatementSyntax _ => true, _ => false }); return enclosingMethod == methodSyntax; } async Task<SemanticDocument> CheckReturnOperations( SyntaxNode node, OperationStatus<IMethodSymbol> methodSymbolResult, SemanticDocument originalDocument, CancellationToken cancellationToken) { var semanticModel = originalDocument.SemanticModel; var methodOperation = semanticModel.GetOperation(node, cancellationToken); var returnOperations = methodOperation.DescendantsAndSelf().OfType<IReturnOperation>(); foreach (var returnOperation in returnOperations) { // If the return statement is located in a nested local function or lambda it // shouldn't contribute to the nullability of the extracted method's return type if (!ReturnOperationBelongsToMethod(returnOperation.Syntax, methodOperation.Syntax)) { continue; } var syntax = returnOperation.ReturnedValue?.Syntax ?? returnOperation.Syntax; var returnTypeInfo = semanticModel.GetTypeInfo(syntax, cancellationToken); if (returnTypeInfo.Nullability.FlowState == NullableFlowState.MaybeNull) { // Flow state shows that return is correctly nullable return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } } return null; } static async Task<Document> GenerateNewDocument( OperationStatus<IMethodSymbol> methodSymbolResult, TypeSyntax returnType, SemanticDocument originalDocument, CancellationToken cancellationToken) { // Return type can be updated to not be null var newType = methodSymbolResult.Data.ReturnType.WithNullableAnnotation(NullableAnnotation.NotAnnotated); var oldRoot = await originalDocument.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = oldRoot.ReplaceNode(returnType, newType.GenerateTypeSyntax()); return originalDocument.Document.WithSyntaxRoot(newRoot); } } protected SyntaxToken GenerateMethodNameForStatementGenerators() { var semanticModel = SemanticDocument.SemanticModel; var nameGenerator = new UniqueNameGenerator(semanticModel); var scope = CSharpSelectionResult.GetContainingScope(); // If extracting a local function, we want to ensure all local variables are considered when generating a unique name. if (LocalFunction) { scope = CSharpSelectionResult.GetFirstTokenInSelection().Parent; } return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(scope, GenerateMethodNameFromUserPreference())); } protected string GenerateMethodNameFromUserPreference() { var methodName = NewMethodPascalCaseStr; if (!LocalFunction) { return methodName; } // For local functions, pascal case and camel case should be the most common and therefore we only consider those cases. var namingPreferences = Options.GetOption(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp); var localFunctionPreferences = namingPreferences.SymbolSpecifications.Where(symbol => symbol.AppliesTo(new SymbolKindOrTypeKind(MethodKind.LocalFunction), CreateMethodModifiers(), null)); var namingRules = namingPreferences.Rules.NamingRules; var localFunctionKind = new SymbolKindOrTypeKind(MethodKind.LocalFunction); if (LocalFunction) { if (namingRules.Any(rule => rule.NamingStyle.CapitalizationScheme.Equals(Capitalization.CamelCase) && rule.SymbolSpecification.AppliesTo(localFunctionKind, CreateMethodModifiers(), null))) { methodName = NewMethodCamelCaseStr; } } // We default to pascal case. return methodName; } } } }
1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/Core/Portable/ExtractMethod/MethodExtractor.CodeGenerator.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected abstract partial class CodeGenerator<TStatement, TExpression, TNodeUnderContainer> where TStatement : SyntaxNode where TExpression : SyntaxNode where TNodeUnderContainer : SyntaxNode { protected readonly SyntaxAnnotation MethodNameAnnotation; protected readonly SyntaxAnnotation MethodDefinitionAnnotation; protected readonly SyntaxAnnotation CallSiteAnnotation; protected readonly InsertionPoint InsertionPoint; protected readonly SemanticDocument SemanticDocument; protected readonly SelectionResult SelectionResult; protected readonly AnalyzerResult AnalyzerResult; protected readonly OptionSet Options; protected readonly bool LocalFunction; protected CodeGenerator(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options = null, bool localFunction = false) { Contract.ThrowIfFalse(insertionPoint.SemanticDocument == analyzerResult.SemanticDocument); InsertionPoint = insertionPoint; SemanticDocument = insertionPoint.SemanticDocument; SelectionResult = selectionResult; AnalyzerResult = analyzerResult; Options = options; LocalFunction = localFunction; MethodNameAnnotation = new SyntaxAnnotation(); CallSiteAnnotation = new SyntaxAnnotation(); MethodDefinitionAnnotation = new SyntaxAnnotation(); } #region method to be implemented in sub classes protected abstract SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken); protected abstract Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken); protected abstract SyntaxNode GetPreviousMember(SemanticDocument document); protected abstract OperationStatus<IMethodSymbol> GenerateMethodDefinition(bool localFunction, CancellationToken cancellationToken); protected abstract SyntaxToken CreateIdentifier(string name); protected abstract SyntaxToken CreateMethodName(); protected abstract bool LastStatementOrHasReturnStatementInReturnableConstruct(); protected abstract TNodeUnderContainer GetFirstStatementOrInitializerSelectedAtCallSite(); protected abstract TNodeUnderContainer GetLastStatementOrInitializerSelectedAtCallSite(); protected abstract Task<TNodeUnderContainer> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken); protected abstract TExpression CreateCallSignature(); protected abstract TStatement CreateDeclarationStatement(VariableInfo variable, TExpression initialValue, CancellationToken cancellationToken); protected abstract TStatement CreateAssignmentExpressionStatement(SyntaxToken identifier, TExpression rvalue); protected abstract TStatement CreateReturnStatement(string identifierName = null); protected abstract ImmutableArray<TStatement> GetInitialStatementsForMethodDefinitions(); #endregion public async Task<GeneratedCode> GenerateAsync(CancellationToken cancellationToken) { var root = SemanticDocument.Root; // should I check venus hidden position check here as well? root = root.ReplaceNode(GetOutermostCallSiteContainerToProcess(cancellationToken), await GenerateBodyForCallSiteContainerAsync(cancellationToken).ConfigureAwait(false)); var callSiteDocument = await SemanticDocument.WithSyntaxRootAsync(root, cancellationToken).ConfigureAwait(false); var newCallSiteRoot = callSiteDocument.Root; var codeGenerationService = SemanticDocument.Document.GetLanguageService<ICodeGenerationService>(); var result = GenerateMethodDefinition(LocalFunction, cancellationToken); SyntaxNode destination, newContainer; if (LocalFunction) { destination = InsertionPoint.With(callSiteDocument).GetContext(); // No valid location to insert the new method call. if (destination == null) { return await CreateGeneratedCodeAsync( OperationStatus.NoValidLocationToInsertMethodCall, callSiteDocument, cancellationToken).ConfigureAwait(false); } var localMethod = codeGenerationService.CreateMethodDeclaration( method: result.Data, options: new CodeGenerationOptions(generateDefaultAccessibility: false, generateMethodBodies: true, options: Options, parseOptions: destination?.SyntaxTree.Options)); newContainer = codeGenerationService.AddStatements(destination, new[] { localMethod }, cancellationToken: cancellationToken); } else { var previousMemberNode = GetPreviousMember(callSiteDocument); // it is possible in a script file case where there is no previous member. in that case, insert new text into top level script destination = previousMemberNode.Parent ?? previousMemberNode; newContainer = codeGenerationService.AddMethod( destination, result.Data, new CodeGenerationOptions(afterThisLocation: previousMemberNode.GetLocation(), generateDefaultAccessibility: true, generateMethodBodies: true, options: Options), cancellationToken); } var newSyntaxRoot = newCallSiteRoot.ReplaceNode(destination, newContainer); var newDocument = callSiteDocument.Document.WithSyntaxRoot(newSyntaxRoot); newDocument = await Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, null, cancellationToken).ConfigureAwait(false); var generatedDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); // For nullable reference types, we can provide a better experience by reducing use // of nullable reference types after a method is done being generated. If we can // determine that the method never returns null, for example, then we can // make the signature into a non-null reference type even though // the original type was nullable. This allows our code generation to // follow our recommendation of only using nullable when necessary. // This is done after method generation instead of at analyzer time because it's purely // based on the resulting code, which the generator can modify as needed. If return statements // are added, the flow analysis could change to indicate something different. It's cleaner to rely // on flow analysis of the final resulting code than to try and predict from the analyzer what // will happen in the generator. var finalDocument = await UpdateMethodAfterGenerationAsync(generatedDocument, result, cancellationToken).ConfigureAwait(false); var finalRoot = finalDocument.Root; var methodDefinition = finalRoot.GetAnnotatedNodesAndTokens(MethodDefinitionAnnotation).FirstOrDefault(); if (!methodDefinition.IsNode || methodDefinition.AsNode() == null) { return await CreateGeneratedCodeAsync( result.Status.With(OperationStatus.FailedWithUnknownReason), finalDocument, cancellationToken).ConfigureAwait(false); } if (methodDefinition.SyntaxTree.IsHiddenPosition(methodDefinition.AsNode().SpanStart, cancellationToken) || methodDefinition.SyntaxTree.IsHiddenPosition(methodDefinition.AsNode().Span.End, cancellationToken)) { return await CreateGeneratedCodeAsync( result.Status.With(OperationStatus.OverlapsHiddenPosition), finalDocument, cancellationToken).ConfigureAwait(false); } return await CreateGeneratedCodeAsync(result.Status, finalDocument, cancellationToken).ConfigureAwait(false); } protected virtual Task<SemanticDocument> UpdateMethodAfterGenerationAsync( SemanticDocument originalDocument, OperationStatus<IMethodSymbol> methodSymbolResult, CancellationToken cancellationToken) => Task.FromResult(originalDocument); protected virtual Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { return Task.FromResult(new GeneratedCode( status, newDocument, MethodNameAnnotation, CallSiteAnnotation, MethodDefinitionAnnotation)); } protected VariableInfo GetOutermostVariableToMoveIntoMethodDefinition(CancellationToken cancellationToken) { using var _ = ArrayBuilder<VariableInfo>.GetInstance(out var variables); variables.AddRange(AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken)); if (variables.Count <= 0) return null; VariableInfo.SortVariables(SemanticDocument.SemanticModel.Compilation, variables); return variables[0]; } protected ImmutableArray<TStatement> AddReturnIfUnreachable(ImmutableArray<TStatement> statements) { if (AnalyzerResult.EndOfSelectionReachable) { return statements; } var type = SelectionResult.GetContainingScopeType(); if (type != null && type.SpecialType != SpecialType.System_Void) { return statements; } // no return type + end of selection not reachable if (LastStatementOrHasReturnStatementInReturnableConstruct()) { return statements; } return statements.Concat(CreateReturnStatement()); } protected async Task<ImmutableArray<TStatement>> AddInvocationAtCallSiteAsync( ImmutableArray<TStatement> statements, CancellationToken cancellationToken) { if (AnalyzerResult.HasVariableToUseAsReturnValue) { return statements; } Contract.ThrowIfTrue(AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken).Any(v => v.UseAsReturnValue)); // add invocation expression return statements.Concat( (TStatement)(SyntaxNode)await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken).ConfigureAwait(false)); } protected ImmutableArray<TStatement> AddAssignmentStatementToCallSite( ImmutableArray<TStatement> statements, CancellationToken cancellationToken) { if (!AnalyzerResult.HasVariableToUseAsReturnValue) { return statements; } var variable = AnalyzerResult.VariableToUseAsReturnValue; if (variable.ReturnBehavior == ReturnBehavior.Initialization) { // there must be one decl behavior when there is "return value and initialize" variable Contract.ThrowIfFalse(AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken).Single(v => v.ReturnBehavior == ReturnBehavior.Initialization) != null); var declarationStatement = CreateDeclarationStatement( variable, CreateCallSignature(), cancellationToken); declarationStatement = declarationStatement.WithAdditionalAnnotations(CallSiteAnnotation); return statements.Concat(declarationStatement); } Contract.ThrowIfFalse(variable.ReturnBehavior == ReturnBehavior.Assignment); return statements.Concat( CreateAssignmentExpressionStatement(CreateIdentifier(variable.Name), CreateCallSignature()).WithAdditionalAnnotations(CallSiteAnnotation)); } protected ImmutableArray<TStatement> CreateDeclarationStatements( ImmutableArray<VariableInfo> variables, CancellationToken cancellationToken) { return variables.SelectAsArray(v => CreateDeclarationStatement(v, initialValue: null, cancellationToken)); } protected ImmutableArray<TStatement> AddSplitOrMoveDeclarationOutStatementsToCallSite( CancellationToken cancellationToken) { using var _ = ArrayBuilder<TStatement>.GetInstance(out var list); foreach (var variable in AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken)) { if (variable.UseAsReturnValue) continue; var declaration = CreateDeclarationStatement( variable, initialValue: null, cancellationToken: cancellationToken); list.Add(declaration); } return list.ToImmutable(); } protected ImmutableArray<TStatement> AppendReturnStatementIfNeeded(ImmutableArray<TStatement> statements) { if (!AnalyzerResult.HasVariableToUseAsReturnValue) { return statements; } var variableToUseAsReturnValue = AnalyzerResult.VariableToUseAsReturnValue; Contract.ThrowIfFalse(variableToUseAsReturnValue.ReturnBehavior is ReturnBehavior.Assignment or ReturnBehavior.Initialization); return statements.Concat(CreateReturnStatement(AnalyzerResult.VariableToUseAsReturnValue.Name)); } protected static HashSet<SyntaxAnnotation> CreateVariableDeclarationToRemoveMap( IEnumerable<VariableInfo> variables, CancellationToken cancellationToken) { var annotations = new List<Tuple<SyntaxToken, SyntaxAnnotation>>(); foreach (var variable in variables) { Contract.ThrowIfFalse(variable.GetDeclarationBehavior(cancellationToken) is DeclarationBehavior.MoveOut or DeclarationBehavior.MoveIn or DeclarationBehavior.Delete); variable.AddIdentifierTokenAnnotationPair(annotations, cancellationToken); } return new HashSet<SyntaxAnnotation>(annotations.Select(t => t.Item2)); } protected ImmutableArray<ITypeParameterSymbol> CreateMethodTypeParameters() { if (AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0) { return ImmutableArray<ITypeParameterSymbol>.Empty; } var set = new HashSet<ITypeParameterSymbol>(AnalyzerResult.MethodTypeParametersInConstraintList); var typeParameters = ArrayBuilder<ITypeParameterSymbol>.GetInstance(); foreach (var parameter in AnalyzerResult.MethodTypeParametersInDeclaration) { if (parameter != null && set.Contains(parameter)) { typeParameters.Add(parameter); continue; } typeParameters.Add(CodeGenerationSymbolFactory.CreateTypeParameter( parameter.GetAttributes(), parameter.Variance, parameter.Name, ImmutableArray.Create<ITypeSymbol>(), parameter.NullableAnnotation, parameter.HasConstructorConstraint, parameter.HasReferenceTypeConstraint, parameter.HasUnmanagedTypeConstraint, parameter.HasValueTypeConstraint, parameter.HasNotNullConstraint, parameter.Ordinal)); } return typeParameters.ToImmutableAndFree(); } protected ImmutableArray<IParameterSymbol> CreateMethodParameters() { var parameters = ArrayBuilder<IParameterSymbol>.GetInstance(); foreach (var parameter in AnalyzerResult.MethodParameters) { var refKind = GetRefKind(parameter.ParameterModifier); var type = parameter.GetVariableType(SemanticDocument); parameters.Add( CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: ImmutableArray<AttributeData>.Empty, refKind: refKind, isParams: false, type: type, name: parameter.Name)); } return parameters.ToImmutableAndFree(); } private static RefKind GetRefKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? RefKind.Ref : parameterBehavior == ParameterBehavior.Out ? RefKind.Out : RefKind.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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected abstract partial class CodeGenerator<TStatement, TExpression, TNodeUnderContainer> where TStatement : SyntaxNode where TExpression : SyntaxNode where TNodeUnderContainer : SyntaxNode { protected readonly SyntaxAnnotation MethodNameAnnotation; protected readonly SyntaxAnnotation MethodDefinitionAnnotation; protected readonly SyntaxAnnotation CallSiteAnnotation; protected readonly InsertionPoint InsertionPoint; protected readonly SemanticDocument SemanticDocument; protected readonly SelectionResult SelectionResult; protected readonly AnalyzerResult AnalyzerResult; protected readonly OptionSet Options; protected readonly bool LocalFunction; protected CodeGenerator(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options = null, bool localFunction = false) { Contract.ThrowIfFalse(insertionPoint.SemanticDocument == analyzerResult.SemanticDocument); InsertionPoint = insertionPoint; SemanticDocument = insertionPoint.SemanticDocument; SelectionResult = selectionResult; AnalyzerResult = analyzerResult; Options = options; LocalFunction = localFunction; MethodNameAnnotation = new SyntaxAnnotation(); CallSiteAnnotation = new SyntaxAnnotation(); MethodDefinitionAnnotation = new SyntaxAnnotation(); } #region method to be implemented in sub classes protected abstract SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken); protected abstract Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken); protected abstract SyntaxNode GetPreviousMember(SemanticDocument document); protected abstract OperationStatus<IMethodSymbol> GenerateMethodDefinition(bool localFunction, CancellationToken cancellationToken); protected abstract bool ShouldLocalFunctionCaptureParameter(SyntaxNode node); protected abstract SyntaxToken CreateIdentifier(string name); protected abstract SyntaxToken CreateMethodName(); protected abstract bool LastStatementOrHasReturnStatementInReturnableConstruct(); protected abstract TNodeUnderContainer GetFirstStatementOrInitializerSelectedAtCallSite(); protected abstract TNodeUnderContainer GetLastStatementOrInitializerSelectedAtCallSite(); protected abstract Task<TNodeUnderContainer> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken); protected abstract TExpression CreateCallSignature(); protected abstract TStatement CreateDeclarationStatement(VariableInfo variable, TExpression initialValue, CancellationToken cancellationToken); protected abstract TStatement CreateAssignmentExpressionStatement(SyntaxToken identifier, TExpression rvalue); protected abstract TStatement CreateReturnStatement(string identifierName = null); protected abstract ImmutableArray<TStatement> GetInitialStatementsForMethodDefinitions(); #endregion public async Task<GeneratedCode> GenerateAsync(CancellationToken cancellationToken) { var root = SemanticDocument.Root; // should I check venus hidden position check here as well? root = root.ReplaceNode(GetOutermostCallSiteContainerToProcess(cancellationToken), await GenerateBodyForCallSiteContainerAsync(cancellationToken).ConfigureAwait(false)); var callSiteDocument = await SemanticDocument.WithSyntaxRootAsync(root, cancellationToken).ConfigureAwait(false); var newCallSiteRoot = callSiteDocument.Root; var codeGenerationService = SemanticDocument.Document.GetLanguageService<ICodeGenerationService>(); var result = GenerateMethodDefinition(LocalFunction, cancellationToken); SyntaxNode destination, newContainer; if (LocalFunction) { destination = InsertionPoint.With(callSiteDocument).GetContext(); // No valid location to insert the new method call. if (destination == null) { return await CreateGeneratedCodeAsync( OperationStatus.NoValidLocationToInsertMethodCall, callSiteDocument, cancellationToken).ConfigureAwait(false); } var localMethod = codeGenerationService.CreateMethodDeclaration( method: result.Data, options: new CodeGenerationOptions(generateDefaultAccessibility: false, generateMethodBodies: true, options: Options, parseOptions: destination?.SyntaxTree.Options)); newContainer = codeGenerationService.AddStatements(destination, new[] { localMethod }, cancellationToken: cancellationToken); } else { var previousMemberNode = GetPreviousMember(callSiteDocument); // it is possible in a script file case where there is no previous member. in that case, insert new text into top level script destination = previousMemberNode.Parent ?? previousMemberNode; newContainer = codeGenerationService.AddMethod( destination, result.Data, new CodeGenerationOptions(afterThisLocation: previousMemberNode.GetLocation(), generateDefaultAccessibility: true, generateMethodBodies: true, options: Options), cancellationToken); } var newSyntaxRoot = newCallSiteRoot.ReplaceNode(destination, newContainer); var newDocument = callSiteDocument.Document.WithSyntaxRoot(newSyntaxRoot); newDocument = await Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, null, cancellationToken).ConfigureAwait(false); var generatedDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); // For nullable reference types, we can provide a better experience by reducing use // of nullable reference types after a method is done being generated. If we can // determine that the method never returns null, for example, then we can // make the signature into a non-null reference type even though // the original type was nullable. This allows our code generation to // follow our recommendation of only using nullable when necessary. // This is done after method generation instead of at analyzer time because it's purely // based on the resulting code, which the generator can modify as needed. If return statements // are added, the flow analysis could change to indicate something different. It's cleaner to rely // on flow analysis of the final resulting code than to try and predict from the analyzer what // will happen in the generator. var finalDocument = await UpdateMethodAfterGenerationAsync(generatedDocument, result, cancellationToken).ConfigureAwait(false); var finalRoot = finalDocument.Root; var methodDefinition = finalRoot.GetAnnotatedNodesAndTokens(MethodDefinitionAnnotation).FirstOrDefault(); if (!methodDefinition.IsNode || methodDefinition.AsNode() == null) { return await CreateGeneratedCodeAsync( result.Status.With(OperationStatus.FailedWithUnknownReason), finalDocument, cancellationToken).ConfigureAwait(false); } if (methodDefinition.SyntaxTree.IsHiddenPosition(methodDefinition.AsNode().SpanStart, cancellationToken) || methodDefinition.SyntaxTree.IsHiddenPosition(methodDefinition.AsNode().Span.End, cancellationToken)) { return await CreateGeneratedCodeAsync( result.Status.With(OperationStatus.OverlapsHiddenPosition), finalDocument, cancellationToken).ConfigureAwait(false); } return await CreateGeneratedCodeAsync(result.Status, finalDocument, cancellationToken).ConfigureAwait(false); } protected virtual Task<SemanticDocument> UpdateMethodAfterGenerationAsync( SemanticDocument originalDocument, OperationStatus<IMethodSymbol> methodSymbolResult, CancellationToken cancellationToken) => Task.FromResult(originalDocument); protected virtual Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { return Task.FromResult(new GeneratedCode( status, newDocument, MethodNameAnnotation, CallSiteAnnotation, MethodDefinitionAnnotation)); } protected VariableInfo GetOutermostVariableToMoveIntoMethodDefinition(CancellationToken cancellationToken) { using var _ = ArrayBuilder<VariableInfo>.GetInstance(out var variables); variables.AddRange(AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken)); if (variables.Count <= 0) return null; VariableInfo.SortVariables(SemanticDocument.SemanticModel.Compilation, variables); return variables[0]; } protected ImmutableArray<TStatement> AddReturnIfUnreachable(ImmutableArray<TStatement> statements) { if (AnalyzerResult.EndOfSelectionReachable) { return statements; } var type = SelectionResult.GetContainingScopeType(); if (type != null && type.SpecialType != SpecialType.System_Void) { return statements; } // no return type + end of selection not reachable if (LastStatementOrHasReturnStatementInReturnableConstruct()) { return statements; } return statements.Concat(CreateReturnStatement()); } protected async Task<ImmutableArray<TStatement>> AddInvocationAtCallSiteAsync( ImmutableArray<TStatement> statements, CancellationToken cancellationToken) { if (AnalyzerResult.HasVariableToUseAsReturnValue) { return statements; } Contract.ThrowIfTrue(AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken).Any(v => v.UseAsReturnValue)); // add invocation expression return statements.Concat( (TStatement)(SyntaxNode)await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken).ConfigureAwait(false)); } protected ImmutableArray<TStatement> AddAssignmentStatementToCallSite( ImmutableArray<TStatement> statements, CancellationToken cancellationToken) { if (!AnalyzerResult.HasVariableToUseAsReturnValue) { return statements; } var variable = AnalyzerResult.VariableToUseAsReturnValue; if (variable.ReturnBehavior == ReturnBehavior.Initialization) { // there must be one decl behavior when there is "return value and initialize" variable Contract.ThrowIfFalse(AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken).Single(v => v.ReturnBehavior == ReturnBehavior.Initialization) != null); var declarationStatement = CreateDeclarationStatement( variable, CreateCallSignature(), cancellationToken); declarationStatement = declarationStatement.WithAdditionalAnnotations(CallSiteAnnotation); return statements.Concat(declarationStatement); } Contract.ThrowIfFalse(variable.ReturnBehavior == ReturnBehavior.Assignment); return statements.Concat( CreateAssignmentExpressionStatement(CreateIdentifier(variable.Name), CreateCallSignature()).WithAdditionalAnnotations(CallSiteAnnotation)); } protected ImmutableArray<TStatement> CreateDeclarationStatements( ImmutableArray<VariableInfo> variables, CancellationToken cancellationToken) { return variables.SelectAsArray(v => CreateDeclarationStatement(v, initialValue: null, cancellationToken)); } protected ImmutableArray<TStatement> AddSplitOrMoveDeclarationOutStatementsToCallSite( CancellationToken cancellationToken) { using var _ = ArrayBuilder<TStatement>.GetInstance(out var list); foreach (var variable in AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken)) { if (variable.UseAsReturnValue) continue; var declaration = CreateDeclarationStatement( variable, initialValue: null, cancellationToken: cancellationToken); list.Add(declaration); } return list.ToImmutable(); } protected ImmutableArray<TStatement> AppendReturnStatementIfNeeded(ImmutableArray<TStatement> statements) { if (!AnalyzerResult.HasVariableToUseAsReturnValue) { return statements; } var variableToUseAsReturnValue = AnalyzerResult.VariableToUseAsReturnValue; Contract.ThrowIfFalse(variableToUseAsReturnValue.ReturnBehavior is ReturnBehavior.Assignment or ReturnBehavior.Initialization); return statements.Concat(CreateReturnStatement(AnalyzerResult.VariableToUseAsReturnValue.Name)); } protected static HashSet<SyntaxAnnotation> CreateVariableDeclarationToRemoveMap( IEnumerable<VariableInfo> variables, CancellationToken cancellationToken) { var annotations = new List<Tuple<SyntaxToken, SyntaxAnnotation>>(); foreach (var variable in variables) { Contract.ThrowIfFalse(variable.GetDeclarationBehavior(cancellationToken) is DeclarationBehavior.MoveOut or DeclarationBehavior.MoveIn or DeclarationBehavior.Delete); variable.AddIdentifierTokenAnnotationPair(annotations, cancellationToken); } return new HashSet<SyntaxAnnotation>(annotations.Select(t => t.Item2)); } protected ImmutableArray<ITypeParameterSymbol> CreateMethodTypeParameters() { if (AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0) { return ImmutableArray<ITypeParameterSymbol>.Empty; } var set = new HashSet<ITypeParameterSymbol>(AnalyzerResult.MethodTypeParametersInConstraintList); var typeParameters = ArrayBuilder<ITypeParameterSymbol>.GetInstance(); foreach (var parameter in AnalyzerResult.MethodTypeParametersInDeclaration) { if (parameter != null && set.Contains(parameter)) { typeParameters.Add(parameter); continue; } typeParameters.Add(CodeGenerationSymbolFactory.CreateTypeParameter( parameter.GetAttributes(), parameter.Variance, parameter.Name, ImmutableArray.Create<ITypeSymbol>(), parameter.NullableAnnotation, parameter.HasConstructorConstraint, parameter.HasReferenceTypeConstraint, parameter.HasUnmanagedTypeConstraint, parameter.HasValueTypeConstraint, parameter.HasNotNullConstraint, parameter.Ordinal)); } return typeParameters.ToImmutableAndFree(); } protected ImmutableArray<IParameterSymbol> CreateMethodParameters() { var parameters = ArrayBuilder<IParameterSymbol>.GetInstance(); var isLocalFunction = LocalFunction && ShouldLocalFunctionCaptureParameter(SemanticDocument.Root); foreach (var parameter in AnalyzerResult.MethodParameters) { if (!isLocalFunction || !parameter.CanBeCapturedByLocalFunction) { var refKind = GetRefKind(parameter.ParameterModifier); var type = parameter.GetVariableType(SemanticDocument); parameters.Add( CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: ImmutableArray<AttributeData>.Empty, refKind: refKind, isParams: false, type: type, name: parameter.Name)); } } return parameters.ToImmutableAndFree(); } private static RefKind GetRefKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? RefKind.Ref : parameterBehavior == ParameterBehavior.Out ? RefKind.Out : RefKind.None; } } } }
1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/Core/Portable/ExtractMethod/MethodExtractor.VariableInfo.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.Linq; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected class VariableInfo { private readonly VariableSymbol _variableSymbol; private readonly VariableStyle _variableStyle; private readonly bool _useAsReturnValue; public VariableInfo( VariableSymbol variableSymbol, VariableStyle variableStyle, bool useAsReturnValue = false) { _variableSymbol = variableSymbol; _variableStyle = variableStyle; _useAsReturnValue = useAsReturnValue; } public bool UseAsReturnValue { get { Contract.ThrowIfFalse(!_useAsReturnValue || _variableStyle.ReturnStyle.ReturnBehavior != ReturnBehavior.None); return _useAsReturnValue; } } public bool CanBeUsedAsReturnValue { get { return _variableStyle.ReturnStyle.ReturnBehavior != ReturnBehavior.None; } } public bool UseAsParameter { get { return (!_useAsReturnValue && _variableStyle.ParameterStyle.ParameterBehavior != ParameterBehavior.None) || (_useAsReturnValue && _variableStyle.ReturnStyle.ParameterBehavior != ParameterBehavior.None); } } public ParameterBehavior ParameterModifier { get { return _useAsReturnValue ? _variableStyle.ReturnStyle.ParameterBehavior : _variableStyle.ParameterStyle.ParameterBehavior; } } public DeclarationBehavior GetDeclarationBehavior(CancellationToken cancellationToken) { if (_useAsReturnValue) { return _variableStyle.ReturnStyle.DeclarationBehavior; } if (_variableSymbol.GetUseSaferDeclarationBehavior(cancellationToken)) { return _variableStyle.ParameterStyle.SaferDeclarationBehavior; } return _variableStyle.ParameterStyle.DeclarationBehavior; } public ReturnBehavior ReturnBehavior { get { if (_useAsReturnValue) { return _variableStyle.ReturnStyle.ReturnBehavior; } return ReturnBehavior.None; } } public static VariableInfo CreateReturnValue(VariableInfo variable) { Contract.ThrowIfNull(variable); Contract.ThrowIfFalse(variable.CanBeUsedAsReturnValue); Contract.ThrowIfFalse(variable.ParameterModifier is ParameterBehavior.Out or ParameterBehavior.Ref); return new VariableInfo(variable._variableSymbol, variable._variableStyle, useAsReturnValue: true); } public void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { _variableSymbol.AddIdentifierTokenAnnotationPair(annotations, cancellationToken); } public string Name => _variableSymbol.Name; public bool OriginalTypeHadAnonymousTypeOrDelegate => _variableSymbol.OriginalTypeHadAnonymousTypeOrDelegate; public ITypeSymbol OriginalType => _variableSymbol.OriginalType; public ITypeSymbol GetVariableType(SemanticDocument document) => document.SemanticModel.ResolveType(_variableSymbol.OriginalType); public SyntaxToken GetIdentifierTokenAtDeclaration(SemanticDocument document) => document.GetTokenWithAnnotation(_variableSymbol.IdentifierTokenAnnotation); public SyntaxToken GetIdentifierTokenAtDeclaration(SyntaxNode node) => node.GetAnnotatedTokens(_variableSymbol.IdentifierTokenAnnotation).SingleOrDefault(); public static void SortVariables(Compilation compilation, ArrayBuilder<VariableInfo> variables) { var cancellationTokenType = compilation.GetTypeByMetadataName(typeof(CancellationToken).FullName); variables.Sort((v1, v2) => Compare(v1, v2, cancellationTokenType)); } private static int Compare(VariableInfo left, VariableInfo right, INamedTypeSymbol cancellationTokenType) => VariableSymbol.Compare(left._variableSymbol, right._variableSymbol, cancellationTokenType); } } }
// 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected class VariableInfo { private readonly VariableSymbol _variableSymbol; private readonly VariableStyle _variableStyle; private readonly bool _useAsReturnValue; public VariableInfo( VariableSymbol variableSymbol, VariableStyle variableStyle, bool useAsReturnValue = false) { _variableSymbol = variableSymbol; _variableStyle = variableStyle; _useAsReturnValue = useAsReturnValue; } public bool UseAsReturnValue { get { Contract.ThrowIfFalse(!_useAsReturnValue || _variableStyle.ReturnStyle.ReturnBehavior != ReturnBehavior.None); return _useAsReturnValue; } } public bool CanBeUsedAsReturnValue { get { return _variableStyle.ReturnStyle.ReturnBehavior != ReturnBehavior.None; } } public bool UseAsParameter { get { return (!_useAsReturnValue && _variableStyle.ParameterStyle.ParameterBehavior != ParameterBehavior.None) || (_useAsReturnValue && _variableStyle.ReturnStyle.ParameterBehavior != ParameterBehavior.None); } } public ParameterBehavior ParameterModifier { get { return _useAsReturnValue ? _variableStyle.ReturnStyle.ParameterBehavior : _variableStyle.ParameterStyle.ParameterBehavior; } } public DeclarationBehavior GetDeclarationBehavior(CancellationToken cancellationToken) { if (_useAsReturnValue) { return _variableStyle.ReturnStyle.DeclarationBehavior; } if (_variableSymbol.GetUseSaferDeclarationBehavior(cancellationToken)) { return _variableStyle.ParameterStyle.SaferDeclarationBehavior; } return _variableStyle.ParameterStyle.DeclarationBehavior; } public ReturnBehavior ReturnBehavior { get { if (_useAsReturnValue) { return _variableStyle.ReturnStyle.ReturnBehavior; } return ReturnBehavior.None; } } public static VariableInfo CreateReturnValue(VariableInfo variable) { Contract.ThrowIfNull(variable); Contract.ThrowIfFalse(variable.CanBeUsedAsReturnValue); Contract.ThrowIfFalse(variable.ParameterModifier is ParameterBehavior.Out or ParameterBehavior.Ref); return new VariableInfo(variable._variableSymbol, variable._variableStyle, useAsReturnValue: true); } public void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { _variableSymbol.AddIdentifierTokenAnnotationPair(annotations, cancellationToken); } public string Name => _variableSymbol.Name; /// <summary> /// Returns true, if the variable could be either passed as a parameter /// to the new local function or the local function can capture the variable. /// </summary> public bool CanBeCapturedByLocalFunction => _variableSymbol.CanBeCapturedByLocalFunction; public bool OriginalTypeHadAnonymousTypeOrDelegate => _variableSymbol.OriginalTypeHadAnonymousTypeOrDelegate; public ITypeSymbol OriginalType => _variableSymbol.OriginalType; public ITypeSymbol GetVariableType(SemanticDocument document) => document.SemanticModel.ResolveType(_variableSymbol.OriginalType); public SyntaxToken GetIdentifierTokenAtDeclaration(SemanticDocument document) => document.GetTokenWithAnnotation(_variableSymbol.IdentifierTokenAnnotation); public SyntaxToken GetIdentifierTokenAtDeclaration(SyntaxNode node) => node.GetAnnotatedTokens(_variableSymbol.IdentifierTokenAnnotation).SingleOrDefault(); public static void SortVariables(Compilation compilation, ArrayBuilder<VariableInfo> variables) { var cancellationTokenType = compilation.GetTypeByMetadataName(typeof(CancellationToken).FullName); variables.Sort((v1, v2) => Compare(v1, v2, cancellationTokenType)); } private static int Compare(VariableInfo left, VariableInfo right, INamedTypeSymbol cancellationTokenType) => VariableSymbol.Compare(left._variableSymbol, right._variableSymbol, cancellationTokenType); } } }
1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/Core/Portable/ExtractMethod/MethodExtractor.VariableSymbol.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.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { /// <summary> /// temporary symbol until we have a symbol that can hold onto both local and parameter symbol /// </summary> protected abstract class VariableSymbol { protected VariableSymbol(Compilation compilation, ITypeSymbol type) { OriginalTypeHadAnonymousTypeOrDelegate = type.ContainsAnonymousType(); OriginalType = OriginalTypeHadAnonymousTypeOrDelegate ? type.RemoveAnonymousTypes(compilation) : type; } public abstract int DisplayOrder { get; } public abstract string Name { get; } public abstract bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken); public abstract SyntaxAnnotation IdentifierTokenAnnotation { get; } public abstract SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken); public abstract void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken); protected abstract int CompareTo(VariableSymbol right); /// <summary> /// return true if original type had anonymous type or delegate somewhere in the type /// </summary> public bool OriginalTypeHadAnonymousTypeOrDelegate { get; } /// <summary> /// get the original type with anonymous type removed /// </summary> public ITypeSymbol OriginalType { get; } public static int Compare( VariableSymbol left, VariableSymbol right, INamedTypeSymbol cancellationTokenType) { // CancellationTokens always go at the end of method signature. var leftIsCancellationToken = left.OriginalType.Equals(cancellationTokenType); var rightIsCancellationToken = right.OriginalType.Equals(cancellationTokenType); if (leftIsCancellationToken && !rightIsCancellationToken) { return 1; } else if (!leftIsCancellationToken && rightIsCancellationToken) { return -1; } if (left.DisplayOrder == right.DisplayOrder) { return left.CompareTo(right); } return left.DisplayOrder - right.DisplayOrder; } } protected abstract class NotMovableVariableSymbol : VariableSymbol { public NotMovableVariableSymbol(Compilation compilation, ITypeSymbol type) : base(compilation, type) { } public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken) { // decl never get moved return false; } public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken) => throw ExceptionUtilities.Unreachable; public override SyntaxAnnotation IdentifierTokenAnnotation => throw ExceptionUtilities.Unreachable; public override void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { // do nothing for parameter } } protected class ParameterVariableSymbol : NotMovableVariableSymbol, IComparable<ParameterVariableSymbol> { private readonly IParameterSymbol _parameterSymbol; public ParameterVariableSymbol(Compilation compilation, IParameterSymbol parameterSymbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(parameterSymbol); _parameterSymbol = parameterSymbol; } public override int DisplayOrder => 0; protected override int CompareTo(VariableSymbol right) => CompareTo((ParameterVariableSymbol)right); public int CompareTo(ParameterVariableSymbol other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } var compare = CompareMethodParameters((IMethodSymbol)_parameterSymbol.ContainingSymbol, (IMethodSymbol)other._parameterSymbol.ContainingSymbol); if (compare != 0) { return compare; } Contract.ThrowIfFalse(_parameterSymbol.Ordinal != other._parameterSymbol.Ordinal); return (_parameterSymbol.Ordinal > other._parameterSymbol.Ordinal) ? 1 : -1; } private static int CompareMethodParameters(IMethodSymbol left, IMethodSymbol right) { if (left == null && right == null) { // not method parameters return 0; } if (left.Equals(right)) { // parameter of same method return 0; } // these methods can be either regular one, anonymous function, local function and etc // but all must belong to same outer regular method. // so, it should have location pointing to same tree var leftLocations = left.Locations; var rightLocations = right.Locations; var commonTree = leftLocations.Select(l => l.SourceTree).Intersect(rightLocations.Select(l => l.SourceTree)).WhereNotNull().First(); var leftLocation = leftLocations.First(l => l.SourceTree == commonTree); var rightLocation = rightLocations.First(l => l.SourceTree == commonTree); return leftLocation.SourceSpan.Start - rightLocation.SourceSpan.Start; } public override string Name { get { return _parameterSymbol.ToDisplayString( new SymbolDisplayFormat( parameterOptions: SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } } protected class LocalVariableSymbol<T> : VariableSymbol, IComparable<LocalVariableSymbol<T>> where T : SyntaxNode { private readonly SyntaxAnnotation _annotation; private readonly ILocalSymbol _localSymbol; private readonly HashSet<int> _nonNoisySet; public LocalVariableSymbol(Compilation compilation, ILocalSymbol localSymbol, ITypeSymbol type, HashSet<int> nonNoisySet) : base(compilation, type) { Contract.ThrowIfNull(localSymbol); Contract.ThrowIfNull(nonNoisySet); _annotation = new SyntaxAnnotation(); _localSymbol = localSymbol; _nonNoisySet = nonNoisySet; } public override int DisplayOrder => 1; protected override int CompareTo(VariableSymbol right) => CompareTo((LocalVariableSymbol<T>)right); public int CompareTo(LocalVariableSymbol<T> other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(other._localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource); Contract.ThrowIfFalse(other._localSymbol.Locations[0].IsInSource); Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceTree == other._localSymbol.Locations[0].SourceTree); Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceSpan.Start != other._localSymbol.Locations[0].SourceSpan.Start); return _localSymbol.Locations[0].SourceSpan.Start - other._localSymbol.Locations[0].SourceSpan.Start; } public override string Name { get { return _localSymbol.ToDisplayString( new SymbolDisplayFormat( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken) { Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource); Contract.ThrowIfNull(_localSymbol.Locations[0].SourceTree); var tree = _localSymbol.Locations[0].SourceTree; var span = _localSymbol.Locations[0].SourceSpan; var token = tree.GetRoot(cancellationToken).FindToken(span.Start); Contract.ThrowIfFalse(token.Span.Equals(span)); return token; } public override SyntaxAnnotation IdentifierTokenAnnotation => _annotation; public override void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { annotations.Add(Tuple.Create(GetOriginalIdentifierToken(cancellationToken), _annotation)); } public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken) { var identifier = GetOriginalIdentifierToken(cancellationToken); // check whether there is a noisy trivia around the token. if (ContainsNoisyTrivia(identifier.LeadingTrivia)) { return true; } if (ContainsNoisyTrivia(identifier.TrailingTrivia)) { return true; } var declStatement = identifier.Parent.FirstAncestorOrSelf<T>(); if (declStatement == null) { return true; } foreach (var token in declStatement.DescendantTokens()) { if (ContainsNoisyTrivia(token.LeadingTrivia)) { return true; } if (ContainsNoisyTrivia(token.TrailingTrivia)) { return true; } } return false; } private bool ContainsNoisyTrivia(SyntaxTriviaList list) => list.Any(t => !_nonNoisySet.Contains(t.RawKind)); } protected class QueryVariableSymbol : NotMovableVariableSymbol, IComparable<QueryVariableSymbol> { private readonly IRangeVariableSymbol _symbol; public QueryVariableSymbol(Compilation compilation, IRangeVariableSymbol symbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(symbol); _symbol = symbol; } public override int DisplayOrder => 2; protected override int CompareTo(VariableSymbol right) => CompareTo((QueryVariableSymbol)right); public int CompareTo(QueryVariableSymbol other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } var locationLeft = _symbol.Locations.First(); var locationRight = other._symbol.Locations.First(); Contract.ThrowIfFalse(locationLeft.IsInSource); Contract.ThrowIfFalse(locationRight.IsInSource); Contract.ThrowIfFalse(locationLeft.SourceTree == locationRight.SourceTree); Contract.ThrowIfFalse(locationLeft.SourceSpan.Start != locationRight.SourceSpan.Start); return locationLeft.SourceSpan.Start - locationRight.SourceSpan.Start; } public override string Name { get { return _symbol.ToDisplayString( new SymbolDisplayFormat( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } } } }
// 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.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { /// <summary> /// temporary symbol until we have a symbol that can hold onto both local and parameter symbol /// </summary> protected abstract class VariableSymbol { protected VariableSymbol(Compilation compilation, ITypeSymbol type) { OriginalTypeHadAnonymousTypeOrDelegate = type.ContainsAnonymousType(); OriginalType = OriginalTypeHadAnonymousTypeOrDelegate ? type.RemoveAnonymousTypes(compilation) : type; } public abstract int DisplayOrder { get; } public abstract string Name { get; } public abstract bool CanBeCapturedByLocalFunction { get; } public abstract bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken); public abstract SyntaxAnnotation IdentifierTokenAnnotation { get; } public abstract SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken); public abstract void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken); protected abstract int CompareTo(VariableSymbol right); /// <summary> /// return true if original type had anonymous type or delegate somewhere in the type /// </summary> public bool OriginalTypeHadAnonymousTypeOrDelegate { get; } /// <summary> /// get the original type with anonymous type removed /// </summary> public ITypeSymbol OriginalType { get; } public static int Compare( VariableSymbol left, VariableSymbol right, INamedTypeSymbol cancellationTokenType) { // CancellationTokens always go at the end of method signature. var leftIsCancellationToken = left.OriginalType.Equals(cancellationTokenType); var rightIsCancellationToken = right.OriginalType.Equals(cancellationTokenType); if (leftIsCancellationToken && !rightIsCancellationToken) { return 1; } else if (!leftIsCancellationToken && rightIsCancellationToken) { return -1; } if (left.DisplayOrder == right.DisplayOrder) { return left.CompareTo(right); } return left.DisplayOrder - right.DisplayOrder; } } protected abstract class NotMovableVariableSymbol : VariableSymbol { public NotMovableVariableSymbol(Compilation compilation, ITypeSymbol type) : base(compilation, type) { } public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken) { // decl never get moved return false; } public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken) => throw ExceptionUtilities.Unreachable; public override SyntaxAnnotation IdentifierTokenAnnotation => throw ExceptionUtilities.Unreachable; public override void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { // do nothing for parameter } } protected class ParameterVariableSymbol : NotMovableVariableSymbol, IComparable<ParameterVariableSymbol> { private readonly IParameterSymbol _parameterSymbol; public ParameterVariableSymbol(Compilation compilation, IParameterSymbol parameterSymbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(parameterSymbol); _parameterSymbol = parameterSymbol; } public override int DisplayOrder => 0; protected override int CompareTo(VariableSymbol right) => CompareTo((ParameterVariableSymbol)right); public int CompareTo(ParameterVariableSymbol other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } var compare = CompareMethodParameters((IMethodSymbol)_parameterSymbol.ContainingSymbol, (IMethodSymbol)other._parameterSymbol.ContainingSymbol); if (compare != 0) { return compare; } Contract.ThrowIfFalse(_parameterSymbol.Ordinal != other._parameterSymbol.Ordinal); return (_parameterSymbol.Ordinal > other._parameterSymbol.Ordinal) ? 1 : -1; } private static int CompareMethodParameters(IMethodSymbol left, IMethodSymbol right) { if (left == null && right == null) { // not method parameters return 0; } if (left.Equals(right)) { // parameter of same method return 0; } // these methods can be either regular one, anonymous function, local function and etc // but all must belong to same outer regular method. // so, it should have location pointing to same tree var leftLocations = left.Locations; var rightLocations = right.Locations; var commonTree = leftLocations.Select(l => l.SourceTree).Intersect(rightLocations.Select(l => l.SourceTree)).WhereNotNull().First(); var leftLocation = leftLocations.First(l => l.SourceTree == commonTree); var rightLocation = rightLocations.First(l => l.SourceTree == commonTree); return leftLocation.SourceSpan.Start - rightLocation.SourceSpan.Start; } public override string Name { get { return _parameterSymbol.ToDisplayString( new SymbolDisplayFormat( parameterOptions: SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } public override bool CanBeCapturedByLocalFunction => true; } protected class LocalVariableSymbol<T> : VariableSymbol, IComparable<LocalVariableSymbol<T>> where T : SyntaxNode { private readonly SyntaxAnnotation _annotation; private readonly ILocalSymbol _localSymbol; private readonly HashSet<int> _nonNoisySet; public LocalVariableSymbol(Compilation compilation, ILocalSymbol localSymbol, ITypeSymbol type, HashSet<int> nonNoisySet) : base(compilation, type) { Contract.ThrowIfNull(localSymbol); Contract.ThrowIfNull(nonNoisySet); _annotation = new SyntaxAnnotation(); _localSymbol = localSymbol; _nonNoisySet = nonNoisySet; } public override int DisplayOrder => 1; protected override int CompareTo(VariableSymbol right) => CompareTo((LocalVariableSymbol<T>)right); public int CompareTo(LocalVariableSymbol<T> other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(other._localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource); Contract.ThrowIfFalse(other._localSymbol.Locations[0].IsInSource); Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceTree == other._localSymbol.Locations[0].SourceTree); Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceSpan.Start != other._localSymbol.Locations[0].SourceSpan.Start); return _localSymbol.Locations[0].SourceSpan.Start - other._localSymbol.Locations[0].SourceSpan.Start; } public override string Name { get { return _localSymbol.ToDisplayString( new SymbolDisplayFormat( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken) { Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource); Contract.ThrowIfNull(_localSymbol.Locations[0].SourceTree); var tree = _localSymbol.Locations[0].SourceTree; var span = _localSymbol.Locations[0].SourceSpan; var token = tree.GetRoot(cancellationToken).FindToken(span.Start); Contract.ThrowIfFalse(token.Span.Equals(span)); return token; } public override SyntaxAnnotation IdentifierTokenAnnotation => _annotation; public override bool CanBeCapturedByLocalFunction => true; public override void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { annotations.Add(Tuple.Create(GetOriginalIdentifierToken(cancellationToken), _annotation)); } public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken) { var identifier = GetOriginalIdentifierToken(cancellationToken); // check whether there is a noisy trivia around the token. if (ContainsNoisyTrivia(identifier.LeadingTrivia)) { return true; } if (ContainsNoisyTrivia(identifier.TrailingTrivia)) { return true; } var declStatement = identifier.Parent.FirstAncestorOrSelf<T>(); if (declStatement == null) { return true; } foreach (var token in declStatement.DescendantTokens()) { if (ContainsNoisyTrivia(token.LeadingTrivia)) { return true; } if (ContainsNoisyTrivia(token.TrailingTrivia)) { return true; } } return false; } private bool ContainsNoisyTrivia(SyntaxTriviaList list) => list.Any(t => !_nonNoisySet.Contains(t.RawKind)); } protected class QueryVariableSymbol : NotMovableVariableSymbol, IComparable<QueryVariableSymbol> { private readonly IRangeVariableSymbol _symbol; public QueryVariableSymbol(Compilation compilation, IRangeVariableSymbol symbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(symbol); _symbol = symbol; } public override int DisplayOrder => 2; protected override int CompareTo(VariableSymbol right) => CompareTo((QueryVariableSymbol)right); public int CompareTo(QueryVariableSymbol other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } var locationLeft = _symbol.Locations.First(); var locationRight = other._symbol.Locations.First(); Contract.ThrowIfFalse(locationLeft.IsInSource); Contract.ThrowIfFalse(locationRight.IsInSource); Contract.ThrowIfFalse(locationLeft.SourceTree == locationRight.SourceTree); Contract.ThrowIfFalse(locationLeft.SourceSpan.Start != locationRight.SourceSpan.Start); return locationLeft.SourceSpan.Start - locationRight.SourceSpan.Start; } public override string Name { get { return _symbol.ToDisplayString( new SymbolDisplayFormat( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } public override bool CanBeCapturedByLocalFunction => false; } } }
1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.VisualBasicCodeGenerator.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 Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Simplification Imports System.Collections.Immutable Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Partial Friend Class VisualBasicMethodExtractor Partial Private MustInherit Class VisualBasicCodeGenerator Inherits CodeGenerator(Of StatementSyntax, ExpressionSyntax, StatementSyntax) Private ReadOnly _methodName As SyntaxToken Public Shared Async Function GenerateResultAsync(insertionPoint As InsertionPoint, selectionResult As SelectionResult, analyzerResult As AnalyzerResult, cancellationToken As CancellationToken) As Task(Of GeneratedCode) Dim generator = Create(insertionPoint, selectionResult, analyzerResult) Return Await generator.GenerateAsync(cancellationToken).ConfigureAwait(False) End Function Private Shared Function Create(insertionPoint As InsertionPoint, selectionResult As SelectionResult, analyzerResult As AnalyzerResult) As VisualBasicCodeGenerator If ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult) Then Return New ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult) End If If SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult) Then Return New SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult) End If If MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult) Then Return New MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult) End If throw ExceptionUtilities.UnexpectedValue(selectionResult) End Function Protected Sub New(insertionPoint As InsertionPoint, selectionResult As SelectionResult, analyzerResult As AnalyzerResult) MyBase.New(insertionPoint, selectionResult, analyzerResult) Contract.ThrowIfFalse(Me.SemanticDocument Is selectionResult.SemanticDocument) Me._methodName = CreateMethodName().WithAdditionalAnnotations(MethodNameAnnotation) End Sub Private ReadOnly Property VBSelectionResult() As VisualBasicSelectionResult Get Return CType(SelectionResult, VisualBasicSelectionResult) End Get End Property Protected Overrides Function GetPreviousMember(document As SemanticDocument) As SyntaxNode Return Me.InsertionPoint.With(document).GetContext() End Function Protected Overrides Function GenerateMethodDefinition(localFunction As Boolean, cancellationToken As CancellationToken) As OperationStatus(Of IMethodSymbol) Dim result = CreateMethodBody(cancellationToken) Dim statements = result.Data Dim methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes:=ImmutableArray(Of AttributeData).Empty, accessibility:=Accessibility.Private, modifiers:=CreateMethodModifiers(), returnType:=Me.AnalyzerResult.ReturnType, refKind:=RefKind.None, explicitInterfaceImplementations:=Nothing, name:=_methodName.ToString(), typeParameters:=CreateMethodTypeParameters(), parameters:=CreateMethodParameters(), statements:=statements.Cast(Of SyntaxNode).ToImmutableArray()) Return result.With( Me.MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))) End Function Protected Overrides Async Function GenerateBodyForCallSiteContainerAsync(cancellationToken As CancellationToken) As Task(Of SyntaxNode) Dim container = GetOutermostCallSiteContainerToProcess(cancellationToken) Dim variableMapToRemove = CreateVariableDeclarationToRemoveMap(AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken) Dim firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite() Dim lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite() Contract.ThrowIfFalse(firstStatementToRemove.Parent Is lastStatementToRemove.Parent) Dim statementsToInsert = Await CreateStatementsToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(False) Dim callSiteGenerator = New CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert) Return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation) End Function Private Async Function CreateStatementsToInsertAtCallSiteAsync(cancellationToken As CancellationToken) As Task(Of IEnumerable(Of StatementSyntax)) Dim semanticModel = SemanticDocument.SemanticModel Dim context = InsertionPoint.GetContext() Dim postProcessor = New PostProcessor(semanticModel, context.SpanStart) Dim statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(cancellationToken) statements = postProcessor.MergeDeclarationStatements(statements) statements = AddAssignmentStatementToCallSite(statements, cancellationToken) statements = Await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(False) statements = AddReturnIfUnreachable(statements) Return statements End Function Private Function CreateMethodNameForInvocation() As ExpressionSyntax If AnalyzerResult.MethodTypeParametersInDeclaration.Count = 0 Then Return SyntaxFactory.IdentifierName(_methodName) End If Return SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(arguments:=CreateMethodCallTypeVariables())) End Function Private Function CreateMethodCallTypeVariables() As SeparatedSyntaxList(Of TypeSyntax) Contract.ThrowIfTrue(AnalyzerResult.MethodTypeParametersInDeclaration.Count = 0) ' propagate any type variable used in extracted code Dim typeVariables = (From methodTypeParameter In AnalyzerResult.MethodTypeParametersInDeclaration Select SyntaxFactory.ParseTypeName(methodTypeParameter.Name)).ToList() Return SyntaxFactory.SeparatedList(typeVariables) End Function Protected Function GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken As CancellationToken) As SyntaxNode Dim outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken) If outmostVariable Is Nothing Then Return Nothing End If Dim idToken = outmostVariable.GetIdentifierTokenAtDeclaration(SemanticDocument) Dim declStatement = idToken.GetAncestor(Of LocalDeclarationStatementSyntax)() Contract.ThrowIfNull(declStatement) Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()) Return declStatement.Parent End Function Private Function CreateMethodModifiers() As DeclarationModifiers Dim isShared = False If Not Me.AnalyzerResult.UseInstanceMember AndAlso Not VBSelectionResult.IsUnderModuleBlock() AndAlso Not VBSelectionResult.ContainsInstanceExpression() Then isShared = True End If Dim isAsync = Me.VBSelectionResult.ShouldPutAsyncModifier() Return New DeclarationModifiers(isStatic:=isShared, isAsync:=isAsync) End Function Private Function CreateMethodBody(cancellationToken As CancellationToken) As OperationStatus(Of ImmutableArray(Of StatementSyntax)) Dim statements = GetInitialStatementsForMethodDefinitions() statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken) statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken) Dim emptyStatements = ImmutableArray(Of StatementSyntax).Empty Dim returnStatements = AppendReturnStatementIfNeeded(emptyStatements) statements = statements.Concat(returnStatements) Dim semanticModel = SemanticDocument.SemanticModel Dim context = Me.InsertionPoint.GetContext() statements = PostProcessor.RemoveDeclarationAssignmentPattern(statements) statements = PostProcessor.RemoveInitializedDeclarationAndReturnPattern(statements) ' assign before checking issues so that we can do negative preview Return CheckActiveStatements(statements).With(statements) End Function Private Shared Function CheckActiveStatements(statements As ImmutableArray(Of StatementSyntax)) As OperationStatus Dim count = statements.Count() If count = 0 Then Return OperationStatus.NoActiveStatement End If If count = 1 Then Dim returnStatement = TryCast(statements(0), ReturnStatementSyntax) If returnStatement IsNot Nothing AndAlso returnStatement.Expression Is Nothing Then Return OperationStatus.NoActiveStatement End If End If For Each statement In statements Dim localDeclStatement = TryCast(statement, LocalDeclarationStatementSyntax) If localDeclStatement Is Nothing Then 'found one Return OperationStatus.Succeeded End If For Each variableDecl In localDeclStatement.Declarators If variableDecl.Initializer IsNot Nothing Then 'found one Return OperationStatus.Succeeded ElseIf TypeOf variableDecl.AsClause Is AsNewClauseSyntax Then 'found one Return OperationStatus.Succeeded End If Next Next Return OperationStatus.NoActiveStatement End Function Private Function MoveDeclarationOutFromMethodDefinition(statements As ImmutableArray(Of StatementSyntax), cancellationToken As CancellationToken) As ImmutableArray(Of StatementSyntax) Dim variableToRemoveMap = CreateVariableDeclarationToRemoveMap( Me.AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken) Dim declarationStatements = New List(Of StatementSyntax)() For Each statement In statements Dim declarationStatement = TryCast(statement, LocalDeclarationStatementSyntax) If declarationStatement Is Nothing Then ' if given statement is not decl statement, do nothing. declarationStatements.Add(statement) Continue For End If Dim expressionStatements = New List(Of StatementSyntax)() Dim variableDeclarators = New List(Of VariableDeclaratorSyntax)() Dim triviaList = New List(Of SyntaxTrivia)() If Not variableToRemoveMap.ProcessLocalDeclarationStatement(declarationStatement, expressionStatements, variableDeclarators, triviaList) Then declarationStatements.Add(statement) Continue For End If If variableDeclarators.Count = 0 AndAlso triviaList.Any(Function(t) t.Kind <> SyntaxKind.WhitespaceTrivia AndAlso t.Kind <> SyntaxKind.EndOfLineTrivia) Then ' well, there are trivia associated with the node. ' we can't just delete the node since then, we will lose ' the trivia. unfortunately, it is not easy to attach the trivia ' to next token. for now, create an empty statement and associate the ' trivia to the statement ' TODO : think about a way to trivia attached to next token Dim emptyStatement As StatementSyntax = SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.EmptyToken).WithLeadingTrivia(SyntaxFactory.TriviaList(triviaList))) declarationStatements.Add(emptyStatement) triviaList.Clear() End If ' return survived var decls If variableDeclarators.Count > 0 Then Dim localStatement As StatementSyntax = SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, SyntaxFactory.SeparatedList(variableDeclarators)).WithPrependedLeadingTrivia(triviaList) declarationStatements.Add(localStatement) triviaList.Clear() End If ' return any expression statement if there was any For Each expressionStatement In expressionStatements declarationStatements.Add(expressionStatement) Next expressionStatement Next Return declarationStatements.ToImmutableArray() End Function Private Function SplitOrMoveDeclarationIntoMethodDefinition(statements As ImmutableArray(Of StatementSyntax), cancellationToken As CancellationToken) As ImmutableArray(Of StatementSyntax) Dim semanticModel = CType(Me.SemanticDocument.SemanticModel, SemanticModel) Dim context = Me.InsertionPoint.GetContext() Dim postProcessor = New PostProcessor(semanticModel, context.SpanStart) Dim declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken) declStatements = postProcessor.MergeDeclarationStatements(declStatements) Return declStatements.Concat(statements) End Function Protected Overrides Function CreateIdentifier(name As String) As SyntaxToken Return SyntaxFactory.Identifier(name) End Function Protected Overrides Function CreateReturnStatement(Optional identifierName As String = Nothing) As StatementSyntax If String.IsNullOrEmpty(identifierName) Then Return SyntaxFactory.ReturnStatement() End If Return SyntaxFactory.ReturnStatement(expression:=SyntaxFactory.IdentifierName(identifierName)) End Function Protected Overrides Function LastStatementOrHasReturnStatementInReturnableConstruct() As Boolean Dim lastStatement = GetLastStatementOrInitializerSelectedAtCallSite() Dim container = lastStatement.GetAncestorsOrThis(Of SyntaxNode).Where(Function(n) n.IsReturnableConstruct()).FirstOrDefault() If container Is Nothing Then ' case such as field initializer Return False End If Dim statements = container.GetStatements() If statements.Count = 0 Then ' such as expression lambda Return False End If If statements.Last() Is lastStatement Then Return True End If Dim index = statements.IndexOf(lastStatement) Return statements(index + 1).IsKind(SyntaxKind.ReturnStatement, SyntaxKind.ExitSubStatement) End Function Protected Overrides Function CreateCallSignature() As ExpressionSyntax Dim methodName As ExpressionSyntax = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation) Dim arguments = New List(Of ArgumentSyntax)() For Each argument In AnalyzerResult.MethodParameters arguments.Add(SyntaxFactory.SimpleArgument(expression:=GetIdentifierName(argument.Name))) Next argument Dim invocation = SyntaxFactory.InvocationExpression( methodName, SyntaxFactory.ArgumentList(arguments:=SyntaxFactory.SeparatedList(arguments))) If Me.VBSelectionResult.ShouldPutAsyncModifier() Then If Me.VBSelectionResult.ShouldCallConfigureAwaitFalse() Then If AnalyzerResult.ReturnType.GetMembers().Any( Function(x) Dim method = TryCast(x, IMethodSymbol) If method Is Nothing Then Return False End If If Not CaseInsensitiveComparison.Equals(method.Name, NameOf(Task.ConfigureAwait)) Then Return False End If If method.Parameters.Length <> 1 Then Return False End If Return method.Parameters(0).Type.SpecialType = SpecialType.System_Boolean End Function) Then invocation = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, invocation, SyntaxFactory.Token(SyntaxKind.DotToken), SyntaxFactory.IdentifierName(NameOf(Task.ConfigureAwait))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(Of ArgumentSyntax)( SyntaxFactory.SimpleArgument( SyntaxFactory.LiteralExpression( SyntaxKind.FalseLiteralExpression, SyntaxFactory.Token(SyntaxKind.FalseKeyword)))))) End If End If Return SyntaxFactory.AwaitExpression(invocation) End If Return invocation End Function Private Shared Function GetIdentifierName(name As String) As ExpressionSyntax Dim bracket = SyntaxFacts.MakeHalfWidthIdentifier(name.First) = "[" AndAlso SyntaxFacts.MakeHalfWidthIdentifier(name.Last) = "]" If bracket Then Dim unescaped = name.Substring(1, name.Length() - 2) Return SyntaxFactory.IdentifierName(SyntaxFactory.BracketedIdentifier(unescaped)) End If Return SyntaxFactory.IdentifierName(name) End Function Protected Overrides Function CreateAssignmentExpressionStatement(identifier As SyntaxToken, rvalue As ExpressionSyntax) As StatementSyntax Return identifier.CreateAssignmentExpressionStatementWithValue(rvalue) End Function Protected Overrides Function CreateDeclarationStatement( variable As VariableInfo, givenInitializer As ExpressionSyntax, cancellationToken As CancellationToken) As StatementSyntax Dim shouldInitializeWithNothing = (variable.GetDeclarationBehavior(cancellationToken) = DeclarationBehavior.MoveOut OrElse variable.GetDeclarationBehavior(cancellationToken) = DeclarationBehavior.SplitOut) AndAlso (variable.ParameterModifier = ParameterBehavior.Out) Dim initializer = If(givenInitializer, If(shouldInitializeWithNothing, SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)), Nothing)) Dim variableType = variable.GetVariableType(Me.SemanticDocument) Dim typeNode = variableType.GenerateTypeSyntax() Dim names = SyntaxFactory.SingletonSeparatedList(SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(variable.Name))) Dim modifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.DimKeyword)) Dim equalsValue = If(initializer Is Nothing, Nothing, SyntaxFactory.EqualsValue(value:=initializer)) Dim declarators = SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(names, SyntaxFactory.SimpleAsClause(type:=typeNode), equalsValue)) Return SyntaxFactory.LocalDeclarationStatement(modifiers, declarators) End Function Protected Overrides Async Function CreateGeneratedCodeAsync(status As OperationStatus, newDocument As SemanticDocument, cancellationToken As CancellationToken) As Task(Of GeneratedCode) If (status.Flag And OperationStatusFlag.Succeeded) <> 0 Then ' in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. ' here, we explicitly insert newline at the end of auto generated method decl's begin statement so that anchor knows how to find out ' indentation of inserted statements (from users code) with user code style preserved Dim root = newDocument.Root Dim methodDefinition = root.GetAnnotatedNodes(Of MethodBlockBaseSyntax)(Me.MethodDefinitionAnnotation).First() Dim lastTokenOfBeginStatement = methodDefinition.BlockStatement.GetLastToken(includeZeroWidth:=True) Dim newMethodDefinition = methodDefinition.ReplaceToken(lastTokenOfBeginStatement, lastTokenOfBeginStatement.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))) newDocument = Await newDocument.WithSyntaxRootAsync(root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(False) End If Return Await MyBase.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(False) End Function Protected Function GetStatementContainingInvocationToExtractedMethodWorker() As StatementSyntax Dim callSignature = CreateCallSignature() If Me.AnalyzerResult.HasReturnType Then Contract.ThrowIfTrue(Me.AnalyzerResult.HasVariableToUseAsReturnValue) Return SyntaxFactory.ReturnStatement(expression:=callSignature) End If Return SyntaxFactory.ExpressionStatement(expression:=callSignature) End Function 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.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Simplification Imports System.Collections.Immutable Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Partial Friend Class VisualBasicMethodExtractor Partial Private MustInherit Class VisualBasicCodeGenerator Inherits CodeGenerator(Of StatementSyntax, ExpressionSyntax, StatementSyntax) Private ReadOnly _methodName As SyntaxToken Public Shared Async Function GenerateResultAsync(insertionPoint As InsertionPoint, selectionResult As SelectionResult, analyzerResult As AnalyzerResult, cancellationToken As CancellationToken) As Task(Of GeneratedCode) Dim generator = Create(insertionPoint, selectionResult, analyzerResult) Return Await generator.GenerateAsync(cancellationToken).ConfigureAwait(False) End Function Private Shared Function Create(insertionPoint As InsertionPoint, selectionResult As SelectionResult, analyzerResult As AnalyzerResult) As VisualBasicCodeGenerator If ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult) Then Return New ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult) End If If SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult) Then Return New SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult) End If If MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult) Then Return New MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult) End If throw ExceptionUtilities.UnexpectedValue(selectionResult) End Function Protected Sub New(insertionPoint As InsertionPoint, selectionResult As SelectionResult, analyzerResult As AnalyzerResult) MyBase.New(insertionPoint, selectionResult, analyzerResult) Contract.ThrowIfFalse(Me.SemanticDocument Is selectionResult.SemanticDocument) Me._methodName = CreateMethodName().WithAdditionalAnnotations(MethodNameAnnotation) End Sub Private ReadOnly Property VBSelectionResult() As VisualBasicSelectionResult Get Return CType(SelectionResult, VisualBasicSelectionResult) End Get End Property Protected Overrides Function GetPreviousMember(document As SemanticDocument) As SyntaxNode Return Me.InsertionPoint.With(document).GetContext() End Function Protected Overrides Function ShouldLocalFunctionCaptureParameter(node As SyntaxNode) As Boolean Return False End Function Protected Overrides Function GenerateMethodDefinition(localFunction As Boolean, cancellationToken As CancellationToken) As OperationStatus(Of IMethodSymbol) Dim result = CreateMethodBody(cancellationToken) Dim statements = result.Data Dim methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes:=ImmutableArray(Of AttributeData).Empty, accessibility:=Accessibility.Private, modifiers:=CreateMethodModifiers(), returnType:=Me.AnalyzerResult.ReturnType, refKind:=RefKind.None, explicitInterfaceImplementations:=Nothing, name:=_methodName.ToString(), typeParameters:=CreateMethodTypeParameters(), parameters:=CreateMethodParameters(), statements:=statements.Cast(Of SyntaxNode).ToImmutableArray()) Return result.With( Me.MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))) End Function Protected Overrides Async Function GenerateBodyForCallSiteContainerAsync(cancellationToken As CancellationToken) As Task(Of SyntaxNode) Dim container = GetOutermostCallSiteContainerToProcess(cancellationToken) Dim variableMapToRemove = CreateVariableDeclarationToRemoveMap(AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken) Dim firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite() Dim lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite() Contract.ThrowIfFalse(firstStatementToRemove.Parent Is lastStatementToRemove.Parent) Dim statementsToInsert = Await CreateStatementsToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(False) Dim callSiteGenerator = New CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert) Return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation) End Function Private Async Function CreateStatementsToInsertAtCallSiteAsync(cancellationToken As CancellationToken) As Task(Of IEnumerable(Of StatementSyntax)) Dim semanticModel = SemanticDocument.SemanticModel Dim context = InsertionPoint.GetContext() Dim postProcessor = New PostProcessor(semanticModel, context.SpanStart) Dim statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(cancellationToken) statements = postProcessor.MergeDeclarationStatements(statements) statements = AddAssignmentStatementToCallSite(statements, cancellationToken) statements = Await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(False) statements = AddReturnIfUnreachable(statements) Return statements End Function Private Function CreateMethodNameForInvocation() As ExpressionSyntax If AnalyzerResult.MethodTypeParametersInDeclaration.Count = 0 Then Return SyntaxFactory.IdentifierName(_methodName) End If Return SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(arguments:=CreateMethodCallTypeVariables())) End Function Private Function CreateMethodCallTypeVariables() As SeparatedSyntaxList(Of TypeSyntax) Contract.ThrowIfTrue(AnalyzerResult.MethodTypeParametersInDeclaration.Count = 0) ' propagate any type variable used in extracted code Dim typeVariables = (From methodTypeParameter In AnalyzerResult.MethodTypeParametersInDeclaration Select SyntaxFactory.ParseTypeName(methodTypeParameter.Name)).ToList() Return SyntaxFactory.SeparatedList(typeVariables) End Function Protected Function GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken As CancellationToken) As SyntaxNode Dim outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken) If outmostVariable Is Nothing Then Return Nothing End If Dim idToken = outmostVariable.GetIdentifierTokenAtDeclaration(SemanticDocument) Dim declStatement = idToken.GetAncestor(Of LocalDeclarationStatementSyntax)() Contract.ThrowIfNull(declStatement) Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()) Return declStatement.Parent End Function Private Function CreateMethodModifiers() As DeclarationModifiers Dim isShared = False If Not Me.AnalyzerResult.UseInstanceMember AndAlso Not VBSelectionResult.IsUnderModuleBlock() AndAlso Not VBSelectionResult.ContainsInstanceExpression() Then isShared = True End If Dim isAsync = Me.VBSelectionResult.ShouldPutAsyncModifier() Return New DeclarationModifiers(isStatic:=isShared, isAsync:=isAsync) End Function Private Function CreateMethodBody(cancellationToken As CancellationToken) As OperationStatus(Of ImmutableArray(Of StatementSyntax)) Dim statements = GetInitialStatementsForMethodDefinitions() statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken) statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken) Dim emptyStatements = ImmutableArray(Of StatementSyntax).Empty Dim returnStatements = AppendReturnStatementIfNeeded(emptyStatements) statements = statements.Concat(returnStatements) Dim semanticModel = SemanticDocument.SemanticModel Dim context = Me.InsertionPoint.GetContext() statements = PostProcessor.RemoveDeclarationAssignmentPattern(statements) statements = PostProcessor.RemoveInitializedDeclarationAndReturnPattern(statements) ' assign before checking issues so that we can do negative preview Return CheckActiveStatements(statements).With(statements) End Function Private Shared Function CheckActiveStatements(statements As ImmutableArray(Of StatementSyntax)) As OperationStatus Dim count = statements.Count() If count = 0 Then Return OperationStatus.NoActiveStatement End If If count = 1 Then Dim returnStatement = TryCast(statements(0), ReturnStatementSyntax) If returnStatement IsNot Nothing AndAlso returnStatement.Expression Is Nothing Then Return OperationStatus.NoActiveStatement End If End If For Each statement In statements Dim localDeclStatement = TryCast(statement, LocalDeclarationStatementSyntax) If localDeclStatement Is Nothing Then 'found one Return OperationStatus.Succeeded End If For Each variableDecl In localDeclStatement.Declarators If variableDecl.Initializer IsNot Nothing Then 'found one Return OperationStatus.Succeeded ElseIf TypeOf variableDecl.AsClause Is AsNewClauseSyntax Then 'found one Return OperationStatus.Succeeded End If Next Next Return OperationStatus.NoActiveStatement End Function Private Function MoveDeclarationOutFromMethodDefinition(statements As ImmutableArray(Of StatementSyntax), cancellationToken As CancellationToken) As ImmutableArray(Of StatementSyntax) Dim variableToRemoveMap = CreateVariableDeclarationToRemoveMap( Me.AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken) Dim declarationStatements = New List(Of StatementSyntax)() For Each statement In statements Dim declarationStatement = TryCast(statement, LocalDeclarationStatementSyntax) If declarationStatement Is Nothing Then ' if given statement is not decl statement, do nothing. declarationStatements.Add(statement) Continue For End If Dim expressionStatements = New List(Of StatementSyntax)() Dim variableDeclarators = New List(Of VariableDeclaratorSyntax)() Dim triviaList = New List(Of SyntaxTrivia)() If Not variableToRemoveMap.ProcessLocalDeclarationStatement(declarationStatement, expressionStatements, variableDeclarators, triviaList) Then declarationStatements.Add(statement) Continue For End If If variableDeclarators.Count = 0 AndAlso triviaList.Any(Function(t) t.Kind <> SyntaxKind.WhitespaceTrivia AndAlso t.Kind <> SyntaxKind.EndOfLineTrivia) Then ' well, there are trivia associated with the node. ' we can't just delete the node since then, we will lose ' the trivia. unfortunately, it is not easy to attach the trivia ' to next token. for now, create an empty statement and associate the ' trivia to the statement ' TODO : think about a way to trivia attached to next token Dim emptyStatement As StatementSyntax = SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.EmptyToken).WithLeadingTrivia(SyntaxFactory.TriviaList(triviaList))) declarationStatements.Add(emptyStatement) triviaList.Clear() End If ' return survived var decls If variableDeclarators.Count > 0 Then Dim localStatement As StatementSyntax = SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, SyntaxFactory.SeparatedList(variableDeclarators)).WithPrependedLeadingTrivia(triviaList) declarationStatements.Add(localStatement) triviaList.Clear() End If ' return any expression statement if there was any For Each expressionStatement In expressionStatements declarationStatements.Add(expressionStatement) Next expressionStatement Next Return declarationStatements.ToImmutableArray() End Function Private Function SplitOrMoveDeclarationIntoMethodDefinition(statements As ImmutableArray(Of StatementSyntax), cancellationToken As CancellationToken) As ImmutableArray(Of StatementSyntax) Dim semanticModel = CType(Me.SemanticDocument.SemanticModel, SemanticModel) Dim context = Me.InsertionPoint.GetContext() Dim postProcessor = New PostProcessor(semanticModel, context.SpanStart) Dim declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken) declStatements = postProcessor.MergeDeclarationStatements(declStatements) Return declStatements.Concat(statements) End Function Protected Overrides Function CreateIdentifier(name As String) As SyntaxToken Return SyntaxFactory.Identifier(name) End Function Protected Overrides Function CreateReturnStatement(Optional identifierName As String = Nothing) As StatementSyntax If String.IsNullOrEmpty(identifierName) Then Return SyntaxFactory.ReturnStatement() End If Return SyntaxFactory.ReturnStatement(expression:=SyntaxFactory.IdentifierName(identifierName)) End Function Protected Overrides Function LastStatementOrHasReturnStatementInReturnableConstruct() As Boolean Dim lastStatement = GetLastStatementOrInitializerSelectedAtCallSite() Dim container = lastStatement.GetAncestorsOrThis(Of SyntaxNode).Where(Function(n) n.IsReturnableConstruct()).FirstOrDefault() If container Is Nothing Then ' case such as field initializer Return False End If Dim statements = container.GetStatements() If statements.Count = 0 Then ' such as expression lambda Return False End If If statements.Last() Is lastStatement Then Return True End If Dim index = statements.IndexOf(lastStatement) Return statements(index + 1).IsKind(SyntaxKind.ReturnStatement, SyntaxKind.ExitSubStatement) End Function Protected Overrides Function CreateCallSignature() As ExpressionSyntax Dim methodName As ExpressionSyntax = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation) Dim arguments = New List(Of ArgumentSyntax)() For Each argument In AnalyzerResult.MethodParameters arguments.Add(SyntaxFactory.SimpleArgument(expression:=GetIdentifierName(argument.Name))) Next argument Dim invocation = SyntaxFactory.InvocationExpression( methodName, SyntaxFactory.ArgumentList(arguments:=SyntaxFactory.SeparatedList(arguments))) If Me.VBSelectionResult.ShouldPutAsyncModifier() Then If Me.VBSelectionResult.ShouldCallConfigureAwaitFalse() Then If AnalyzerResult.ReturnType.GetMembers().Any( Function(x) Dim method = TryCast(x, IMethodSymbol) If method Is Nothing Then Return False End If If Not CaseInsensitiveComparison.Equals(method.Name, NameOf(Task.ConfigureAwait)) Then Return False End If If method.Parameters.Length <> 1 Then Return False End If Return method.Parameters(0).Type.SpecialType = SpecialType.System_Boolean End Function) Then invocation = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, invocation, SyntaxFactory.Token(SyntaxKind.DotToken), SyntaxFactory.IdentifierName(NameOf(Task.ConfigureAwait))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(Of ArgumentSyntax)( SyntaxFactory.SimpleArgument( SyntaxFactory.LiteralExpression( SyntaxKind.FalseLiteralExpression, SyntaxFactory.Token(SyntaxKind.FalseKeyword)))))) End If End If Return SyntaxFactory.AwaitExpression(invocation) End If Return invocation End Function Private Shared Function GetIdentifierName(name As String) As ExpressionSyntax Dim bracket = SyntaxFacts.MakeHalfWidthIdentifier(name.First) = "[" AndAlso SyntaxFacts.MakeHalfWidthIdentifier(name.Last) = "]" If bracket Then Dim unescaped = name.Substring(1, name.Length() - 2) Return SyntaxFactory.IdentifierName(SyntaxFactory.BracketedIdentifier(unescaped)) End If Return SyntaxFactory.IdentifierName(name) End Function Protected Overrides Function CreateAssignmentExpressionStatement(identifier As SyntaxToken, rvalue As ExpressionSyntax) As StatementSyntax Return identifier.CreateAssignmentExpressionStatementWithValue(rvalue) End Function Protected Overrides Function CreateDeclarationStatement( variable As VariableInfo, givenInitializer As ExpressionSyntax, cancellationToken As CancellationToken) As StatementSyntax Dim shouldInitializeWithNothing = (variable.GetDeclarationBehavior(cancellationToken) = DeclarationBehavior.MoveOut OrElse variable.GetDeclarationBehavior(cancellationToken) = DeclarationBehavior.SplitOut) AndAlso (variable.ParameterModifier = ParameterBehavior.Out) Dim initializer = If(givenInitializer, If(shouldInitializeWithNothing, SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)), Nothing)) Dim variableType = variable.GetVariableType(Me.SemanticDocument) Dim typeNode = variableType.GenerateTypeSyntax() Dim names = SyntaxFactory.SingletonSeparatedList(SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(variable.Name))) Dim modifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.DimKeyword)) Dim equalsValue = If(initializer Is Nothing, Nothing, SyntaxFactory.EqualsValue(value:=initializer)) Dim declarators = SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(names, SyntaxFactory.SimpleAsClause(type:=typeNode), equalsValue)) Return SyntaxFactory.LocalDeclarationStatement(modifiers, declarators) End Function Protected Overrides Async Function CreateGeneratedCodeAsync(status As OperationStatus, newDocument As SemanticDocument, cancellationToken As CancellationToken) As Task(Of GeneratedCode) If (status.Flag And OperationStatusFlag.Succeeded) <> 0 Then ' in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. ' here, we explicitly insert newline at the end of auto generated method decl's begin statement so that anchor knows how to find out ' indentation of inserted statements (from users code) with user code style preserved Dim root = newDocument.Root Dim methodDefinition = root.GetAnnotatedNodes(Of MethodBlockBaseSyntax)(Me.MethodDefinitionAnnotation).First() Dim lastTokenOfBeginStatement = methodDefinition.BlockStatement.GetLastToken(includeZeroWidth:=True) Dim newMethodDefinition = methodDefinition.ReplaceToken(lastTokenOfBeginStatement, lastTokenOfBeginStatement.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))) newDocument = Await newDocument.WithSyntaxRootAsync(root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(False) End If Return Await MyBase.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(False) End Function Protected Function GetStatementContainingInvocationToExtractedMethodWorker() As StatementSyntax Dim callSignature = CreateCallSignature() If Me.AnalyzerResult.HasReturnType Then Contract.ThrowIfTrue(Me.AnalyzerResult.HasVariableToUseAsReturnValue) Return SyntaxFactory.ReturnStatement(expression:=callSignature) End If Return SyntaxFactory.ExpressionStatement(expression:=callSignature) End Function End Class End Class End Namespace
1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpTypeStyleHelper.State.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.Threading; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using OptionSet = Microsoft.CodeAnalysis.Options.OptionSet; #endif namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal partial class CSharpTypeStyleHelper { protected readonly struct State { public readonly UseVarPreference TypeStylePreference; private readonly ReportDiagnostic _forBuiltInTypes; private readonly ReportDiagnostic _whenTypeIsApparent; private readonly ReportDiagnostic _elsewhere; public readonly bool IsInIntrinsicTypeContext; public readonly bool IsTypeApparentInContext; public State( SyntaxNode declaration, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { TypeStylePreference = default; IsInIntrinsicTypeContext = default; IsTypeApparentInContext = default; var styleForIntrinsicTypes = optionSet.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes); var styleForApparent = optionSet.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent); var styleForElsewhere = optionSet.GetOption(CSharpCodeStyleOptions.VarElsewhere); _forBuiltInTypes = styleForIntrinsicTypes.Notification.Severity; _whenTypeIsApparent = styleForApparent.Notification.Severity; _elsewhere = styleForElsewhere.Notification.Severity; var stylePreferences = UseVarPreference.None; if (styleForIntrinsicTypes.Value) stylePreferences |= UseVarPreference.ForBuiltInTypes; if (styleForApparent.Value) stylePreferences |= UseVarPreference.WhenTypeIsApparent; if (styleForElsewhere.Value) stylePreferences |= UseVarPreference.Elsewhere; this.TypeStylePreference = stylePreferences; IsTypeApparentInContext = declaration.IsKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax? varDecl) && IsTypeApparentInDeclaration(varDecl, semanticModel, TypeStylePreference, cancellationToken); IsInIntrinsicTypeContext = IsPredefinedTypeInDeclaration(declaration, semanticModel) || IsInferredPredefinedType(declaration, semanticModel); } public ReportDiagnostic GetDiagnosticSeverityPreference() => IsInIntrinsicTypeContext ? _forBuiltInTypes : IsTypeApparentInContext ? _whenTypeIsApparent : _elsewhere; /// <summary> /// Returns true if type information could be gleaned by simply looking at the given statement. /// This typically means that the type name occurs in right hand side of an assignment. /// </summary> private static bool IsTypeApparentInDeclaration(VariableDeclarationSyntax variableDeclaration, SemanticModel semanticModel, UseVarPreference stylePreferences, CancellationToken cancellationToken) { if (variableDeclaration.Variables.Count != 1) { return false; } var initializer = variableDeclaration.Variables[0].Initializer; if (initializer == null) { return false; } var initializerExpression = CSharpUseImplicitTypeHelper.GetInitializerExpression(initializer.Value); var declaredTypeSymbol = semanticModel.GetTypeInfo(variableDeclaration.Type.StripRefIfNeeded(), cancellationToken).Type; return TypeStyleHelper.IsTypeApparentInAssignmentExpression(stylePreferences, initializerExpression, semanticModel, declaredTypeSymbol, cancellationToken); } /// <summary> /// checks if the type represented by the given symbol is one of the /// simple types defined in the compiler. /// </summary> /// <remarks> /// From the IDE perspective, we also include object and string to be simplified /// to var. <see cref="SyntaxFacts.IsPredefinedType(SyntaxKind)"/> considers string /// and object but the compiler's implementation of IsIntrinsicType does not. /// </remarks> private static bool IsPredefinedTypeInDeclaration(SyntaxNode declarationStatement, SemanticModel semanticModel) { var typeSyntax = GetTypeSyntaxFromDeclaration(declarationStatement); return typeSyntax != null ? IsMadeOfSpecialTypes(semanticModel.GetTypeInfo(typeSyntax.StripRefIfNeeded()).Type) : false; } /// <summary> /// Returns true for type that are arrays/nullable/pointer types of special types /// </summary> private static bool IsMadeOfSpecialTypes([NotNullWhen(true)] ITypeSymbol? type) { if (type == null) { return false; } while (true) { type = type.RemoveNullableIfPresent(); if (type.IsArrayType()) { type = ((IArrayTypeSymbol)type).ElementType; continue; } if (type.IsPointerType()) { type = ((IPointerTypeSymbol)type).PointedAtType; continue; } return type.IsSpecialType(); } } private static bool IsInferredPredefinedType(SyntaxNode declarationStatement, SemanticModel semanticModel) { var typeSyntax = GetTypeSyntaxFromDeclaration(declarationStatement); return typeSyntax != null && typeSyntax.IsTypeInferred(semanticModel) && semanticModel.GetTypeInfo(typeSyntax).Type?.IsSpecialType() == true; } private static TypeSyntax? GetTypeSyntaxFromDeclaration(SyntaxNode declarationStatement) => declarationStatement switch { VariableDeclarationSyntax varDecl => varDecl.Type, ForEachStatementSyntax forEach => forEach.Type, DeclarationExpressionSyntax declExpr => declExpr.Type, _ => 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. using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using OptionSet = Microsoft.CodeAnalysis.Options.OptionSet; #endif namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal partial class CSharpTypeStyleHelper { protected readonly struct State { public readonly UseVarPreference TypeStylePreference; private readonly ReportDiagnostic _forBuiltInTypes; private readonly ReportDiagnostic _whenTypeIsApparent; private readonly ReportDiagnostic _elsewhere; public readonly bool IsInIntrinsicTypeContext; public readonly bool IsTypeApparentInContext; public State( SyntaxNode declaration, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { TypeStylePreference = default; IsInIntrinsicTypeContext = default; IsTypeApparentInContext = default; var styleForIntrinsicTypes = optionSet.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes); var styleForApparent = optionSet.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent); var styleForElsewhere = optionSet.GetOption(CSharpCodeStyleOptions.VarElsewhere); _forBuiltInTypes = styleForIntrinsicTypes.Notification.Severity; _whenTypeIsApparent = styleForApparent.Notification.Severity; _elsewhere = styleForElsewhere.Notification.Severity; var stylePreferences = UseVarPreference.None; if (styleForIntrinsicTypes.Value) stylePreferences |= UseVarPreference.ForBuiltInTypes; if (styleForApparent.Value) stylePreferences |= UseVarPreference.WhenTypeIsApparent; if (styleForElsewhere.Value) stylePreferences |= UseVarPreference.Elsewhere; this.TypeStylePreference = stylePreferences; IsTypeApparentInContext = declaration.IsKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax? varDecl) && IsTypeApparentInDeclaration(varDecl, semanticModel, TypeStylePreference, cancellationToken); IsInIntrinsicTypeContext = IsPredefinedTypeInDeclaration(declaration, semanticModel) || IsInferredPredefinedType(declaration, semanticModel); } public ReportDiagnostic GetDiagnosticSeverityPreference() => IsInIntrinsicTypeContext ? _forBuiltInTypes : IsTypeApparentInContext ? _whenTypeIsApparent : _elsewhere; /// <summary> /// Returns true if type information could be gleaned by simply looking at the given statement. /// This typically means that the type name occurs in right hand side of an assignment. /// </summary> private static bool IsTypeApparentInDeclaration(VariableDeclarationSyntax variableDeclaration, SemanticModel semanticModel, UseVarPreference stylePreferences, CancellationToken cancellationToken) { if (variableDeclaration.Variables.Count != 1) { return false; } var initializer = variableDeclaration.Variables[0].Initializer; if (initializer == null) { return false; } var initializerExpression = CSharpUseImplicitTypeHelper.GetInitializerExpression(initializer.Value); var declaredTypeSymbol = semanticModel.GetTypeInfo(variableDeclaration.Type.StripRefIfNeeded(), cancellationToken).Type; return TypeStyleHelper.IsTypeApparentInAssignmentExpression(stylePreferences, initializerExpression, semanticModel, declaredTypeSymbol, cancellationToken); } /// <summary> /// checks if the type represented by the given symbol is one of the /// simple types defined in the compiler. /// </summary> /// <remarks> /// From the IDE perspective, we also include object and string to be simplified /// to var. <see cref="SyntaxFacts.IsPredefinedType(SyntaxKind)"/> considers string /// and object but the compiler's implementation of IsIntrinsicType does not. /// </remarks> private static bool IsPredefinedTypeInDeclaration(SyntaxNode declarationStatement, SemanticModel semanticModel) { var typeSyntax = GetTypeSyntaxFromDeclaration(declarationStatement); return typeSyntax != null ? IsMadeOfSpecialTypes(semanticModel.GetTypeInfo(typeSyntax.StripRefIfNeeded()).Type) : false; } /// <summary> /// Returns true for type that are arrays/nullable/pointer types of special types /// </summary> private static bool IsMadeOfSpecialTypes([NotNullWhen(true)] ITypeSymbol? type) { if (type == null) { return false; } while (true) { type = type.RemoveNullableIfPresent(); if (type.IsArrayType()) { type = ((IArrayTypeSymbol)type).ElementType; continue; } if (type.IsPointerType()) { type = ((IPointerTypeSymbol)type).PointedAtType; continue; } return type.IsSpecialType(); } } private static bool IsInferredPredefinedType(SyntaxNode declarationStatement, SemanticModel semanticModel) { var typeSyntax = GetTypeSyntaxFromDeclaration(declarationStatement); return typeSyntax != null && typeSyntax.IsTypeInferred(semanticModel) && semanticModel.GetTypeInfo(typeSyntax).Type?.IsSpecialType() == true; } private static TypeSyntax? GetTypeSyntaxFromDeclaration(SyntaxNode declarationStatement) => declarationStatement switch { VariableDeclarationSyntax varDecl => varDecl.Type, ForEachStatementSyntax forEach => forEach.Type, DeclarationExpressionSyntax declExpr => declExpr.Type, _ => null, }; } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/Core/Portable/ChangeSignature/CallSiteKind.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.ChangeSignature { internal enum CallSiteKind { /// <summary> /// Use an explicit value to populate call sites, without forcing /// the addition of a named argument. /// </summary> Value, /// <summary> /// Use an explicit value to populate call sites, and convert /// arguments to named arguments even if not required. Often /// useful for literal callsite values like "true" or "null". /// </summary> ValueWithName, /// <summary> /// Indicates whether a "TODO" should be introduced at callsites /// to cause errors that the user can then go visit and fix up. /// </summary> Todo, /// <summary> /// When an optional parameter is added, passing an argument for /// it is not required. This indicates that the corresponding argument /// should be omitted. This often results in subsequent arguments needing /// to become named arguments /// </summary> Omitted, /// <summary> /// Populate each call site with an available variable of a matching types. /// If no matching variable is found, this falls back to the /// <see cref="Todo"/> behavior. /// </summary> Inferred } }
// 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.ChangeSignature { internal enum CallSiteKind { /// <summary> /// Use an explicit value to populate call sites, without forcing /// the addition of a named argument. /// </summary> Value, /// <summary> /// Use an explicit value to populate call sites, and convert /// arguments to named arguments even if not required. Often /// useful for literal callsite values like "true" or "null". /// </summary> ValueWithName, /// <summary> /// Indicates whether a "TODO" should be introduced at callsites /// to cause errors that the user can then go visit and fix up. /// </summary> Todo, /// <summary> /// When an optional parameter is added, passing an argument for /// it is not required. This indicates that the corresponding argument /// should be omitted. This often results in subsequent arguments needing /// to become named arguments /// </summary> Omitted, /// <summary> /// Populate each call site with an available variable of a matching types. /// If no matching variable is found, this falls back to the /// <see cref="Todo"/> behavior. /// </summary> Inferred } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.InternalsVisibleTo.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.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestPrivateMethodNotSeenInDownstreamProjectWithoutIVT(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> public class C { private static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.Goo(); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodNotSeenInDownstreamProjectWithoutIVT(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.Goo(); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestPrivateMethodNotSeenInDownstreamProjectWithIVT(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("P2")] public class C { private static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.Goo(); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_SimpleString(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_WithAttributeSuffix(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleToAttribute("P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_QualifiedAttributeName(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_VerbatimString(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(@"P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_UsingAlias(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using X = System.Runtime.CompilerServices.InternalsVisibleToAttribute; [assembly: X(@"P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_NonLiteralString(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("P" + "2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) 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.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestPrivateMethodNotSeenInDownstreamProjectWithoutIVT(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> public class C { private static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.Goo(); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodNotSeenInDownstreamProjectWithoutIVT(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.Goo(); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestPrivateMethodNotSeenInDownstreamProjectWithIVT(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("P2")] public class C { private static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.Goo(); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_SimpleString(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_WithAttributeSuffix(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleToAttribute("P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_QualifiedAttributeName(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_VerbatimString(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(@"P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_UsingAlias(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using X = System.Runtime.CompilerServices.InternalsVisibleToAttribute; [assembly: X(@"P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_NonLiteralString(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("P" + "2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function End Class End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/EditorFeatures/CSharpTest2/Recommendations/NotKeywordRecommenderTests.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 Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class NotKeywordRecommenderTests : KeywordRecommenderTests { private const string InitializeObjectE = @"object e = new object(); "; [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIsKeyword() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNotKeyword() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is not $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNotKeywordAndOpenParen() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is not ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAndKeyword_IntExpression() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 and $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAndKeyword_StrExpression() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is ""str"" and $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAndKeyword_RelationalExpression() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is <= 1 and $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOpenParen() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMultipleOpenParen() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is ((($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleofCompletePattern() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is $$ 1 or 2)")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleOfCompleteQualifiedPattern() { await VerifyKeywordAsync( @"namespace N { class C { const int P = 1; void M() { if (e is $$ N.C.P or 2) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleOfCompleteQualifiedPattern_List() { await VerifyKeywordAsync( @"namespace N { class C { const int P = 1; void M() { if (e is $$ System.Collections.Generic.List<int> or 2) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleofCompletePattern_MultipleParens() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is ((($$ 1 or 2))))")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtBeginningOfSwitchExpression() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"var result = e switch { $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtBeginningOfSwitchStatement() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"switch (e) { case $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleOfSwitchExpression() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"var result = e switch { 1 => 2, $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleOfSwitchStatement() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"switch (e) { case 1: case $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtBeginningOfSwitchExpression_AfterOpenParen() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"var result = e switch { ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleOfSwitchExpression_AfterOpenParen() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"var result = e switch { 1 => 2, ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleOfSwitchExpression_ComplexCase() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"var result = e switch { 1 and ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtBeginningOfSwitchStatement_AfterOpenParen() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"switch (e) { case ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtBeginningOfSwitchStatement_AfterOpenParen_CompleteStatement() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"switch (e) { case ($$ 1)")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideSubpattern() { await VerifyKeywordAsync( @"class C { public int P { get; } void M(C test) { if (test is { P: $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideSubpattern_ExtendedProperty() { await VerifyKeywordAsync( @"class C { public C P { get; } public int P2 { get; } void M(C test) { if (test is { P.P2: $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideSubpattern_AfterOpenParen() { await VerifyKeywordAsync( @"class C { public int P { get; } void M(C test) { if (test is { P: ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideSubpattern_AfterOpenParen_Complex() { await VerifyKeywordAsync( @"class C { public int P { get; } void M(C test) { if (test is { P: (1 or $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterConstant() { await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterMultipleConstants() { await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 or 2 $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterType() { await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is int $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRelationalOperator() { await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is >= 0 $$")); } } }
// 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 Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class NotKeywordRecommenderTests : KeywordRecommenderTests { private const string InitializeObjectE = @"object e = new object(); "; [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIsKeyword() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNotKeyword() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is not $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNotKeywordAndOpenParen() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is not ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAndKeyword_IntExpression() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 and $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAndKeyword_StrExpression() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is ""str"" and $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAndKeyword_RelationalExpression() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is <= 1 and $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOpenParen() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMultipleOpenParen() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is ((($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleofCompletePattern() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is $$ 1 or 2)")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleOfCompleteQualifiedPattern() { await VerifyKeywordAsync( @"namespace N { class C { const int P = 1; void M() { if (e is $$ N.C.P or 2) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleOfCompleteQualifiedPattern_List() { await VerifyKeywordAsync( @"namespace N { class C { const int P = 1; void M() { if (e is $$ System.Collections.Generic.List<int> or 2) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleofCompletePattern_MultipleParens() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"if (e is ((($$ 1 or 2))))")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtBeginningOfSwitchExpression() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"var result = e switch { $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtBeginningOfSwitchStatement() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"switch (e) { case $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleOfSwitchExpression() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"var result = e switch { 1 => 2, $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleOfSwitchStatement() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"switch (e) { case 1: case $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtBeginningOfSwitchExpression_AfterOpenParen() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"var result = e switch { ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleOfSwitchExpression_AfterOpenParen() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"var result = e switch { 1 => 2, ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMiddleOfSwitchExpression_ComplexCase() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"var result = e switch { 1 and ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtBeginningOfSwitchStatement_AfterOpenParen() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"switch (e) { case ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtBeginningOfSwitchStatement_AfterOpenParen_CompleteStatement() { await VerifyKeywordAsync(AddInsideMethod(InitializeObjectE + @"switch (e) { case ($$ 1)")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideSubpattern() { await VerifyKeywordAsync( @"class C { public int P { get; } void M(C test) { if (test is { P: $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideSubpattern_ExtendedProperty() { await VerifyKeywordAsync( @"class C { public C P { get; } public int P2 { get; } void M(C test) { if (test is { P.P2: $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideSubpattern_AfterOpenParen() { await VerifyKeywordAsync( @"class C { public int P { get; } void M(C test) { if (test is { P: ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideSubpattern_AfterOpenParen_Complex() { await VerifyKeywordAsync( @"class C { public int P { get; } void M(C test) { if (test is { P: (1 or $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterConstant() { await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterMultipleConstants() { await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is 1 or 2 $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterType() { await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is int $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRelationalOperator() { await VerifyAbsenceAsync(AddInsideMethod(InitializeObjectE + @"if (e is >= 0 $$")); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/Core/Portable/SymbolDisplay/ObjectDisplayOptions.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; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the options for how generics are displayed in the description of a symbol. /// </summary> [Flags] internal enum ObjectDisplayOptions { /// <summary> /// Format object using default options. /// </summary> None = 0, /// <summary> /// In C#, include the numeric code point before character literals. /// </summary> IncludeCodePoints = 1 << 0, /// <summary> /// Whether or not to include type suffix for applicable integral literals. /// </summary> IncludeTypeSuffix = 1 << 1, /// <summary> /// Whether or not to display integral literals in hexadecimal. /// </summary> UseHexadecimalNumbers = 1 << 2, /// <summary> /// Whether or not to quote character and string literals. /// </summary> UseQuotes = 1 << 3, /// <summary> /// In C#, replace non-printable (e.g. control) characters with dedicated (e.g. \t) or unicode (\u0001) escape sequences. /// In Visual Basic, replace non-printable characters with calls to ChrW and vb* constants. /// </summary> EscapeNonPrintableCharacters = 1 << 4, } }
// 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; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the options for how generics are displayed in the description of a symbol. /// </summary> [Flags] internal enum ObjectDisplayOptions { /// <summary> /// Format object using default options. /// </summary> None = 0, /// <summary> /// In C#, include the numeric code point before character literals. /// </summary> IncludeCodePoints = 1 << 0, /// <summary> /// Whether or not to include type suffix for applicable integral literals. /// </summary> IncludeTypeSuffix = 1 << 1, /// <summary> /// Whether or not to display integral literals in hexadecimal. /// </summary> UseHexadecimalNumbers = 1 << 2, /// <summary> /// Whether or not to quote character and string literals. /// </summary> UseQuotes = 1 << 3, /// <summary> /// In C#, replace non-printable (e.g. control) characters with dedicated (e.g. \t) or unicode (\u0001) escape sequences. /// In Visual Basic, replace non-printable characters with calls to ChrW and vb* constants. /// </summary> EscapeNonPrintableCharacters = 1 << 4, } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/Core/Portable/Operations/OperationVisitor.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.Operations { /// <summary> /// Represents a <see cref="IOperation"/> visitor that visits only the single IOperation /// passed into its Visit method. /// </summary> public abstract partial class OperationVisitor { // Make public after review: https://github.com/dotnet/roslyn/issues/21281 internal virtual void VisitFixed(IFixedOperation operation) => // https://github.com/dotnet/roslyn/issues/21281 //DefaultVisit(operation); VisitNoneOperation(operation); } /// <summary> /// Represents a <see cref="IOperation"/> visitor that visits only the single IOperation /// passed into its Visit method with an additional argument of the type specified by the /// <typeparamref name="TArgument"/> parameter and produces a value of the type specified by /// the <typeparamref name="TResult"/> parameter. /// </summary> /// <typeparam name="TArgument"> /// The type of the additional argument passed to this visitor's Visit method. /// </typeparam> /// <typeparam name="TResult"> /// The type of the return value of this visitor's Visit method. /// </typeparam> public abstract partial class OperationVisitor<TArgument, TResult> { // Make public after review: https://github.com/dotnet/roslyn/issues/21281 internal virtual TResult? VisitFixed(IFixedOperation operation, TArgument argument) => // https://github.com/dotnet/roslyn/issues/21281 //return DefaultVisit(operation, argument); VisitNoneOperation(operation, argument); } }
// 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.Operations { /// <summary> /// Represents a <see cref="IOperation"/> visitor that visits only the single IOperation /// passed into its Visit method. /// </summary> public abstract partial class OperationVisitor { // Make public after review: https://github.com/dotnet/roslyn/issues/21281 internal virtual void VisitFixed(IFixedOperation operation) => // https://github.com/dotnet/roslyn/issues/21281 //DefaultVisit(operation); VisitNoneOperation(operation); } /// <summary> /// Represents a <see cref="IOperation"/> visitor that visits only the single IOperation /// passed into its Visit method with an additional argument of the type specified by the /// <typeparamref name="TArgument"/> parameter and produces a value of the type specified by /// the <typeparamref name="TResult"/> parameter. /// </summary> /// <typeparam name="TArgument"> /// The type of the additional argument passed to this visitor's Visit method. /// </typeparam> /// <typeparam name="TResult"> /// The type of the return value of this visitor's Visit method. /// </typeparam> public abstract partial class OperationVisitor<TArgument, TResult> { // Make public after review: https://github.com/dotnet/roslyn/issues/21281 internal virtual TResult? VisitFixed(IFixedOperation operation, TArgument argument) => // https://github.com/dotnet/roslyn/issues/21281 //return DefaultVisit(operation, argument); VisitNoneOperation(operation, argument); } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/CSharp/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.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.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("InvocationExpressionSignatureHelpProvider", LanguageNames.CSharp), Shared] internal sealed class InvocationExpressionSignatureHelpProvider : InvocationExpressionSignatureHelpProviderBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InvocationExpressionSignatureHelpProvider() { } } internal partial class InvocationExpressionSignatureHelpProviderBase : AbstractOrdinaryMethodSignatureHelpProvider { public override bool IsTriggerCharacter(char ch) => ch == '(' || ch == ','; public override bool IsRetriggerCharacter(char ch) => ch == ')'; private bool TryGetInvocationExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out InvocationExpressionSyntax expression) { if (!CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out expression)) { return false; } return expression.ArgumentList != null; } private bool IsTriggerToken(SyntaxToken token) => SignatureHelpUtilities.IsTriggerParenOrComma<InvocationExpressionSyntax>(token, IsTriggerCharacter); private static bool IsArgumentListToken(InvocationExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseParenToken; } protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!TryGetInvocationExpression(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out var invocationExpression)) { return null; } var semanticModel = await document.ReuseExistingSpeculativeModelAsync(invocationExpression, cancellationToken).ConfigureAwait(false); var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within == null) { return null; } // get the regular signature help items var methodGroup = semanticModel.GetMemberGroup(invocationExpression.Expression, cancellationToken) .OfType<IMethodSymbol>() .ToImmutableArray() .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation); // try to bind to the actual method var symbolInfo = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken); // if the symbol could be bound, replace that item in the symbol list if (symbolInfo.Symbol is IMethodSymbol matchedMethodSymbol && matchedMethodSymbol.IsGenericMethod) { methodGroup = methodGroup.SelectAsArray(m => Equals(matchedMethodSymbol.OriginalDefinition, m) ? matchedMethodSymbol : m); } methodGroup = methodGroup.Sort( semanticModel, invocationExpression.SpanStart); var anonymousTypeDisplayService = document.Project.LanguageServices.GetRequiredService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.Project.LanguageServices.GetRequiredService<IDocumentationCommentFormattingService>(); var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(invocationExpression.ArgumentList); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (methodGroup.Any()) { var accessibleMethods = GetAccessibleMethods(invocationExpression, semanticModel, within, methodGroup, cancellationToken); var (items, selectedItem) = await GetMethodGroupItemsAndSelectionAsync(accessibleMethods, document, invocationExpression, semanticModel, symbolInfo, cancellationToken).ConfigureAwait(false); return CreateSignatureHelpItems( items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } var invokedType = semanticModel.GetTypeInfo(invocationExpression.Expression, cancellationToken).Type; if (invokedType is INamedTypeSymbol expressionType && expressionType.TypeKind == TypeKind.Delegate) { var items = GetDelegateInvokeItems(invocationExpression, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService, within, expressionType, out var selectedItem, cancellationToken); return CreateSignatureHelpItems(items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } else if (invokedType is IFunctionPointerTypeSymbol functionPointerType) { var items = GetFunctionPointerInvokeItems(invocationExpression, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService, functionPointerType, out var selectedItem, cancellationToken); return CreateSignatureHelpItems(items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } return null; } public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (TryGetInvocationExpression( root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var expression) && currentSpan.Start == SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start) { return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position); } 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. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("InvocationExpressionSignatureHelpProvider", LanguageNames.CSharp), Shared] internal sealed class InvocationExpressionSignatureHelpProvider : InvocationExpressionSignatureHelpProviderBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InvocationExpressionSignatureHelpProvider() { } } internal partial class InvocationExpressionSignatureHelpProviderBase : AbstractOrdinaryMethodSignatureHelpProvider { public override bool IsTriggerCharacter(char ch) => ch == '(' || ch == ','; public override bool IsRetriggerCharacter(char ch) => ch == ')'; private bool TryGetInvocationExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out InvocationExpressionSyntax expression) { if (!CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out expression)) { return false; } return expression.ArgumentList != null; } private bool IsTriggerToken(SyntaxToken token) => SignatureHelpUtilities.IsTriggerParenOrComma<InvocationExpressionSyntax>(token, IsTriggerCharacter); private static bool IsArgumentListToken(InvocationExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseParenToken; } protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!TryGetInvocationExpression(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out var invocationExpression)) { return null; } var semanticModel = await document.ReuseExistingSpeculativeModelAsync(invocationExpression, cancellationToken).ConfigureAwait(false); var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within == null) { return null; } // get the regular signature help items var methodGroup = semanticModel.GetMemberGroup(invocationExpression.Expression, cancellationToken) .OfType<IMethodSymbol>() .ToImmutableArray() .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation); // try to bind to the actual method var symbolInfo = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken); // if the symbol could be bound, replace that item in the symbol list if (symbolInfo.Symbol is IMethodSymbol matchedMethodSymbol && matchedMethodSymbol.IsGenericMethod) { methodGroup = methodGroup.SelectAsArray(m => Equals(matchedMethodSymbol.OriginalDefinition, m) ? matchedMethodSymbol : m); } methodGroup = methodGroup.Sort( semanticModel, invocationExpression.SpanStart); var anonymousTypeDisplayService = document.Project.LanguageServices.GetRequiredService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.Project.LanguageServices.GetRequiredService<IDocumentationCommentFormattingService>(); var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(invocationExpression.ArgumentList); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (methodGroup.Any()) { var accessibleMethods = GetAccessibleMethods(invocationExpression, semanticModel, within, methodGroup, cancellationToken); var (items, selectedItem) = await GetMethodGroupItemsAndSelectionAsync(accessibleMethods, document, invocationExpression, semanticModel, symbolInfo, cancellationToken).ConfigureAwait(false); return CreateSignatureHelpItems( items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } var invokedType = semanticModel.GetTypeInfo(invocationExpression.Expression, cancellationToken).Type; if (invokedType is INamedTypeSymbol expressionType && expressionType.TypeKind == TypeKind.Delegate) { var items = GetDelegateInvokeItems(invocationExpression, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService, within, expressionType, out var selectedItem, cancellationToken); return CreateSignatureHelpItems(items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } else if (invokedType is IFunctionPointerTypeSymbol functionPointerType) { var items = GetFunctionPointerInvokeItems(invocationExpression, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService, functionPointerType, out var selectedItem, cancellationToken); return CreateSignatureHelpItems(items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } return null; } public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (TryGetInvocationExpression( root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var expression) && currentSpan.Start == SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start) { return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position); } return null; } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/VisualStudio/Core/Def/Implementation/Library/AbstractLibraryManager_IVsLibrary2.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 Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library { internal partial class AbstractLibraryManager : IVsLibrary2 { int IVsLibrary2.AddBrowseContainer(VSCOMPONENTSELECTORDATA[] pcdComponent, ref uint pgrfOptions, string[] pbstrComponentAdded) => VSConstants.E_NOTIMPL; int IVsLibrary2.CreateNavInfo(SYMBOL_DESCRIPTION_NODE[] rgSymbolNodes, uint ulcNodes, out IVsNavInfo ppNavInfo) { ppNavInfo = null; return VSConstants.E_NOTIMPL; } int IVsLibrary2.GetBrowseContainersForHierarchy(IVsHierarchy pHierarchy, uint celt, VSBROWSECONTAINER[] rgBrowseContainers, uint[] pcActual) => VSConstants.E_NOTIMPL; int IVsLibrary2.GetGuid(out IntPtr ppguidLib) { ppguidLib = IntPtr.Zero; return VSConstants.E_NOTIMPL; } int IVsLibrary2.GetLibFlags2(out uint pgrfFlags) { pgrfFlags = 0; return VSConstants.E_NOTIMPL; } int IVsLibrary2.GetLibList(LIB_PERSISTTYPE lptType, out IVsLiteTreeList ppList) { ppList = null; return VSConstants.E_NOTIMPL; } int IVsLibrary2.GetList2(uint listType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch, out IVsObjectList2 ppIVsObjectList2) { ppIVsObjectList2 = null; return VSConstants.E_NOTIMPL; } int IVsLibrary2.GetSeparatorString(IntPtr pszSeparator) => VSConstants.E_NOTIMPL; int IVsLibrary2.GetSupportedCategoryFields2(int category, out uint pgrfCatField) { pgrfCatField = 0; return VSConstants.E_NOTIMPL; } int IVsLibrary2.LoadState(IStream pIStream, LIB_PERSISTTYPE lptType) => VSConstants.E_NOTIMPL; int IVsLibrary2.RemoveBrowseContainer(uint dwReserved, string pszLibName) => VSConstants.E_NOTIMPL; int IVsLibrary2.SaveState(IStream pIStream, LIB_PERSISTTYPE lptType) => VSConstants.E_NOTIMPL; int IVsLibrary2.UpdateCounter(out uint pCurUpdate) { pCurUpdate = 0; return VSConstants.E_NOTIMPL; } } }
// 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 Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library { internal partial class AbstractLibraryManager : IVsLibrary2 { int IVsLibrary2.AddBrowseContainer(VSCOMPONENTSELECTORDATA[] pcdComponent, ref uint pgrfOptions, string[] pbstrComponentAdded) => VSConstants.E_NOTIMPL; int IVsLibrary2.CreateNavInfo(SYMBOL_DESCRIPTION_NODE[] rgSymbolNodes, uint ulcNodes, out IVsNavInfo ppNavInfo) { ppNavInfo = null; return VSConstants.E_NOTIMPL; } int IVsLibrary2.GetBrowseContainersForHierarchy(IVsHierarchy pHierarchy, uint celt, VSBROWSECONTAINER[] rgBrowseContainers, uint[] pcActual) => VSConstants.E_NOTIMPL; int IVsLibrary2.GetGuid(out IntPtr ppguidLib) { ppguidLib = IntPtr.Zero; return VSConstants.E_NOTIMPL; } int IVsLibrary2.GetLibFlags2(out uint pgrfFlags) { pgrfFlags = 0; return VSConstants.E_NOTIMPL; } int IVsLibrary2.GetLibList(LIB_PERSISTTYPE lptType, out IVsLiteTreeList ppList) { ppList = null; return VSConstants.E_NOTIMPL; } int IVsLibrary2.GetList2(uint listType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch, out IVsObjectList2 ppIVsObjectList2) { ppIVsObjectList2 = null; return VSConstants.E_NOTIMPL; } int IVsLibrary2.GetSeparatorString(IntPtr pszSeparator) => VSConstants.E_NOTIMPL; int IVsLibrary2.GetSupportedCategoryFields2(int category, out uint pgrfCatField) { pgrfCatField = 0; return VSConstants.E_NOTIMPL; } int IVsLibrary2.LoadState(IStream pIStream, LIB_PERSISTTYPE lptType) => VSConstants.E_NOTIMPL; int IVsLibrary2.RemoveBrowseContainer(uint dwReserved, string pszLibName) => VSConstants.E_NOTIMPL; int IVsLibrary2.SaveState(IStream pIStream, LIB_PERSISTTYPE lptType) => VSConstants.E_NOTIMPL; int IVsLibrary2.UpdateCounter(out uint pCurUpdate) { pCurUpdate = 0; return VSConstants.E_NOTIMPL; } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerActionCounts.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 namespace Microsoft.CodeAnalysis.Diagnostics.Telemetry { /// <summary> /// Contains the counts of registered actions for an analyzer. /// </summary> internal class AnalyzerActionCounts { internal static readonly AnalyzerActionCounts Empty = new AnalyzerActionCounts(in AnalyzerActions.Empty); internal AnalyzerActionCounts(in AnalyzerActions analyzerActions) : this( analyzerActions.CompilationStartActionsCount, analyzerActions.CompilationEndActionsCount, analyzerActions.CompilationActionsCount, analyzerActions.SyntaxTreeActionsCount, analyzerActions.AdditionalFileActionsCount, analyzerActions.SemanticModelActionsCount, analyzerActions.SymbolActionsCount, analyzerActions.SymbolStartActionsCount, analyzerActions.SymbolEndActionsCount, analyzerActions.SyntaxNodeActionsCount, analyzerActions.CodeBlockStartActionsCount, analyzerActions.CodeBlockEndActionsCount, analyzerActions.CodeBlockActionsCount, analyzerActions.OperationActionsCount, analyzerActions.OperationBlockStartActionsCount, analyzerActions.OperationBlockEndActionsCount, analyzerActions.OperationBlockActionsCount, analyzerActions.Concurrent) { } internal AnalyzerActionCounts( int compilationStartActionsCount, int compilationEndActionsCount, int compilationActionsCount, int syntaxTreeActionsCount, int additionalFileActionsCount, int semanticModelActionsCount, int symbolActionsCount, int symbolStartActionsCount, int symbolEndActionsCount, int syntaxNodeActionsCount, int codeBlockStartActionsCount, int codeBlockEndActionsCount, int codeBlockActionsCount, int operationActionsCount, int operationBlockStartActionsCount, int operationBlockEndActionsCount, int operationBlockActionsCount, bool concurrent) { CompilationStartActionsCount = compilationStartActionsCount; CompilationEndActionsCount = compilationEndActionsCount; CompilationActionsCount = compilationActionsCount; SyntaxTreeActionsCount = syntaxTreeActionsCount; AdditionalFileActionsCount = additionalFileActionsCount; SemanticModelActionsCount = semanticModelActionsCount; SymbolActionsCount = symbolActionsCount; SymbolStartActionsCount = symbolStartActionsCount; SymbolEndActionsCount = symbolEndActionsCount; SyntaxNodeActionsCount = syntaxNodeActionsCount; CodeBlockStartActionsCount = codeBlockStartActionsCount; CodeBlockEndActionsCount = codeBlockEndActionsCount; CodeBlockActionsCount = codeBlockActionsCount; OperationActionsCount = operationActionsCount; OperationBlockStartActionsCount = operationBlockStartActionsCount; OperationBlockEndActionsCount = operationBlockEndActionsCount; OperationBlockActionsCount = operationBlockActionsCount; Concurrent = concurrent; HasAnyExecutableCodeActions = CodeBlockActionsCount > 0 || CodeBlockStartActionsCount > 0 || SyntaxNodeActionsCount > 0 || OperationActionsCount > 0 || OperationBlockActionsCount > 0 || OperationBlockStartActionsCount > 0 || SymbolStartActionsCount > 0; } /// <summary> /// Count of registered compilation start actions. /// </summary> public int CompilationStartActionsCount { get; } /// <summary> /// Count of registered compilation end actions. /// </summary> public int CompilationEndActionsCount { get; } /// <summary> /// Count of registered compilation actions. /// </summary> public int CompilationActionsCount { get; } /// <summary> /// Count of registered syntax tree actions. /// </summary> public int SyntaxTreeActionsCount { get; } /// <summary> /// Count of registered additional file actions. /// </summary> public int AdditionalFileActionsCount { get; } /// <summary> /// Count of registered semantic model actions. /// </summary> public int SemanticModelActionsCount { get; } /// <summary> /// Count of registered symbol actions. /// </summary> public int SymbolActionsCount { get; } /// <summary> /// Count of registered symbol start actions. /// </summary> public int SymbolStartActionsCount { get; } /// <summary> /// Count of registered symbol end actions. /// </summary> public int SymbolEndActionsCount { get; } /// <summary> /// Count of registered syntax node actions. /// </summary> public int SyntaxNodeActionsCount { get; } /// <summary> /// Count of code block start actions. /// </summary> public int CodeBlockStartActionsCount { get; } /// <summary> /// Count of code block end actions. /// </summary> public int CodeBlockEndActionsCount { get; } /// <summary> /// Count of code block actions. /// </summary> public int CodeBlockActionsCount { get; } /// <summary> /// Count of Operation actions. /// </summary> public int OperationActionsCount { get; } /// <summary> /// Count of Operation block start actions. /// </summary> public int OperationBlockStartActionsCount { get; } /// <summary> /// Count of Operation block end actions. /// </summary> public int OperationBlockEndActionsCount { get; } /// <summary> /// Count of Operation block actions. /// </summary> public int OperationBlockActionsCount { get; } /// <summary> /// Returns true if there are any actions that need to run on executable code. /// </summary> public bool HasAnyExecutableCodeActions { get; } /// <summary> /// Gets a value indicating whether the analyzer supports concurrent execution. /// </summary> public bool Concurrent { 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 namespace Microsoft.CodeAnalysis.Diagnostics.Telemetry { /// <summary> /// Contains the counts of registered actions for an analyzer. /// </summary> internal class AnalyzerActionCounts { internal static readonly AnalyzerActionCounts Empty = new AnalyzerActionCounts(in AnalyzerActions.Empty); internal AnalyzerActionCounts(in AnalyzerActions analyzerActions) : this( analyzerActions.CompilationStartActionsCount, analyzerActions.CompilationEndActionsCount, analyzerActions.CompilationActionsCount, analyzerActions.SyntaxTreeActionsCount, analyzerActions.AdditionalFileActionsCount, analyzerActions.SemanticModelActionsCount, analyzerActions.SymbolActionsCount, analyzerActions.SymbolStartActionsCount, analyzerActions.SymbolEndActionsCount, analyzerActions.SyntaxNodeActionsCount, analyzerActions.CodeBlockStartActionsCount, analyzerActions.CodeBlockEndActionsCount, analyzerActions.CodeBlockActionsCount, analyzerActions.OperationActionsCount, analyzerActions.OperationBlockStartActionsCount, analyzerActions.OperationBlockEndActionsCount, analyzerActions.OperationBlockActionsCount, analyzerActions.Concurrent) { } internal AnalyzerActionCounts( int compilationStartActionsCount, int compilationEndActionsCount, int compilationActionsCount, int syntaxTreeActionsCount, int additionalFileActionsCount, int semanticModelActionsCount, int symbolActionsCount, int symbolStartActionsCount, int symbolEndActionsCount, int syntaxNodeActionsCount, int codeBlockStartActionsCount, int codeBlockEndActionsCount, int codeBlockActionsCount, int operationActionsCount, int operationBlockStartActionsCount, int operationBlockEndActionsCount, int operationBlockActionsCount, bool concurrent) { CompilationStartActionsCount = compilationStartActionsCount; CompilationEndActionsCount = compilationEndActionsCount; CompilationActionsCount = compilationActionsCount; SyntaxTreeActionsCount = syntaxTreeActionsCount; AdditionalFileActionsCount = additionalFileActionsCount; SemanticModelActionsCount = semanticModelActionsCount; SymbolActionsCount = symbolActionsCount; SymbolStartActionsCount = symbolStartActionsCount; SymbolEndActionsCount = symbolEndActionsCount; SyntaxNodeActionsCount = syntaxNodeActionsCount; CodeBlockStartActionsCount = codeBlockStartActionsCount; CodeBlockEndActionsCount = codeBlockEndActionsCount; CodeBlockActionsCount = codeBlockActionsCount; OperationActionsCount = operationActionsCount; OperationBlockStartActionsCount = operationBlockStartActionsCount; OperationBlockEndActionsCount = operationBlockEndActionsCount; OperationBlockActionsCount = operationBlockActionsCount; Concurrent = concurrent; HasAnyExecutableCodeActions = CodeBlockActionsCount > 0 || CodeBlockStartActionsCount > 0 || SyntaxNodeActionsCount > 0 || OperationActionsCount > 0 || OperationBlockActionsCount > 0 || OperationBlockStartActionsCount > 0 || SymbolStartActionsCount > 0; } /// <summary> /// Count of registered compilation start actions. /// </summary> public int CompilationStartActionsCount { get; } /// <summary> /// Count of registered compilation end actions. /// </summary> public int CompilationEndActionsCount { get; } /// <summary> /// Count of registered compilation actions. /// </summary> public int CompilationActionsCount { get; } /// <summary> /// Count of registered syntax tree actions. /// </summary> public int SyntaxTreeActionsCount { get; } /// <summary> /// Count of registered additional file actions. /// </summary> public int AdditionalFileActionsCount { get; } /// <summary> /// Count of registered semantic model actions. /// </summary> public int SemanticModelActionsCount { get; } /// <summary> /// Count of registered symbol actions. /// </summary> public int SymbolActionsCount { get; } /// <summary> /// Count of registered symbol start actions. /// </summary> public int SymbolStartActionsCount { get; } /// <summary> /// Count of registered symbol end actions. /// </summary> public int SymbolEndActionsCount { get; } /// <summary> /// Count of registered syntax node actions. /// </summary> public int SyntaxNodeActionsCount { get; } /// <summary> /// Count of code block start actions. /// </summary> public int CodeBlockStartActionsCount { get; } /// <summary> /// Count of code block end actions. /// </summary> public int CodeBlockEndActionsCount { get; } /// <summary> /// Count of code block actions. /// </summary> public int CodeBlockActionsCount { get; } /// <summary> /// Count of Operation actions. /// </summary> public int OperationActionsCount { get; } /// <summary> /// Count of Operation block start actions. /// </summary> public int OperationBlockStartActionsCount { get; } /// <summary> /// Count of Operation block end actions. /// </summary> public int OperationBlockEndActionsCount { get; } /// <summary> /// Count of Operation block actions. /// </summary> public int OperationBlockActionsCount { get; } /// <summary> /// Returns true if there are any actions that need to run on executable code. /// </summary> public bool HasAnyExecutableCodeActions { get; } /// <summary> /// Gets a value indicating whether the analyzer supports concurrent execution. /// </summary> public bool Concurrent { get; } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/Core/Portable/Completion/Providers/AbstractOverrideCompletionProvider.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 System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractOverrideCompletionProvider : AbstractMemberInsertingCompletionProvider { public AbstractOverrideCompletionProvider() { } public abstract SyntaxToken FindStartingToken(SyntaxTree tree, int position, CancellationToken cancellationToken); public abstract ImmutableArray<ISymbol> FilterOverrides(ImmutableArray<ISymbol> members, ITypeSymbol returnType); public abstract bool TryDetermineModifiers(SyntaxToken startToken, SourceText text, int startLine, out Accessibility seenAccessibility, out DeclarationModifiers modifiers); public override async Task ProvideCompletionsAsync(CompletionContext context) { var state = await ItemGetter.CreateAsync(this, context.Document, context.Position, context.CancellationToken).ConfigureAwait(false); var items = await state.GetItemsAsync().ConfigureAwait(false); if (!items.IsDefaultOrEmpty) { context.IsExclusive = true; context.AddItems(items); } } protected override Task<ISymbol> GenerateMemberAsync(ISymbol newOverriddenMember, INamedTypeSymbol newContainingType, Document newDocument, CompletionItem completionItem, CancellationToken cancellationToken) { // Special case: if you are overriding object.ToString(), we will make the return value as non-nullable. The return was made nullable because // are implementations out there that will return null, but that's not something we really want new implementations doing. We may need to consider // expanding this behavior to other methods in the future; if that is the case then we would want there to be an attribute on the return type // rather than updating this list, but for now there is no such attribute until we find more cases for it. See // https://github.com/dotnet/roslyn/issues/30317 for some additional conversation about this design decision. // // We don't check if methodSymbol.ContainingType is object, in case you're overriding something that is itself an override if (newOverriddenMember is IMethodSymbol methodSymbol && methodSymbol.Name == "ToString" && methodSymbol.Parameters.Length == 0) { newOverriddenMember = CodeGenerationSymbolFactory.CreateMethodSymbol(methodSymbol, returnType: methodSymbol.ReturnType.WithNullableAnnotation(NullableAnnotation.NotAnnotated)); } // Figure out what to insert, and do it. Throw if we've somehow managed to get this far and can't. var syntaxFactory = newDocument.GetLanguageService<SyntaxGenerator>(); var itemModifiers = MemberInsertionCompletionItem.GetModifiers(completionItem); var modifiers = itemModifiers.WithIsUnsafe(itemModifiers.IsUnsafe | newOverriddenMember.RequiresUnsafeModifier()); return syntaxFactory.OverrideAsync( newOverriddenMember, newContainingType, newDocument, modifiers, cancellationToken); } public abstract bool TryDetermineReturnType( SyntaxToken startToken, SemanticModel semanticModel, CancellationToken cancellationToken, out ITypeSymbol returnType, out SyntaxToken nextToken); protected static bool IsOnStartLine(int position, SourceText text, int startLine) => text.Lines.IndexOf(position) == startLine; protected static ITypeSymbol GetReturnType(ISymbol symbol) => symbol.Kind switch { SymbolKind.Event => ((IEventSymbol)symbol).Type, SymbolKind.Method => ((IMethodSymbol)symbol).ReturnType, SymbolKind.Property => ((IPropertySymbol)symbol).Type, _ => throw ExceptionUtilities.UnexpectedValue(symbol.Kind), }; } }
// 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 System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractOverrideCompletionProvider : AbstractMemberInsertingCompletionProvider { public AbstractOverrideCompletionProvider() { } public abstract SyntaxToken FindStartingToken(SyntaxTree tree, int position, CancellationToken cancellationToken); public abstract ImmutableArray<ISymbol> FilterOverrides(ImmutableArray<ISymbol> members, ITypeSymbol returnType); public abstract bool TryDetermineModifiers(SyntaxToken startToken, SourceText text, int startLine, out Accessibility seenAccessibility, out DeclarationModifiers modifiers); public override async Task ProvideCompletionsAsync(CompletionContext context) { var state = await ItemGetter.CreateAsync(this, context.Document, context.Position, context.CancellationToken).ConfigureAwait(false); var items = await state.GetItemsAsync().ConfigureAwait(false); if (!items.IsDefaultOrEmpty) { context.IsExclusive = true; context.AddItems(items); } } protected override Task<ISymbol> GenerateMemberAsync(ISymbol newOverriddenMember, INamedTypeSymbol newContainingType, Document newDocument, CompletionItem completionItem, CancellationToken cancellationToken) { // Special case: if you are overriding object.ToString(), we will make the return value as non-nullable. The return was made nullable because // are implementations out there that will return null, but that's not something we really want new implementations doing. We may need to consider // expanding this behavior to other methods in the future; if that is the case then we would want there to be an attribute on the return type // rather than updating this list, but for now there is no such attribute until we find more cases for it. See // https://github.com/dotnet/roslyn/issues/30317 for some additional conversation about this design decision. // // We don't check if methodSymbol.ContainingType is object, in case you're overriding something that is itself an override if (newOverriddenMember is IMethodSymbol methodSymbol && methodSymbol.Name == "ToString" && methodSymbol.Parameters.Length == 0) { newOverriddenMember = CodeGenerationSymbolFactory.CreateMethodSymbol(methodSymbol, returnType: methodSymbol.ReturnType.WithNullableAnnotation(NullableAnnotation.NotAnnotated)); } // Figure out what to insert, and do it. Throw if we've somehow managed to get this far and can't. var syntaxFactory = newDocument.GetLanguageService<SyntaxGenerator>(); var itemModifiers = MemberInsertionCompletionItem.GetModifiers(completionItem); var modifiers = itemModifiers.WithIsUnsafe(itemModifiers.IsUnsafe | newOverriddenMember.RequiresUnsafeModifier()); return syntaxFactory.OverrideAsync( newOverriddenMember, newContainingType, newDocument, modifiers, cancellationToken); } public abstract bool TryDetermineReturnType( SyntaxToken startToken, SemanticModel semanticModel, CancellationToken cancellationToken, out ITypeSymbol returnType, out SyntaxToken nextToken); protected static bool IsOnStartLine(int position, SourceText text, int startLine) => text.Lines.IndexOf(position) == startLine; protected static ITypeSymbol GetReturnType(ISymbol symbol) => symbol.Kind switch { SymbolKind.Event => ((IEventSymbol)symbol).Type, SymbolKind.Method => ((IMethodSymbol)symbol).ReturnType, SymbolKind.Property => ((IPropertySymbol)symbol).Type, _ => throw ExceptionUtilities.UnexpectedValue(symbol.Kind), }; } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/GeneralPia.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.ComponentModel Imports System.ComponentModel.Composition Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("GeneralPIA.dll")> <Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")> Namespace SomeNamespace Public Structure NoAttributesStructure Public Goo1 As Integer Public Goo2 As Integer End Structure End Namespace Public Enum NoAttributesEnum Goo1 Goo2 End Enum Public Delegate Sub NoAttributesDelegate(ByVal x As String, ByVal y As Object) <Guid("ee3c2bee-9dfb-4d1c-91de-4cd32ff13302")> _ Public Enum GooEnum Goo1 __ Goo2 列挙識別子 [Enum] COM End Enum <Guid("63370d76-3395-4560-92fd-b69ccfdaf461")> _ Public Structure GooStruct Public [Structure] As Integer Public NET As Decimal Public 構造メンバー As String Public Goo3 As Object() Public Goo4 As Double() End Structure 'Public Structure GooPrivateStruct ' Public Goo1 As Integer ' Private Goo2 As Long 'End Structure 'Public Structure GooSharedStruct ' Public Shared Field1 As Integer = 4 'End Structure Public Structure GooConstStruct Public Const Field1 As String = "2" End Structure <Guid("bd62ff24-a97c-4a9c-a43e-09a31ff8b312")> _ <ComImport()> _ <InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)> _ Public Interface ISubFuncProp Sub Goo(ByVal p As Integer) Function Bar() As String Property Prop() As <MarshalAs(UnmanagedType.Currency)> Decimal End Interface <Guid("6a97be13-2611-4fc0-9d78-926dccec3243")> _ <ComImport()> _ <InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)> _ Public Interface IDuplicates Function DuplicateA(ByVal x As String) As Object Function DuplicateB(ByVal y As String) As Object Property PropDupeA() As ISubFuncProp Property PropDupeB() As ISubFuncProp End Interface Namespace Parameters <Guid("ed4bf792-06dd-449a-91d7-dde226e9f471")> _ <ComImport()> _ Public Interface IA End Interface <Guid("3b3fce76-b864-4a7c-93f6-87ec17339299")> _ <ComImport()> _ Public Interface IB End Interface <Guid("a6fa1a95-b29f-4f59-b457-29f8a55b3b6e")> _ <ComImport()> _ Public Interface IC End Interface <Guid("906b08a3-e478-4c52-ae30-ecb484ac01f0")> _ <ComImport()> _ Public Interface ID End Interface <Guid("bedd42c1-d023-4f53-8bfd-7c0b9de3aac7")> _ <ComImport()> _ Public Interface IByRef Function Goo(ByRef p1 As IA, ByRef p2 As IB, ByRef p3 As IC, ByRef p4 As Integer, ByRef p5 As Object) As ID Sub Bar(Optional ByRef p1 As IA = Nothing, Optional ByRef p2 As String() = Nothing, Optional ByRef p3 As Double() = Nothing) End Interface <Guid("1313c178-13f6-4450-8360-cf50d751a0f4")> _ <ComImport()> _ Public Interface IOptionalParam Function Goo(Optional ByVal p1 As IA = Nothing, Optional ByVal p2 As IB = Nothing, Optional ByVal p3 As IC = Nothing, Optional ByVal p4 As Integer = 5, Optional ByVal p5 As Object = Nothing) As ID Sub Bar(ByVal p1 As IA, ByVal p2 As String(), ByVal p3 As Double()) End Interface End Namespace Namespace GeneralEventScenario <Guid("00000502-0000-6600-c000-000000000046")> _ <ComImport()> _ Public Interface IEventArgs2 : Inherits IEnumerable Property GetData() As Parameters.IA End Interface Public Delegate Sub EventHandler(ByVal o As Object, ByVal e As EventArgs) Public Delegate Sub EventHandler2(ByVal o As Object, ByVal e As IEventArgs2) ' Calling interface <Guid("00000002-0000-0000-c000-000000000046")> _ <ComImport()> _ <InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> _ Public Interface _Arc <PreserveSig()> _ Function SomeUnusedMethod() As Object <DispId(1558)> _ <LCIDConversion(10)> _ <PreserveSig()> _ Function Cut(<MarshalAs(UnmanagedType.Bool), [In](), Out()> _ ByVal x As Integer) As <MarshalAs(UnmanagedType.Bool)> Object <PreserveSig()> _ Function SomeOtherUnusedMethod() As Object <PreserveSig()> _ Function SomeLastMethod() As Object End Interface ' Class interface <Guid("00000002-0000-0000-c000-000000000046")> _ <ComImport()> _ Public Interface Arc Inherits _Arc Inherits ArcEvent_Event Inherits ArcEvent_Event2 End Interface ' Source interface <Guid("00000002-0000-0000-c000-000000000047")> _ <ComImport()> _ <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _ Public Interface ArcEvent Function One() As Object <DispId(1558)> _ Sub click() Sub move() Sub groove() Sub shake() Sub rattle() End Interface ' Events interface <ComEventInterface(GetType(ArcEvent), GetType(Integer))> _ Public Interface ArcEvent_Event Event click As EventHandler End Interface ' A few more events <ComEventInterface(GetType(ArcEvent), GetType(Integer))> _ Public Interface ArcEvent_Event2 Event move As EventHandler2 Event groove As EventHandler Event shake As EventHandler Event rattle As EventHandler End Interface End Namespace Namespace Inheritance <Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c6c")> _ <ComImport()> _ <InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)> _ Public Interface IBase Sub IBaseSub(ByVal x As Integer) Function IBaseFunc() As Object Property IBaseProp() As String End Interface <Guid("bd60d4b3-f50b-478b-8ef2-e777df99d810")> _ <ComImport()> _ <InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)> _ <CoClass(GetType(DerivedImpl))> _ Public Interface IDerived Inherits IBase Shadows Sub IBaseSub(ByVal x As Integer) Shadows Function IBaseFunc() As Object Shadows Property IBaseProp() As String Sub IDerivedSub(ByVal x As Integer) Function IDerivedFunc() As Object Property IDerivedProp() As String End Interface <Guid("c9dcf748-b634-4504-a7ce-348cf7c61891")> _ Public Class DerivedImpl End Class End Namespace Namespace InheritanceConflict <Guid("76a62998-7740-4ebd-a09f-e401ffff5c8c")> _ <ComImport()> _ Public Interface IBase Sub Goo() Function Bar() As Integer Sub ConflictMethod(ByVal x As Integer) Default Property IndexedProperty(x As Object) As String End Interface <Guid("d6c92e52-47f4-4075-8078-99a21c29c8fa")> _ <ComImport()> _ <CoClass(GetType(DerivedImpl))> _ Public Interface IDerived Inherits IBase ' IBase methods Shadows Sub Goo() Shadows Function Bar() As Integer Shadows Sub ConflictMethod(ByVal x As Integer) Shadows Property IndexedProperty(x As Object) As String ' New methods Shadows Function ConflictMethod(x As Integer, y As String) As Object Shadows Default Property IndexedPropertyDerived(x As Decimal) As Integer End Interface <Guid("7e12bd3c-1ad1-427f-bab8-af82e30d980d")> _ Public Class DerivedImpl End Class End Namespace Namespace LateBound <Guid("43f3a25e-fccb-4b92-adc1-2fe84c922125")> _ <ComImport()> _ Public Interface INoPIAInterface Function Goo(ByVal x As INoPIAInterface) As String Function Bar(ByVal x As Integer, ByVal y As Integer) As String Function Moo() As Integer End Interface <Guid("ae390f6a-e7e4-47d7-a7b2-d95dfe14aac6")> _ <ComImport()> _ Public Interface INoPIAInterface2 Property Blah() As INoPIAInterface Sub Fazz(ByVal x As INoPIAInterface) End Interface End Namespace Namespace NoPIACopyAttributes Class SomeOtherAttribute Inherits Attribute End Class ' from the below attributes, AutomationProxy and CLSCompliant are not preserved <AutomationProxy(True)> _ <Guid("16063cdc-9759-461c-9ad7-56376771a8fb")> _ <ComImport()> _ <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _ <CoClass(GetType(HasAllSupportedAttributesCoClass))> _ <BestFitMapping(True, ThrowOnUnmappableChar:=True)> _ <TypeLibImportClass(GetType(HasAllSupportedAttributesCoClass))> _ <CLSCompliant(True)> _ <TypeLibType(TypeLibTypeFlags.FDual)> _ Public Interface IHasAllSupportedAttributes Inherits IHasAllSupportedAttributes_Event ' return values have all supported attributes as well WriteOnly Property WOProp() As <MarshalAs(UnmanagedType.LPStr, SizeConst:=5)> String ReadOnly Property ROProp() As <MarshalAs(UnmanagedType.LPArray, arraysubtype:=UnmanagedType.Currency, SizeConst:=2)> Decimal() <TypeLibFunc(TypeLibFuncFlags.FBindable)> <LCIDConversion(10)> Function PropAndRetHasAllSupportedAttributes(<MarshalAs(UnmanagedType.LPArray, arraysubtype:=UnmanagedType.Error)> <[Optional]()> <Out()> <[In]()> <DefaultParameterValue(10)> <[ParamArray]()> ByVal x As Integer()) As String <SpecialName()> _ <PreserveSig()> _ Function Scenario11(ByRef str As String) As <MarshalAs(UnmanagedType.Bool)> Integer <SomeOtherAttribute()> _ Function Scenario12(<CLSCompliant(False), ComAliasName("aoeu")> ByVal p1 As Integer, <CLSCompliant(True), MarshalAs(UnmanagedType.IUnknown)> ByVal p2 As Object, <SomeOtherAttribute()> ByVal p3 As String) As <CLSCompliant(False)> Char() Function Scenario13(<CLSCompliant(False), ComAliasName("aoeu")> ByVal p1 As Integer, <CLSCompliant(True)> ByVal p2 As Object, <SomeOtherAttribute()> ByVal p3 As String) As <CLSCompliant(False), MarshalAs(UnmanagedType.Error)> Integer End Interface <UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet:=CharSet.Auto), CLSCompliant(True), SomeOtherAttribute()> Public Delegate Sub Goo() <Guid("7b072a0e-065c-4266-89f4-bdb0de8df3b5")> _ <ComImport()> _ Public Interface IHasAllSupportedAttributesEvent Sub Scenario14() End Interface <ComEventInterface(GetType(IHasAllSupportedAttributesEvent), GetType(Integer)), CLSCompliant(True)> _ Public Interface IHasAllSupportedAttributes_Event Event Scenario14 As Goo End Interface <Guid("ef307d1d-343d-44ef-a2f0-8235e214295e")> _ Public Class HasAllSupportedAttributesCoClass End Class <Guid("7b072a0e-065c-4266-89f4-bdb0de8df2b5")> _ <ComImport()> _ <AutomationProxy(True)> _ <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _ <SomeOtherAttribute()> _ Public Interface IHasUnsupportedAttributes Function FuncHasUnsupportedAttributes() As <CLSCompliant(True)> Integer Sub Bar() End Interface ' from the below attributes, COMVisible and TypeLibType attributes are not preserved <ComVisible(True)> _ <Guid("6f4eb02b-3469-424c-bbcc-2672f653e646")> _ <BestFitMapping(False)> _ <StructLayout(LayoutKind.Auto)> _ <TypeLibType(TypeLibTypeFlags.FRestricted)> _ <Flags()> _ Public Enum EnumHasAllSupportedAttributes ID1 ID2 End Enum <CLSCompliant(True)> _ <TypeLibType(TypeLibTypeFlags.FRestricted)> _ <Guid("25f37bfe-5a80-42b8-9e35-af88676d7178")> _ <SomeOtherAttribute()> _ Public Enum EnumHasOnlyUnsupportedAttributes ID1 ID2 End Enum <ComVisible(True)> _ <Guid("6f4eb02b-3469-424c-bbcc-2672f653e646")> _ <BestFitMapping(False)> _ <StructLayout(LayoutKind.Explicit, CharSet:=CharSet.Ansi, Pack:=4, Size:=2)> _ <TypeLibType(TypeLibTypeFlags.FRestricted)> _ <SomeOtherAttribute()> _ Public Structure StructHasAllSupportedAttributes <FieldOffset(24)> _ <MarshalAs(UnmanagedType.I4)> _ <SomeOtherAttribute()> _ Public a As Integer <MarshalAs(UnmanagedType.ByValArray, SizeConst:=12)> _ <DispId(2)> _ <TypeLibVar(TypeLibVarFlags.FHidden)> _ <CLSCompliant(False)> _ <FieldOffset(0)> _ Public FieldHasAllSupportedAttributes As Char() End Structure <CLSCompliant(True)> _ <TypeLibType(TypeLibTypeFlags.FControl)> _ <Guid("53de85e6-70eb-4b35-aff6-f34c0313637d")> _ Public Structure StructHasOnlyUnsupportedAttributes ' leave the struct empty - see how it is handled by NoPIA End Structure ' Pseudo-custom attributes that weren't called out in the spec <Serializable()> _ Public Structure OtherPseudoCustomAttributes '<NonSerialized()> _Verified we don't copy this guy (per spec)--not interesting to test, as it complicates verification logic Public Field1 As Date ' Scenarios no longer applicable, as compiler now generates error ' if structs contain anything except public instance fields ' Scenario is covered by Testcase #1422748 ' '<DllImport("blah", CharSet:=CharSet.Unicode)> _ 'Public Shared Sub Method1() 'End Sub '<MethodImpl(MethodImplOptions.NoInlining Or MethodImplOptions.NoOptimization)> _ 'Public Sub Method2() ' Field1 = #1/1/1979# 'End Sub End Structure End Namespace Namespace [Overloads] <ComImport()> _ <Guid("f618f410-0331-487d-ade1-bd46289d9fe1")> _ Public Interface IBase Sub Goo() Function Bar() As Integer End Interface <ComImport()> _ <Guid("984c80ba-2aec-4abf-afdd-c2bce69daa83")> _ Public Interface IDerived Inherits IBase Shadows Sub Goo() Shadows Function Bar() As Integer Shadows Function Goo(ByVal x As Integer) As <MarshalAs(UnmanagedType.LPStr, SizeConst:=10)> String End Interface <ComImport()> _ <Guid("a314887a-b963-4c6c-98a0-ff42d942cc9b")> _ Public Interface IInSameClass Overloads Function Over(ByVal x As Integer, <MarshalAs(UnmanagedType.IUnknown)> ByVal y As Object) As Integer Overloads Function Over(ByVal x As Integer) As Boolean End Interface End Namespace Namespace VTableGap <Guid("4cfdb6c3-ff27-4fc2-b477-07b914286230")> _ <ComImport()> _ Public Interface IScen1 Sub g1() ReadOnly Property g2() As <MarshalAs(UnmanagedType.Bool)> Integer End Interface <Guid("6c5d196f-916c-433a-b62b-0bfc2f97675d")> _ <ComImport()> _ Public Interface IScen2 Sub g000() ' use this one Sub g001() Sub g002() Sub g003() Sub g004() Sub g005() Sub g006() Sub g007() Sub g008() Sub g009() Sub g010() Sub g011() Sub g012() Sub g013() Sub g014() Sub g015() Sub g016() Sub g017() Sub g018() Sub g019() Sub g020() Sub g021() Sub g022() Sub g023() Sub g024() Sub g025() Sub g026() Sub g027() Sub g028() Sub g029() Sub g030() Sub g031() Sub g032() Sub g033() Sub g034() Sub g035() Sub g036() Sub g037() Sub g038() Sub g039() Sub g040() Sub g041() Sub g042() Sub g043() Sub g044() Sub g045() Sub g046() Sub g047() Sub g048() Sub g049() Sub g050() Sub g051() Sub g052() Sub g053() Sub g054() Sub g055() Sub g056() Sub g057() Sub g058() Sub g059() Sub g060() Sub g061() Sub g062() Sub g063() Sub g064() Sub g065() Sub g066() Sub g067() Sub g068() Sub g069() Sub g070() Sub g071() Sub g072() Sub g073() Sub g074() Sub g075() Sub g076() Sub g077() Sub g078() Sub g079() Sub g080() Sub g081() Sub g082() Sub g083() Sub g084() Sub g085() Sub g086() Sub g087() Sub g088() Sub g089() Sub g090() Sub g091() Sub g092() Sub g093() Sub g094() Sub g095() Sub g096() Sub g097() Sub g098() Sub g099() Sub g100() Sub g101() ' use this one End Interface <Guid("d0f4f3fc-6599-4c8f-b97b-8d0ba9a4a3c8")> _ <ComImport()> _ Public Interface IScen3 Function M(<MarshalAs(UnmanagedType.LPArray)> <[In]()> ByVal y As Double()) As <MarshalAs(UnmanagedType.IUnknown)> Object Function g1(ByVal y As Integer) As <MarshalAs(UnmanagedType.LPStr, SizeConst:=10)> String Function g2(<Out()> ByRef y As String) As Integer End Interface <Guid("8feb04fb-8bb6-4121-b883-78b261936ae7")> _ <ComImport()> _ Public Interface IScen4 Property P1() As String Sub g1() Sub g2(<[In]()> <Out()> ByVal x As String) Sub g3(<Out()> ByVal y As Integer) Property P2() As <MarshalAs(UnmanagedType.FunctionPtr)> Func(Of Integer) End Interface <Guid("858df621-87bb-40a0-99b5-617f85d04c88")> _ <ComImport()> _ Public Interface IScen5 Function M1(<MarshalAs(UnmanagedType.LPArray)> <[In]()> ByVal y As Double()) As <MarshalAs(UnmanagedType.IUnknown)> Object Property g1() As Decimal Property g2() As Integer Function M2(<MarshalAs(UnmanagedType.LPArray)> <[In]()> ParamArray ByVal y As Integer()) As String End Interface <Guid("11e95f23-fc7a-4a45-a3b4-b968f0e2cb2c")> _ <ComImport()> _ Public Interface IScen6 Property P1() As String ReadOnly Property g1() As String WriteOnly Property g2() As Integer ReadOnly Property g3() As Decimal WriteOnly Property g4() As Boolean Property P2() As <MarshalAs(UnmanagedType.FunctionPtr)> Func(Of Integer) End Interface <Guid("2f7b5524-4f8d-4471-95e9-ce319babf8d0")> _ <ComImport()> _ Public Interface IScen7 Property g1() As String Sub M(ByVal a As IScen1, ByVal b As IScen2, ByVal c As IScen3) Function g2() As Object Function g3(ByVal x As IScen6) As Integer End Interface <Guid("e08004c7-a558-4b02-b5f4-146c4b94aaa2")> _ <ComImport()> _ <CoClass(GetType(IComplicatedVTableImpl))> _ Public Interface IComplicatedVTable Default Property Goo(<MarshalAs(UnmanagedType.Bool)> ByVal index As Integer) As <MarshalAs(UnmanagedType.LPStr)> String Sub M1(<Out()> ByRef x As Integer) Function M2() As IScen1 Property P1() As IScen2 WriteOnly Property P3() As IComplicatedVTable Sub M3() ReadOnly Property P4() As ISubFuncProp Function M4() As <MarshalAs(UnmanagedType.IUnknown)> Object End Interface <Guid("c9dcf748-b634-4504-a7ce-348cf7c61891")> _ Public Class IComplicatedVTableImpl End Class End Namespace Namespace InheritsFromEnum <ComImport()> _ <Guid("ed9e4072-9bf4-4f6c-994d-8e415bcc6fd2")> _ <CoClass(GetType(CoClassIfe))> _ Public Interface IIfe Inherits IEnumerable Function Concat(ByVal x As Object) As IIfe End Interface <ComImport()> _ <Guid("97792ef5-1377-46c1-9815-59c5828d034f")> _ <CoClass(GetType(CoClassIfeScen2))> _ Public Interface IIfeScen2 Inherits IEnumerable(Of IIfeScen2) Function Concat(ByVal x As Object) As IIfeScen2 End Interface <Guid("f7cdfd32-d2e6-4f3f-92f0-bd2c9dcfa923")> _ Public Class CoClassIfe End Class <Guid("8a8c22bf-d666-4462-bc8d-2faf1940e041")> _ Public Class CoClassIfeScen2 : End Class End Namespace Namespace LackingAttributes Public Interface INoAttributesOrMembers End Interface <ComImport()> _ Public Interface IComImportButNoGuidOrMembers End Interface Public Interface INoAttributes Sub Goo(ByVal p As Integer) Function Bar() As String Property Prop() As <MarshalAs(UnmanagedType.Currency)> Decimal End Interface <ComImport()> _ Public Interface IComImportButNoGuid Sub Goo(ByVal p As Integer) Function Bar() As String Property Prop() As <MarshalAs(UnmanagedType.Currency)> Decimal 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.ComponentModel Imports System.ComponentModel.Composition Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("GeneralPIA.dll")> <Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")> Namespace SomeNamespace Public Structure NoAttributesStructure Public Goo1 As Integer Public Goo2 As Integer End Structure End Namespace Public Enum NoAttributesEnum Goo1 Goo2 End Enum Public Delegate Sub NoAttributesDelegate(ByVal x As String, ByVal y As Object) <Guid("ee3c2bee-9dfb-4d1c-91de-4cd32ff13302")> _ Public Enum GooEnum Goo1 __ Goo2 列挙識別子 [Enum] COM End Enum <Guid("63370d76-3395-4560-92fd-b69ccfdaf461")> _ Public Structure GooStruct Public [Structure] As Integer Public NET As Decimal Public 構造メンバー As String Public Goo3 As Object() Public Goo4 As Double() End Structure 'Public Structure GooPrivateStruct ' Public Goo1 As Integer ' Private Goo2 As Long 'End Structure 'Public Structure GooSharedStruct ' Public Shared Field1 As Integer = 4 'End Structure Public Structure GooConstStruct Public Const Field1 As String = "2" End Structure <Guid("bd62ff24-a97c-4a9c-a43e-09a31ff8b312")> _ <ComImport()> _ <InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)> _ Public Interface ISubFuncProp Sub Goo(ByVal p As Integer) Function Bar() As String Property Prop() As <MarshalAs(UnmanagedType.Currency)> Decimal End Interface <Guid("6a97be13-2611-4fc0-9d78-926dccec3243")> _ <ComImport()> _ <InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)> _ Public Interface IDuplicates Function DuplicateA(ByVal x As String) As Object Function DuplicateB(ByVal y As String) As Object Property PropDupeA() As ISubFuncProp Property PropDupeB() As ISubFuncProp End Interface Namespace Parameters <Guid("ed4bf792-06dd-449a-91d7-dde226e9f471")> _ <ComImport()> _ Public Interface IA End Interface <Guid("3b3fce76-b864-4a7c-93f6-87ec17339299")> _ <ComImport()> _ Public Interface IB End Interface <Guid("a6fa1a95-b29f-4f59-b457-29f8a55b3b6e")> _ <ComImport()> _ Public Interface IC End Interface <Guid("906b08a3-e478-4c52-ae30-ecb484ac01f0")> _ <ComImport()> _ Public Interface ID End Interface <Guid("bedd42c1-d023-4f53-8bfd-7c0b9de3aac7")> _ <ComImport()> _ Public Interface IByRef Function Goo(ByRef p1 As IA, ByRef p2 As IB, ByRef p3 As IC, ByRef p4 As Integer, ByRef p5 As Object) As ID Sub Bar(Optional ByRef p1 As IA = Nothing, Optional ByRef p2 As String() = Nothing, Optional ByRef p3 As Double() = Nothing) End Interface <Guid("1313c178-13f6-4450-8360-cf50d751a0f4")> _ <ComImport()> _ Public Interface IOptionalParam Function Goo(Optional ByVal p1 As IA = Nothing, Optional ByVal p2 As IB = Nothing, Optional ByVal p3 As IC = Nothing, Optional ByVal p4 As Integer = 5, Optional ByVal p5 As Object = Nothing) As ID Sub Bar(ByVal p1 As IA, ByVal p2 As String(), ByVal p3 As Double()) End Interface End Namespace Namespace GeneralEventScenario <Guid("00000502-0000-6600-c000-000000000046")> _ <ComImport()> _ Public Interface IEventArgs2 : Inherits IEnumerable Property GetData() As Parameters.IA End Interface Public Delegate Sub EventHandler(ByVal o As Object, ByVal e As EventArgs) Public Delegate Sub EventHandler2(ByVal o As Object, ByVal e As IEventArgs2) ' Calling interface <Guid("00000002-0000-0000-c000-000000000046")> _ <ComImport()> _ <InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> _ Public Interface _Arc <PreserveSig()> _ Function SomeUnusedMethod() As Object <DispId(1558)> _ <LCIDConversion(10)> _ <PreserveSig()> _ Function Cut(<MarshalAs(UnmanagedType.Bool), [In](), Out()> _ ByVal x As Integer) As <MarshalAs(UnmanagedType.Bool)> Object <PreserveSig()> _ Function SomeOtherUnusedMethod() As Object <PreserveSig()> _ Function SomeLastMethod() As Object End Interface ' Class interface <Guid("00000002-0000-0000-c000-000000000046")> _ <ComImport()> _ Public Interface Arc Inherits _Arc Inherits ArcEvent_Event Inherits ArcEvent_Event2 End Interface ' Source interface <Guid("00000002-0000-0000-c000-000000000047")> _ <ComImport()> _ <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _ Public Interface ArcEvent Function One() As Object <DispId(1558)> _ Sub click() Sub move() Sub groove() Sub shake() Sub rattle() End Interface ' Events interface <ComEventInterface(GetType(ArcEvent), GetType(Integer))> _ Public Interface ArcEvent_Event Event click As EventHandler End Interface ' A few more events <ComEventInterface(GetType(ArcEvent), GetType(Integer))> _ Public Interface ArcEvent_Event2 Event move As EventHandler2 Event groove As EventHandler Event shake As EventHandler Event rattle As EventHandler End Interface End Namespace Namespace Inheritance <Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c6c")> _ <ComImport()> _ <InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)> _ Public Interface IBase Sub IBaseSub(ByVal x As Integer) Function IBaseFunc() As Object Property IBaseProp() As String End Interface <Guid("bd60d4b3-f50b-478b-8ef2-e777df99d810")> _ <ComImport()> _ <InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)> _ <CoClass(GetType(DerivedImpl))> _ Public Interface IDerived Inherits IBase Shadows Sub IBaseSub(ByVal x As Integer) Shadows Function IBaseFunc() As Object Shadows Property IBaseProp() As String Sub IDerivedSub(ByVal x As Integer) Function IDerivedFunc() As Object Property IDerivedProp() As String End Interface <Guid("c9dcf748-b634-4504-a7ce-348cf7c61891")> _ Public Class DerivedImpl End Class End Namespace Namespace InheritanceConflict <Guid("76a62998-7740-4ebd-a09f-e401ffff5c8c")> _ <ComImport()> _ Public Interface IBase Sub Goo() Function Bar() As Integer Sub ConflictMethod(ByVal x As Integer) Default Property IndexedProperty(x As Object) As String End Interface <Guid("d6c92e52-47f4-4075-8078-99a21c29c8fa")> _ <ComImport()> _ <CoClass(GetType(DerivedImpl))> _ Public Interface IDerived Inherits IBase ' IBase methods Shadows Sub Goo() Shadows Function Bar() As Integer Shadows Sub ConflictMethod(ByVal x As Integer) Shadows Property IndexedProperty(x As Object) As String ' New methods Shadows Function ConflictMethod(x As Integer, y As String) As Object Shadows Default Property IndexedPropertyDerived(x As Decimal) As Integer End Interface <Guid("7e12bd3c-1ad1-427f-bab8-af82e30d980d")> _ Public Class DerivedImpl End Class End Namespace Namespace LateBound <Guid("43f3a25e-fccb-4b92-adc1-2fe84c922125")> _ <ComImport()> _ Public Interface INoPIAInterface Function Goo(ByVal x As INoPIAInterface) As String Function Bar(ByVal x As Integer, ByVal y As Integer) As String Function Moo() As Integer End Interface <Guid("ae390f6a-e7e4-47d7-a7b2-d95dfe14aac6")> _ <ComImport()> _ Public Interface INoPIAInterface2 Property Blah() As INoPIAInterface Sub Fazz(ByVal x As INoPIAInterface) End Interface End Namespace Namespace NoPIACopyAttributes Class SomeOtherAttribute Inherits Attribute End Class ' from the below attributes, AutomationProxy and CLSCompliant are not preserved <AutomationProxy(True)> _ <Guid("16063cdc-9759-461c-9ad7-56376771a8fb")> _ <ComImport()> _ <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _ <CoClass(GetType(HasAllSupportedAttributesCoClass))> _ <BestFitMapping(True, ThrowOnUnmappableChar:=True)> _ <TypeLibImportClass(GetType(HasAllSupportedAttributesCoClass))> _ <CLSCompliant(True)> _ <TypeLibType(TypeLibTypeFlags.FDual)> _ Public Interface IHasAllSupportedAttributes Inherits IHasAllSupportedAttributes_Event ' return values have all supported attributes as well WriteOnly Property WOProp() As <MarshalAs(UnmanagedType.LPStr, SizeConst:=5)> String ReadOnly Property ROProp() As <MarshalAs(UnmanagedType.LPArray, arraysubtype:=UnmanagedType.Currency, SizeConst:=2)> Decimal() <TypeLibFunc(TypeLibFuncFlags.FBindable)> <LCIDConversion(10)> Function PropAndRetHasAllSupportedAttributes(<MarshalAs(UnmanagedType.LPArray, arraysubtype:=UnmanagedType.Error)> <[Optional]()> <Out()> <[In]()> <DefaultParameterValue(10)> <[ParamArray]()> ByVal x As Integer()) As String <SpecialName()> _ <PreserveSig()> _ Function Scenario11(ByRef str As String) As <MarshalAs(UnmanagedType.Bool)> Integer <SomeOtherAttribute()> _ Function Scenario12(<CLSCompliant(False), ComAliasName("aoeu")> ByVal p1 As Integer, <CLSCompliant(True), MarshalAs(UnmanagedType.IUnknown)> ByVal p2 As Object, <SomeOtherAttribute()> ByVal p3 As String) As <CLSCompliant(False)> Char() Function Scenario13(<CLSCompliant(False), ComAliasName("aoeu")> ByVal p1 As Integer, <CLSCompliant(True)> ByVal p2 As Object, <SomeOtherAttribute()> ByVal p3 As String) As <CLSCompliant(False), MarshalAs(UnmanagedType.Error)> Integer End Interface <UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet:=CharSet.Auto), CLSCompliant(True), SomeOtherAttribute()> Public Delegate Sub Goo() <Guid("7b072a0e-065c-4266-89f4-bdb0de8df3b5")> _ <ComImport()> _ Public Interface IHasAllSupportedAttributesEvent Sub Scenario14() End Interface <ComEventInterface(GetType(IHasAllSupportedAttributesEvent), GetType(Integer)), CLSCompliant(True)> _ Public Interface IHasAllSupportedAttributes_Event Event Scenario14 As Goo End Interface <Guid("ef307d1d-343d-44ef-a2f0-8235e214295e")> _ Public Class HasAllSupportedAttributesCoClass End Class <Guid("7b072a0e-065c-4266-89f4-bdb0de8df2b5")> _ <ComImport()> _ <AutomationProxy(True)> _ <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _ <SomeOtherAttribute()> _ Public Interface IHasUnsupportedAttributes Function FuncHasUnsupportedAttributes() As <CLSCompliant(True)> Integer Sub Bar() End Interface ' from the below attributes, COMVisible and TypeLibType attributes are not preserved <ComVisible(True)> _ <Guid("6f4eb02b-3469-424c-bbcc-2672f653e646")> _ <BestFitMapping(False)> _ <StructLayout(LayoutKind.Auto)> _ <TypeLibType(TypeLibTypeFlags.FRestricted)> _ <Flags()> _ Public Enum EnumHasAllSupportedAttributes ID1 ID2 End Enum <CLSCompliant(True)> _ <TypeLibType(TypeLibTypeFlags.FRestricted)> _ <Guid("25f37bfe-5a80-42b8-9e35-af88676d7178")> _ <SomeOtherAttribute()> _ Public Enum EnumHasOnlyUnsupportedAttributes ID1 ID2 End Enum <ComVisible(True)> _ <Guid("6f4eb02b-3469-424c-bbcc-2672f653e646")> _ <BestFitMapping(False)> _ <StructLayout(LayoutKind.Explicit, CharSet:=CharSet.Ansi, Pack:=4, Size:=2)> _ <TypeLibType(TypeLibTypeFlags.FRestricted)> _ <SomeOtherAttribute()> _ Public Structure StructHasAllSupportedAttributes <FieldOffset(24)> _ <MarshalAs(UnmanagedType.I4)> _ <SomeOtherAttribute()> _ Public a As Integer <MarshalAs(UnmanagedType.ByValArray, SizeConst:=12)> _ <DispId(2)> _ <TypeLibVar(TypeLibVarFlags.FHidden)> _ <CLSCompliant(False)> _ <FieldOffset(0)> _ Public FieldHasAllSupportedAttributes As Char() End Structure <CLSCompliant(True)> _ <TypeLibType(TypeLibTypeFlags.FControl)> _ <Guid("53de85e6-70eb-4b35-aff6-f34c0313637d")> _ Public Structure StructHasOnlyUnsupportedAttributes ' leave the struct empty - see how it is handled by NoPIA End Structure ' Pseudo-custom attributes that weren't called out in the spec <Serializable()> _ Public Structure OtherPseudoCustomAttributes '<NonSerialized()> _Verified we don't copy this guy (per spec)--not interesting to test, as it complicates verification logic Public Field1 As Date ' Scenarios no longer applicable, as compiler now generates error ' if structs contain anything except public instance fields ' Scenario is covered by Testcase #1422748 ' '<DllImport("blah", CharSet:=CharSet.Unicode)> _ 'Public Shared Sub Method1() 'End Sub '<MethodImpl(MethodImplOptions.NoInlining Or MethodImplOptions.NoOptimization)> _ 'Public Sub Method2() ' Field1 = #1/1/1979# 'End Sub End Structure End Namespace Namespace [Overloads] <ComImport()> _ <Guid("f618f410-0331-487d-ade1-bd46289d9fe1")> _ Public Interface IBase Sub Goo() Function Bar() As Integer End Interface <ComImport()> _ <Guid("984c80ba-2aec-4abf-afdd-c2bce69daa83")> _ Public Interface IDerived Inherits IBase Shadows Sub Goo() Shadows Function Bar() As Integer Shadows Function Goo(ByVal x As Integer) As <MarshalAs(UnmanagedType.LPStr, SizeConst:=10)> String End Interface <ComImport()> _ <Guid("a314887a-b963-4c6c-98a0-ff42d942cc9b")> _ Public Interface IInSameClass Overloads Function Over(ByVal x As Integer, <MarshalAs(UnmanagedType.IUnknown)> ByVal y As Object) As Integer Overloads Function Over(ByVal x As Integer) As Boolean End Interface End Namespace Namespace VTableGap <Guid("4cfdb6c3-ff27-4fc2-b477-07b914286230")> _ <ComImport()> _ Public Interface IScen1 Sub g1() ReadOnly Property g2() As <MarshalAs(UnmanagedType.Bool)> Integer End Interface <Guid("6c5d196f-916c-433a-b62b-0bfc2f97675d")> _ <ComImport()> _ Public Interface IScen2 Sub g000() ' use this one Sub g001() Sub g002() Sub g003() Sub g004() Sub g005() Sub g006() Sub g007() Sub g008() Sub g009() Sub g010() Sub g011() Sub g012() Sub g013() Sub g014() Sub g015() Sub g016() Sub g017() Sub g018() Sub g019() Sub g020() Sub g021() Sub g022() Sub g023() Sub g024() Sub g025() Sub g026() Sub g027() Sub g028() Sub g029() Sub g030() Sub g031() Sub g032() Sub g033() Sub g034() Sub g035() Sub g036() Sub g037() Sub g038() Sub g039() Sub g040() Sub g041() Sub g042() Sub g043() Sub g044() Sub g045() Sub g046() Sub g047() Sub g048() Sub g049() Sub g050() Sub g051() Sub g052() Sub g053() Sub g054() Sub g055() Sub g056() Sub g057() Sub g058() Sub g059() Sub g060() Sub g061() Sub g062() Sub g063() Sub g064() Sub g065() Sub g066() Sub g067() Sub g068() Sub g069() Sub g070() Sub g071() Sub g072() Sub g073() Sub g074() Sub g075() Sub g076() Sub g077() Sub g078() Sub g079() Sub g080() Sub g081() Sub g082() Sub g083() Sub g084() Sub g085() Sub g086() Sub g087() Sub g088() Sub g089() Sub g090() Sub g091() Sub g092() Sub g093() Sub g094() Sub g095() Sub g096() Sub g097() Sub g098() Sub g099() Sub g100() Sub g101() ' use this one End Interface <Guid("d0f4f3fc-6599-4c8f-b97b-8d0ba9a4a3c8")> _ <ComImport()> _ Public Interface IScen3 Function M(<MarshalAs(UnmanagedType.LPArray)> <[In]()> ByVal y As Double()) As <MarshalAs(UnmanagedType.IUnknown)> Object Function g1(ByVal y As Integer) As <MarshalAs(UnmanagedType.LPStr, SizeConst:=10)> String Function g2(<Out()> ByRef y As String) As Integer End Interface <Guid("8feb04fb-8bb6-4121-b883-78b261936ae7")> _ <ComImport()> _ Public Interface IScen4 Property P1() As String Sub g1() Sub g2(<[In]()> <Out()> ByVal x As String) Sub g3(<Out()> ByVal y As Integer) Property P2() As <MarshalAs(UnmanagedType.FunctionPtr)> Func(Of Integer) End Interface <Guid("858df621-87bb-40a0-99b5-617f85d04c88")> _ <ComImport()> _ Public Interface IScen5 Function M1(<MarshalAs(UnmanagedType.LPArray)> <[In]()> ByVal y As Double()) As <MarshalAs(UnmanagedType.IUnknown)> Object Property g1() As Decimal Property g2() As Integer Function M2(<MarshalAs(UnmanagedType.LPArray)> <[In]()> ParamArray ByVal y As Integer()) As String End Interface <Guid("11e95f23-fc7a-4a45-a3b4-b968f0e2cb2c")> _ <ComImport()> _ Public Interface IScen6 Property P1() As String ReadOnly Property g1() As String WriteOnly Property g2() As Integer ReadOnly Property g3() As Decimal WriteOnly Property g4() As Boolean Property P2() As <MarshalAs(UnmanagedType.FunctionPtr)> Func(Of Integer) End Interface <Guid("2f7b5524-4f8d-4471-95e9-ce319babf8d0")> _ <ComImport()> _ Public Interface IScen7 Property g1() As String Sub M(ByVal a As IScen1, ByVal b As IScen2, ByVal c As IScen3) Function g2() As Object Function g3(ByVal x As IScen6) As Integer End Interface <Guid("e08004c7-a558-4b02-b5f4-146c4b94aaa2")> _ <ComImport()> _ <CoClass(GetType(IComplicatedVTableImpl))> _ Public Interface IComplicatedVTable Default Property Goo(<MarshalAs(UnmanagedType.Bool)> ByVal index As Integer) As <MarshalAs(UnmanagedType.LPStr)> String Sub M1(<Out()> ByRef x As Integer) Function M2() As IScen1 Property P1() As IScen2 WriteOnly Property P3() As IComplicatedVTable Sub M3() ReadOnly Property P4() As ISubFuncProp Function M4() As <MarshalAs(UnmanagedType.IUnknown)> Object End Interface <Guid("c9dcf748-b634-4504-a7ce-348cf7c61891")> _ Public Class IComplicatedVTableImpl End Class End Namespace Namespace InheritsFromEnum <ComImport()> _ <Guid("ed9e4072-9bf4-4f6c-994d-8e415bcc6fd2")> _ <CoClass(GetType(CoClassIfe))> _ Public Interface IIfe Inherits IEnumerable Function Concat(ByVal x As Object) As IIfe End Interface <ComImport()> _ <Guid("97792ef5-1377-46c1-9815-59c5828d034f")> _ <CoClass(GetType(CoClassIfeScen2))> _ Public Interface IIfeScen2 Inherits IEnumerable(Of IIfeScen2) Function Concat(ByVal x As Object) As IIfeScen2 End Interface <Guid("f7cdfd32-d2e6-4f3f-92f0-bd2c9dcfa923")> _ Public Class CoClassIfe End Class <Guid("8a8c22bf-d666-4462-bc8d-2faf1940e041")> _ Public Class CoClassIfeScen2 : End Class End Namespace Namespace LackingAttributes Public Interface INoAttributesOrMembers End Interface <ComImport()> _ Public Interface IComImportButNoGuidOrMembers End Interface Public Interface INoAttributes Sub Goo(ByVal p As Integer) Function Bar() As String Property Prop() As <MarshalAs(UnmanagedType.Currency)> Decimal End Interface <ComImport()> _ Public Interface IComImportButNoGuid Sub Goo(ByVal p As Integer) Function Bar() As String Property Prop() As <MarshalAs(UnmanagedType.Currency)> Decimal End Interface End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerService_IncrementalAnalyzer.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 Microsoft.CodeAnalysis.Diagnostics.EngineV2; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { [ExportIncrementalAnalyzerProvider( highPriorityForActiveFile: true, name: WellKnownSolutionCrawlerAnalyzers.Diagnostic, workspaceKinds: new string[] { WorkspaceKind.Host, WorkspaceKind.Interactive })] internal partial class DiagnosticAnalyzerService : IIncrementalAnalyzerProvider { public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { if (!workspace.Options.GetOption(ServiceComponentOnOffOptions.DiagnosticProvider)) { return null; } return _map.GetValue(workspace, _createIncrementalAnalyzer); } public void ShutdownAnalyzerFrom(Workspace workspace) { // this should be only called once analyzer associated with the workspace is done. if (_map.TryGetValue(workspace, out var analyzer)) { analyzer.Shutdown(); } } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] private DiagnosticIncrementalAnalyzer CreateIncrementalAnalyzerCallback(Workspace workspace) { // subscribe to active context changed event for new workspace workspace.DocumentActiveContextChanged += OnDocumentActiveContextChanged; return new DiagnosticIncrementalAnalyzer(this, LogAggregator.GetNextId(), workspace, AnalyzerInfoCache); } private void OnDocumentActiveContextChanged(object sender, DocumentActiveContextChangedEventArgs e) => Reanalyze(e.Solution.Workspace, documentIds: SpecializedCollections.SingletonEnumerable(e.NewActiveContextDocumentId), highPriority: 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 Microsoft.CodeAnalysis.Diagnostics.EngineV2; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { [ExportIncrementalAnalyzerProvider( highPriorityForActiveFile: true, name: WellKnownSolutionCrawlerAnalyzers.Diagnostic, workspaceKinds: new string[] { WorkspaceKind.Host, WorkspaceKind.Interactive })] internal partial class DiagnosticAnalyzerService : IIncrementalAnalyzerProvider { public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { if (!workspace.Options.GetOption(ServiceComponentOnOffOptions.DiagnosticProvider)) { return null; } return _map.GetValue(workspace, _createIncrementalAnalyzer); } public void ShutdownAnalyzerFrom(Workspace workspace) { // this should be only called once analyzer associated with the workspace is done. if (_map.TryGetValue(workspace, out var analyzer)) { analyzer.Shutdown(); } } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] private DiagnosticIncrementalAnalyzer CreateIncrementalAnalyzerCallback(Workspace workspace) { // subscribe to active context changed event for new workspace workspace.DocumentActiveContextChanged += OnDocumentActiveContextChanged; return new DiagnosticIncrementalAnalyzer(this, LogAggregator.GetNextId(), workspace, AnalyzerInfoCache); } private void OnDocumentActiveContextChanged(object sender, DocumentActiveContextChangedEventArgs e) => Reanalyze(e.Solution.Workspace, documentIds: SpecializedCollections.SingletonEnumerable(e.NewActiveContextDocumentId), highPriority: true); } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/EditorFeatures/TestUtilities/Async/AsynchronousOperationBlocker.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.Threading; using Microsoft.CodeAnalysis; namespace Roslyn.Test.Utilities { public sealed class AsynchronousOperationBlocker : IDisposable { private readonly ManualResetEvent _waitHandle; private readonly object _lockObj; private bool _blocking; private bool _disposed; public AsynchronousOperationBlocker() { _waitHandle = new ManualResetEvent(false); _lockObj = new object(); _blocking = true; } public bool IsBlockingOperations { get { lock (_lockObj) { return _blocking; } } private set { lock (_lockObj) { if (_blocking == value) { return; } _blocking = value; if (!_disposed) { if (_blocking) { _waitHandle.Reset(); } else { _waitHandle.Set(); } } } } } public void BlockOperations() => this.IsBlockingOperations = true; public void UnblockOperations() => this.IsBlockingOperations = false; public bool WaitIfBlocked(TimeSpan timeout) { if (_disposed) { FailFast.Fail("Badness"); } return _waitHandle.WaitOne(timeout); } public void Dispose() { if (!_disposed) { _disposed = true; _waitHandle.Dispose(); } } } }
// 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.Threading; using Microsoft.CodeAnalysis; namespace Roslyn.Test.Utilities { public sealed class AsynchronousOperationBlocker : IDisposable { private readonly ManualResetEvent _waitHandle; private readonly object _lockObj; private bool _blocking; private bool _disposed; public AsynchronousOperationBlocker() { _waitHandle = new ManualResetEvent(false); _lockObj = new object(); _blocking = true; } public bool IsBlockingOperations { get { lock (_lockObj) { return _blocking; } } private set { lock (_lockObj) { if (_blocking == value) { return; } _blocking = value; if (!_disposed) { if (_blocking) { _waitHandle.Reset(); } else { _waitHandle.Set(); } } } } } public void BlockOperations() => this.IsBlockingOperations = true; public void UnblockOperations() => this.IsBlockingOperations = false; public bool WaitIfBlocked(TimeSpan timeout) { if (_disposed) { FailFast.Fail("Badness"); } return _waitHandle.WaitOne(timeout); } public void Dispose() { if (!_disposed) { _disposed = true; _waitHandle.Dispose(); } } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CommitManager.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using AsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal sealed class CommitManager : ForegroundThreadAffinitizedObject, IAsyncCompletionCommitManager { private static readonly AsyncCompletionData.CommitResult CommitResultUnhandled = new(isHandled: false, AsyncCompletionData.CommitBehavior.None); private readonly RecentItemsManager _recentItemsManager; private readonly ITextView _textView; public IEnumerable<char> PotentialCommitCharacters { get { if (_textView.Properties.TryGetProperty(CompletionSource.PotentialCommitCharacters, out ImmutableArray<char> potentialCommitCharacters)) { return potentialCommitCharacters; } else { // If we were not initialized with a CompletionService or are called for a wrong textView, we should not make a commit. return ImmutableArray<char>.Empty; } } } internal CommitManager(ITextView textView, RecentItemsManager recentItemsManager, IThreadingContext threadingContext) : base(threadingContext) { _recentItemsManager = recentItemsManager; _textView = textView; } /// <summary> /// The method performs a preliminarily filtering of commit availability. /// In case of a doubt, it should respond with true. /// We will be able to cancel later in /// <see cref="TryCommit(IAsyncCompletionSession, ITextBuffer, VSCompletionItem, char, CancellationToken)"/> /// based on <see cref="VSCompletionItem"/> item, e.g. based on <see cref="CompletionItemRules"/>. /// </summary> public bool ShouldCommitCompletion( IAsyncCompletionSession session, SnapshotPoint location, char typedChar, CancellationToken cancellationToken) { if (!PotentialCommitCharacters.Contains(typedChar)) { return false; } return !(session.Properties.TryGetProperty(CompletionSource.ExcludedCommitCharacters, out ImmutableArray<char> excludedCommitCharacter) && excludedCommitCharacter.Contains(typedChar)); } public AsyncCompletionData.CommitResult TryCommit( IAsyncCompletionSession session, ITextBuffer subjectBuffer, VSCompletionItem item, char typeChar, CancellationToken cancellationToken) { // We can make changes to buffers. We would like to be sure nobody can change them at the same time. AssertIsForeground(); var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return CommitResultUnhandled; } var completionService = document.GetLanguageService<CompletionService>(); if (completionService == null) { return CommitResultUnhandled; } if (!item.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem)) { // Roslyn should not be called if the item committing was not provided by Roslyn. return CommitResultUnhandled; } var filterText = session.ApplicableToSpan.GetText(session.ApplicableToSpan.TextBuffer.CurrentSnapshot) + typeChar; if (Helpers.IsFilterCharacter(roslynItem, typeChar, filterText)) { // Returning Cancel means we keep the current session and consider the character for further filtering. return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.CancelCommit); } var serviceRules = completionService.GetRules(); // We can be called before for ShouldCommitCompletion. However, that call does not provide rules applied for the completion item. // Now we check for the commit charcter in the context of Rules that could change the list of commit characters. if (!Helpers.IsStandardCommitCharacter(typeChar) && !IsCommitCharacter(serviceRules, roslynItem, typeChar)) { // Returning None means we complete the current session with a void commit. // The Editor then will try to trigger a new completion session for the character. return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } if (!item.Properties.TryGetProperty(CompletionSource.TriggerLocation, out SnapshotPoint triggerLocation)) { // Need the trigger snapshot to calculate the span when the commit changes to be applied. // They should always be available from items provided by Roslyn CompletionSource. // Just to be defensive, if it's not found here, Roslyn should not make a commit. return CommitResultUnhandled; } if (!session.Properties.TryGetProperty(CompletionSource.CompletionListSpan, out TextSpan completionListSpan)) { return CommitResultUnhandled; } var triggerDocument = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (triggerDocument == null) { return CommitResultUnhandled; } // Telemetry if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTyperImportCompletionEnabled) && isTyperImportCompletionEnabled) { AsyncCompletionLogger.LogCommitWithTypeImportCompletionEnabled(); } if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled) { // Capture the % of committed completion items that would have appeared in the "Target type matches" filter // (regardless of whether that filter button was active at the time of commit). AsyncCompletionLogger.LogCommitWithTargetTypeCompletionExperimentEnabled(); if (item.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) { AsyncCompletionLogger.LogCommitItemWithTargetTypeFilter(); } } // Commit with completion service assumes that null is provided is case of invoke. VS provides '\0' in the case. var commitChar = typeChar == '\0' ? null : (char?)typeChar; return Commit( session, triggerDocument, completionService, subjectBuffer, roslynItem, completionListSpan, commitChar, triggerLocation.Snapshot, serviceRules, filterText, cancellationToken); } private AsyncCompletionData.CommitResult Commit( IAsyncCompletionSession session, Document document, CompletionService completionService, ITextBuffer subjectBuffer, RoslynCompletionItem roslynItem, TextSpan completionListSpan, char? commitCharacter, ITextSnapshot triggerSnapshot, CompletionRules rules, string filterText, CancellationToken cancellationToken) { AssertIsForeground(); bool includesCommitCharacter; if (!subjectBuffer.CheckEditAccess()) { // We are on the wrong thread. FatalError.ReportAndCatch(new InvalidOperationException("Subject buffer did not provide Edit Access")); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } if (subjectBuffer.EditInProgress) { FatalError.ReportAndCatch(new InvalidOperationException("Subject buffer is editing by someone else.")); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } CompletionChange change; // We met an issue when external code threw an OperationCanceledException and the cancellationToken is not cancelled. // Catching this scenario for further investigations. // See https://github.com/dotnet/roslyn/issues/38455. try { // Cached items have a span computed at the point they were created. This span may no // longer be valid when used again. In that case, override the span with the latest span // for the completion list itself. if (roslynItem.Flags.IsCached()) roslynItem.Span = completionListSpan; change = completionService.GetChangeAsync(document, roslynItem, commitCharacter, cancellationToken).WaitAndGetResult(cancellationToken); } catch (OperationCanceledException e) when (e.CancellationToken != cancellationToken && FatalError.ReportAndCatch(e)) { return CommitResultUnhandled; } cancellationToken.ThrowIfCancellationRequested(); var view = session.TextView; var provider = GetCompletionProvider(completionService, roslynItem); if (provider is ICustomCommitCompletionProvider customCommitProvider) { customCommitProvider.Commit(roslynItem, view, subjectBuffer, triggerSnapshot, commitCharacter); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } var textChange = change.TextChange; var triggerSnapshotSpan = new SnapshotSpan(triggerSnapshot, textChange.Span.ToSpan()); var mappedSpan = triggerSnapshotSpan.TranslateTo(subjectBuffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); using (var edit = subjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null)) { edit.Replace(mappedSpan.Span, change.TextChange.NewText); // edit.Apply() may trigger changes made by extensions. // updatedCurrentSnapshot will contain changes made by Roslyn but not by other extensions. var updatedCurrentSnapshot = edit.Apply(); if (change.NewPosition.HasValue) { // Roslyn knows how to positionate the caret in the snapshot we just created. // If there were more edits made by extensions, TryMoveCaretToAndEnsureVisible maps the snapshot point to the most recent one. view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(updatedCurrentSnapshot, change.NewPosition.Value)); } else { // Or, If we're doing a minimal change, then the edit that we make to the // buffer may not make the total text change that places the caret where we // would expect it to go based on the requested change. In this case, // determine where the item should go and set the care manually. // Note: we only want to move the caret if the caret would have been moved // by the edit. i.e. if the caret was actually in the mapped span that // we're replacing. var caretPositionInBuffer = view.GetCaretPoint(subjectBuffer); if (caretPositionInBuffer.HasValue && mappedSpan.IntersectsWith(caretPositionInBuffer.Value)) { view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(subjectBuffer.CurrentSnapshot, mappedSpan.Start.Position + textChange.NewText?.Length ?? 0)); } else { view.Caret.EnsureVisible(); } } includesCommitCharacter = change.IncludesCommitCharacter; if (roslynItem.Rules.FormatOnCommit) { // The edit updates the snapshot however other extensions may make changes there. // Therefore, it is required to use subjectBuffer.CurrentSnapshot for further calculations rather than the updated current snapsot defined above. var currentDocument = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); var formattingService = currentDocument?.GetRequiredLanguageService<IFormattingInteractionService>(); if (currentDocument != null && formattingService != null) { var spanToFormat = triggerSnapshotSpan.TranslateTo(subjectBuffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); var changes = formattingService.GetFormattingChangesAsync( currentDocument, spanToFormat.Span.ToTextSpan(), documentOptions: null, CancellationToken.None).WaitAndGetResult(CancellationToken.None); currentDocument.Project.Solution.Workspace.ApplyTextChanges(currentDocument.Id, changes, CancellationToken.None); } } } _recentItemsManager.MakeMostRecentItem(roslynItem.FilterText); if (provider is INotifyCommittingItemCompletionProvider notifyProvider) { _ = ThreadingContext.JoinableTaskFactory.RunAsync(async () => { // Make sure the notification isn't sent on UI thread. await TaskScheduler.Default; _ = notifyProvider.NotifyCommittingItemAsync(document, roslynItem, commitCharacter, cancellationToken).ReportNonFatalErrorAsync(); }); } if (includesCommitCharacter) { return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.SuppressFurtherTypeCharCommandHandlers); } if (commitCharacter == '\n' && SendEnterThroughToEditor(rules, roslynItem, filterText)) { return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.RaiseFurtherReturnKeyAndTabKeyCommandHandlers); } return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } internal static bool IsCommitCharacter(CompletionRules completionRules, CompletionItem item, char ch) { // First see if the item has any specifc commit rules it wants followed. foreach (var rule in item.Rules.CommitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: if (rule.Characters.Contains(ch)) { return true; } continue; case CharacterSetModificationKind.Remove: if (rule.Characters.Contains(ch)) { return false; } continue; case CharacterSetModificationKind.Replace: return rule.Characters.Contains(ch); } } // Fall back to the default rules for this language's completion service. return completionRules.DefaultCommitCharacters.IndexOf(ch) >= 0; } internal static bool SendEnterThroughToEditor(CompletionRules rules, RoslynCompletionItem item, string textTypedSoFar) { var rule = item.Rules.EnterKeyRule; if (rule == EnterKeyRule.Default) { rule = rules.DefaultEnterKeyRule; } switch (rule) { default: case EnterKeyRule.Default: case EnterKeyRule.Never: return false; case EnterKeyRule.Always: return true; case EnterKeyRule.AfterFullyTypedWord: // textTypedSoFar is concatenated from individual chars typed. // '\n' is the enter char. // That is why, there is no need to check for '\r\n'. if (textTypedSoFar.LastOrDefault() == '\n') { textTypedSoFar = textTypedSoFar.Substring(0, textTypedSoFar.Length - 1); } return item.GetEntireDisplayText() == textTypedSoFar; } } private static CompletionProvider? GetCompletionProvider(CompletionService completionService, CompletionItem item) { if (completionService is CompletionServiceWithProviders completionServiceWithProviders) { return completionServiceWithProviders.GetProvider(item); } 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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using AsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal sealed class CommitManager : ForegroundThreadAffinitizedObject, IAsyncCompletionCommitManager { private static readonly AsyncCompletionData.CommitResult CommitResultUnhandled = new(isHandled: false, AsyncCompletionData.CommitBehavior.None); private readonly RecentItemsManager _recentItemsManager; private readonly ITextView _textView; public IEnumerable<char> PotentialCommitCharacters { get { if (_textView.Properties.TryGetProperty(CompletionSource.PotentialCommitCharacters, out ImmutableArray<char> potentialCommitCharacters)) { return potentialCommitCharacters; } else { // If we were not initialized with a CompletionService or are called for a wrong textView, we should not make a commit. return ImmutableArray<char>.Empty; } } } internal CommitManager(ITextView textView, RecentItemsManager recentItemsManager, IThreadingContext threadingContext) : base(threadingContext) { _recentItemsManager = recentItemsManager; _textView = textView; } /// <summary> /// The method performs a preliminarily filtering of commit availability. /// In case of a doubt, it should respond with true. /// We will be able to cancel later in /// <see cref="TryCommit(IAsyncCompletionSession, ITextBuffer, VSCompletionItem, char, CancellationToken)"/> /// based on <see cref="VSCompletionItem"/> item, e.g. based on <see cref="CompletionItemRules"/>. /// </summary> public bool ShouldCommitCompletion( IAsyncCompletionSession session, SnapshotPoint location, char typedChar, CancellationToken cancellationToken) { if (!PotentialCommitCharacters.Contains(typedChar)) { return false; } return !(session.Properties.TryGetProperty(CompletionSource.ExcludedCommitCharacters, out ImmutableArray<char> excludedCommitCharacter) && excludedCommitCharacter.Contains(typedChar)); } public AsyncCompletionData.CommitResult TryCommit( IAsyncCompletionSession session, ITextBuffer subjectBuffer, VSCompletionItem item, char typeChar, CancellationToken cancellationToken) { // We can make changes to buffers. We would like to be sure nobody can change them at the same time. AssertIsForeground(); var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return CommitResultUnhandled; } var completionService = document.GetLanguageService<CompletionService>(); if (completionService == null) { return CommitResultUnhandled; } if (!item.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem)) { // Roslyn should not be called if the item committing was not provided by Roslyn. return CommitResultUnhandled; } var filterText = session.ApplicableToSpan.GetText(session.ApplicableToSpan.TextBuffer.CurrentSnapshot) + typeChar; if (Helpers.IsFilterCharacter(roslynItem, typeChar, filterText)) { // Returning Cancel means we keep the current session and consider the character for further filtering. return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.CancelCommit); } var serviceRules = completionService.GetRules(); // We can be called before for ShouldCommitCompletion. However, that call does not provide rules applied for the completion item. // Now we check for the commit charcter in the context of Rules that could change the list of commit characters. if (!Helpers.IsStandardCommitCharacter(typeChar) && !IsCommitCharacter(serviceRules, roslynItem, typeChar)) { // Returning None means we complete the current session with a void commit. // The Editor then will try to trigger a new completion session for the character. return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } if (!item.Properties.TryGetProperty(CompletionSource.TriggerLocation, out SnapshotPoint triggerLocation)) { // Need the trigger snapshot to calculate the span when the commit changes to be applied. // They should always be available from items provided by Roslyn CompletionSource. // Just to be defensive, if it's not found here, Roslyn should not make a commit. return CommitResultUnhandled; } if (!session.Properties.TryGetProperty(CompletionSource.CompletionListSpan, out TextSpan completionListSpan)) { return CommitResultUnhandled; } var triggerDocument = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (triggerDocument == null) { return CommitResultUnhandled; } // Telemetry if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTyperImportCompletionEnabled) && isTyperImportCompletionEnabled) { AsyncCompletionLogger.LogCommitWithTypeImportCompletionEnabled(); } if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled) { // Capture the % of committed completion items that would have appeared in the "Target type matches" filter // (regardless of whether that filter button was active at the time of commit). AsyncCompletionLogger.LogCommitWithTargetTypeCompletionExperimentEnabled(); if (item.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) { AsyncCompletionLogger.LogCommitItemWithTargetTypeFilter(); } } // Commit with completion service assumes that null is provided is case of invoke. VS provides '\0' in the case. var commitChar = typeChar == '\0' ? null : (char?)typeChar; return Commit( session, triggerDocument, completionService, subjectBuffer, roslynItem, completionListSpan, commitChar, triggerLocation.Snapshot, serviceRules, filterText, cancellationToken); } private AsyncCompletionData.CommitResult Commit( IAsyncCompletionSession session, Document document, CompletionService completionService, ITextBuffer subjectBuffer, RoslynCompletionItem roslynItem, TextSpan completionListSpan, char? commitCharacter, ITextSnapshot triggerSnapshot, CompletionRules rules, string filterText, CancellationToken cancellationToken) { AssertIsForeground(); bool includesCommitCharacter; if (!subjectBuffer.CheckEditAccess()) { // We are on the wrong thread. FatalError.ReportAndCatch(new InvalidOperationException("Subject buffer did not provide Edit Access")); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } if (subjectBuffer.EditInProgress) { FatalError.ReportAndCatch(new InvalidOperationException("Subject buffer is editing by someone else.")); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } CompletionChange change; // We met an issue when external code threw an OperationCanceledException and the cancellationToken is not cancelled. // Catching this scenario for further investigations. // See https://github.com/dotnet/roslyn/issues/38455. try { // Cached items have a span computed at the point they were created. This span may no // longer be valid when used again. In that case, override the span with the latest span // for the completion list itself. if (roslynItem.Flags.IsCached()) roslynItem.Span = completionListSpan; change = completionService.GetChangeAsync(document, roslynItem, commitCharacter, cancellationToken).WaitAndGetResult(cancellationToken); } catch (OperationCanceledException e) when (e.CancellationToken != cancellationToken && FatalError.ReportAndCatch(e)) { return CommitResultUnhandled; } cancellationToken.ThrowIfCancellationRequested(); var view = session.TextView; var provider = GetCompletionProvider(completionService, roslynItem); if (provider is ICustomCommitCompletionProvider customCommitProvider) { customCommitProvider.Commit(roslynItem, view, subjectBuffer, triggerSnapshot, commitCharacter); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } var textChange = change.TextChange; var triggerSnapshotSpan = new SnapshotSpan(triggerSnapshot, textChange.Span.ToSpan()); var mappedSpan = triggerSnapshotSpan.TranslateTo(subjectBuffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); using (var edit = subjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null)) { edit.Replace(mappedSpan.Span, change.TextChange.NewText); // edit.Apply() may trigger changes made by extensions. // updatedCurrentSnapshot will contain changes made by Roslyn but not by other extensions. var updatedCurrentSnapshot = edit.Apply(); if (change.NewPosition.HasValue) { // Roslyn knows how to positionate the caret in the snapshot we just created. // If there were more edits made by extensions, TryMoveCaretToAndEnsureVisible maps the snapshot point to the most recent one. view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(updatedCurrentSnapshot, change.NewPosition.Value)); } else { // Or, If we're doing a minimal change, then the edit that we make to the // buffer may not make the total text change that places the caret where we // would expect it to go based on the requested change. In this case, // determine where the item should go and set the care manually. // Note: we only want to move the caret if the caret would have been moved // by the edit. i.e. if the caret was actually in the mapped span that // we're replacing. var caretPositionInBuffer = view.GetCaretPoint(subjectBuffer); if (caretPositionInBuffer.HasValue && mappedSpan.IntersectsWith(caretPositionInBuffer.Value)) { view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(subjectBuffer.CurrentSnapshot, mappedSpan.Start.Position + textChange.NewText?.Length ?? 0)); } else { view.Caret.EnsureVisible(); } } includesCommitCharacter = change.IncludesCommitCharacter; if (roslynItem.Rules.FormatOnCommit) { // The edit updates the snapshot however other extensions may make changes there. // Therefore, it is required to use subjectBuffer.CurrentSnapshot for further calculations rather than the updated current snapsot defined above. var currentDocument = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); var formattingService = currentDocument?.GetRequiredLanguageService<IFormattingInteractionService>(); if (currentDocument != null && formattingService != null) { var spanToFormat = triggerSnapshotSpan.TranslateTo(subjectBuffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); var changes = formattingService.GetFormattingChangesAsync( currentDocument, spanToFormat.Span.ToTextSpan(), documentOptions: null, CancellationToken.None).WaitAndGetResult(CancellationToken.None); currentDocument.Project.Solution.Workspace.ApplyTextChanges(currentDocument.Id, changes, CancellationToken.None); } } } _recentItemsManager.MakeMostRecentItem(roslynItem.FilterText); if (provider is INotifyCommittingItemCompletionProvider notifyProvider) { _ = ThreadingContext.JoinableTaskFactory.RunAsync(async () => { // Make sure the notification isn't sent on UI thread. await TaskScheduler.Default; _ = notifyProvider.NotifyCommittingItemAsync(document, roslynItem, commitCharacter, cancellationToken).ReportNonFatalErrorAsync(); }); } if (includesCommitCharacter) { return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.SuppressFurtherTypeCharCommandHandlers); } if (commitCharacter == '\n' && SendEnterThroughToEditor(rules, roslynItem, filterText)) { return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.RaiseFurtherReturnKeyAndTabKeyCommandHandlers); } return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } internal static bool IsCommitCharacter(CompletionRules completionRules, CompletionItem item, char ch) { // First see if the item has any specifc commit rules it wants followed. foreach (var rule in item.Rules.CommitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: if (rule.Characters.Contains(ch)) { return true; } continue; case CharacterSetModificationKind.Remove: if (rule.Characters.Contains(ch)) { return false; } continue; case CharacterSetModificationKind.Replace: return rule.Characters.Contains(ch); } } // Fall back to the default rules for this language's completion service. return completionRules.DefaultCommitCharacters.IndexOf(ch) >= 0; } internal static bool SendEnterThroughToEditor(CompletionRules rules, RoslynCompletionItem item, string textTypedSoFar) { var rule = item.Rules.EnterKeyRule; if (rule == EnterKeyRule.Default) { rule = rules.DefaultEnterKeyRule; } switch (rule) { default: case EnterKeyRule.Default: case EnterKeyRule.Never: return false; case EnterKeyRule.Always: return true; case EnterKeyRule.AfterFullyTypedWord: // textTypedSoFar is concatenated from individual chars typed. // '\n' is the enter char. // That is why, there is no need to check for '\r\n'. if (textTypedSoFar.LastOrDefault() == '\n') { textTypedSoFar = textTypedSoFar.Substring(0, textTypedSoFar.Length - 1); } return item.GetEntireDisplayText() == textTypedSoFar; } } private static CompletionProvider? GetCompletionProvider(CompletionService completionService, CompletionItem item) { if (completionService is CompletionServiceWithProviders completionServiceWithProviders) { return completionServiceWithProviders.GetProvider(item); } return null; } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/CSharpProjectExistsUIContextProviderLanguageService.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; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { [ExportLanguageService(typeof(IProjectExistsUIContextProviderLanguageService), LanguageNames.CSharp), Shared] internal sealed class CSharpProjectExistsUIContextProviderLanguageService : IProjectExistsUIContextProviderLanguageService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpProjectExistsUIContextProviderLanguageService() { } public UIContext GetUIContext() => UIContext.FromUIContextGuid(Guids.CSharpProjectExistsInWorkspaceUIContext); } }
// 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; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { [ExportLanguageService(typeof(IProjectExistsUIContextProviderLanguageService), LanguageNames.CSharp), Shared] internal sealed class CSharpProjectExistsUIContextProviderLanguageService : IProjectExistsUIContextProviderLanguageService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpProjectExistsUIContextProviderLanguageService() { } public UIContext GetUIContext() => UIContext.FromUIContextGuid(Guids.CSharpProjectExistsInWorkspaceUIContext); } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Analyzers/Core/Analyzers/UseInferredMemberName/AbstractUseInferredMemberNameDiagnosticAnalyzer.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 System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.UseInferredMemberName { internal abstract class AbstractUseInferredMemberNameDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { protected abstract void LanguageSpecificAnalyzeSyntax(SyntaxNodeAnalysisContext context, SyntaxTree syntaxTree, AnalyzerOptions options, CancellationToken cancellationToken); public AbstractUseInferredMemberNameDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseInferredMemberNameDiagnosticId, EnforceOnBuildValues.UseInferredMemberName, options: ImmutableHashSet.Create<IPerLanguageOption>(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, CodeStyleOptions2.PreferInferredTupleNames), new LocalizableResourceString(nameof(AnalyzersResources.Use_inferred_member_name), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Member_name_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var cancellationToken = context.CancellationToken; var syntaxTree = context.Node.SyntaxTree; var options = context.Options; LanguageSpecificAnalyzeSyntax(context, syntaxTree, options, 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.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.UseInferredMemberName { internal abstract class AbstractUseInferredMemberNameDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { protected abstract void LanguageSpecificAnalyzeSyntax(SyntaxNodeAnalysisContext context, SyntaxTree syntaxTree, AnalyzerOptions options, CancellationToken cancellationToken); public AbstractUseInferredMemberNameDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseInferredMemberNameDiagnosticId, EnforceOnBuildValues.UseInferredMemberName, options: ImmutableHashSet.Create<IPerLanguageOption>(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, CodeStyleOptions2.PreferInferredTupleNames), new LocalizableResourceString(nameof(AnalyzersResources.Use_inferred_member_name), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Member_name_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var cancellationToken = context.CancellationToken; var syntaxTree = context.Node.SyntaxTree; var options = context.Options; LanguageSpecificAnalyzeSyntax(context, syntaxTree, options, cancellationToken); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/Core/Portable/InlineHints/IInlineTypeHintsService.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.Text; namespace Microsoft.CodeAnalysis.InlineHints { /// <summary> /// Gets inline hints for type locations. This is an internal service only for C# and VB. Use <see /// cref="IInlineHintsService"/> for other languages. /// </summary> internal interface IInlineTypeHintsService : ILanguageService { Task<ImmutableArray<InlineHint>> GetInlineHintsAsync(Document document, TextSpan textSpan, 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.Text; namespace Microsoft.CodeAnalysis.InlineHints { /// <summary> /// Gets inline hints for type locations. This is an internal service only for C# and VB. Use <see /// cref="IInlineHintsService"/> for other languages. /// </summary> internal interface IInlineTypeHintsService : ILanguageService { Task<ImmutableArray<InlineHint>> GetInlineHintsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/Core/Portable/InternalUtilities/Hash.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 Microsoft.CodeAnalysis; namespace Roslyn.Utilities { internal static class Hash { /// <summary> /// This is how VB Anonymous Types combine hash values for fields. /// </summary> internal static int Combine(int newKey, int currentKey) { return unchecked((currentKey * (int)0xA5555529) + newKey); } internal static int Combine(bool newKeyPart, int currentKey) { return Combine(currentKey, newKeyPart ? 1 : 0); } /// <summary> /// This is how VB Anonymous Types combine hash values for fields. /// PERF: Do not use with enum types because that involves multiple /// unnecessary boxing operations. Unfortunately, we can't constrain /// T to "non-enum", so we'll use a more restrictive constraint. /// </summary> internal static int Combine<T>(T newKeyPart, int currentKey) where T : class? { int hash = unchecked(currentKey * (int)0xA5555529); if (newKeyPart != null) { return unchecked(hash + newKeyPart.GetHashCode()); } return hash; } internal static int CombineValues<T>(IEnumerable<T>? values, int maxItemsToHash = int.MaxValue) { if (values == null) { return 0; } var hashCode = 0; var count = 0; foreach (var value in values) { if (count++ >= maxItemsToHash) { break; } // Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible). if (value != null) { hashCode = Hash.Combine(value.GetHashCode(), hashCode); } } return hashCode; } internal static int CombineValues<T>(T[]? values, int maxItemsToHash = int.MaxValue) { if (values == null) { return 0; } var maxSize = Math.Min(maxItemsToHash, values.Length); var hashCode = 0; for (int i = 0; i < maxSize; i++) { T value = values[i]; // Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible). if (value != null) { hashCode = Hash.Combine(value.GetHashCode(), hashCode); } } return hashCode; } internal static int CombineValues<T>(ImmutableArray<T> values, int maxItemsToHash = int.MaxValue) { if (values.IsDefaultOrEmpty) { return 0; } var hashCode = 0; var count = 0; foreach (var value in values) { if (count++ >= maxItemsToHash) { break; } // Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible). if (value != null) { hashCode = Hash.Combine(value.GetHashCode(), hashCode); } } return hashCode; } internal static int CombineValues(IEnumerable<string?>? values, StringComparer stringComparer, int maxItemsToHash = int.MaxValue) { if (values == null) { return 0; } var hashCode = 0; var count = 0; foreach (var value in values) { if (count++ >= maxItemsToHash) { break; } if (value != null) { hashCode = Hash.Combine(stringComparer.GetHashCode(value), hashCode); } } return hashCode; } /// <summary> /// The offset bias value used in the FNV-1a algorithm /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> internal const int FnvOffsetBias = unchecked((int)2166136261); /// <summary> /// The generative factor used in the FNV-1a algorithm /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> internal const int FnvPrime = 16777619; /// <summary> /// Compute the FNV-1a hash of a sequence of bytes /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="data">The sequence of bytes</param> /// <returns>The FNV-1a hash of <paramref name="data"/></returns> internal static int GetFNVHashCode(byte[] data) { int hashCode = Hash.FnvOffsetBias; for (int i = 0; i < data.Length; i++) { hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Compute the FNV-1a hash of a sequence of bytes and determines if the byte /// sequence is valid ASCII and hence the hash code matches a char sequence /// encoding the same text. /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="data">The sequence of bytes that are likely to be ASCII text.</param> /// <param name="isAscii">True if the sequence contains only characters in the ASCII range.</param> /// <returns>The FNV-1a hash of <paramref name="data"/></returns> internal static int GetFNVHashCode(ReadOnlySpan<byte> data, out bool isAscii) { int hashCode = Hash.FnvOffsetBias; byte asciiMask = 0; for (int i = 0; i < data.Length; i++) { byte b = data[i]; asciiMask |= b; hashCode = unchecked((hashCode ^ b) * Hash.FnvPrime); } isAscii = (asciiMask & 0x80) == 0; return hashCode; } /// <summary> /// Compute the FNV-1a hash of a sequence of bytes /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="data">The sequence of bytes</param> /// <returns>The FNV-1a hash of <paramref name="data"/></returns> internal static int GetFNVHashCode(ImmutableArray<byte> data) { int hashCode = Hash.FnvOffsetBias; for (int i = 0; i < data.Length; i++) { hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Compute the hashcode of a sub-string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// Note: FNV-1a was developed and tuned for 8-bit sequences. We're using it here /// for 16-bit Unicode chars on the understanding that the majority of chars will /// fit into 8-bits and, therefore, the algorithm will retain its desirable traits /// for generating hash codes. /// </summary> internal static int GetFNVHashCode(ReadOnlySpan<char> data) { int hashCode = Hash.FnvOffsetBias; for (int i = 0; i < data.Length; i++) { hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Compute the hashcode of a sub-string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// Note: FNV-1a was developed and tuned for 8-bit sequences. We're using it here /// for 16-bit Unicode chars on the understanding that the majority of chars will /// fit into 8-bits and, therefore, the algorithm will retain its desirable traits /// for generating hash codes. /// </summary> /// <param name="text">The input string</param> /// <param name="start">The start index of the first character to hash</param> /// <param name="length">The number of characters, beginning with <paramref name="start"/> to hash</param> /// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending after <paramref name="length"/> characters.</returns> internal static int GetFNVHashCode(string text, int start, int length) => GetFNVHashCode(text.AsSpan(start, length)); internal static int GetCaseInsensitiveFNVHashCode(string text) { return GetCaseInsensitiveFNVHashCode(text.AsSpan(0, text.Length)); } internal static int GetCaseInsensitiveFNVHashCode(ReadOnlySpan<char> data) { int hashCode = Hash.FnvOffsetBias; for (int i = 0; i < data.Length; i++) { hashCode = unchecked((hashCode ^ CaseInsensitiveComparison.ToLower(data[i])) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Compute the hashcode of a sub-string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="text">The input string</param> /// <param name="start">The start index of the first character to hash</param> /// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending at the end of the string.</returns> internal static int GetFNVHashCode(string text, int start) { return GetFNVHashCode(text, start, length: text.Length - start); } /// <summary> /// Compute the hashcode of a string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="text">The input string</param> /// <returns>The FNV-1a hash code of <paramref name="text"/></returns> internal static int GetFNVHashCode(string text) { return CombineFNVHash(Hash.FnvOffsetBias, text); } /// <summary> /// Compute the hashcode of a string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="text">The input string</param> /// <returns>The FNV-1a hash code of <paramref name="text"/></returns> internal static int GetFNVHashCode(System.Text.StringBuilder text) { int hashCode = Hash.FnvOffsetBias; int end = text.Length; for (int i = 0; i < end; i++) { hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Compute the hashcode of a sub string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="text">The input string as a char array</param> /// <param name="start">The start index of the first character to hash</param> /// <param name="length">The number of characters, beginning with <paramref name="start"/> to hash</param> /// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending after <paramref name="length"/> characters.</returns> internal static int GetFNVHashCode(char[] text, int start, int length) { int hashCode = Hash.FnvOffsetBias; int end = start + length; for (int i = start; i < end; i++) { hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Compute the hashcode of a single character using the FNV-1a algorithm /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// Note: In general, this isn't any more useful than "char.GetHashCode". However, /// it may be needed if you need to generate the same hash code as a string or /// substring with just a single character. /// </summary> /// <param name="ch">The character to hash</param> /// <returns>The FNV-1a hash code of the character.</returns> internal static int GetFNVHashCode(char ch) { return Hash.CombineFNVHash(Hash.FnvOffsetBias, ch); } /// <summary> /// Combine a string with an existing FNV-1a hash code /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="hashCode">The accumulated hash code</param> /// <param name="text">The string to combine</param> /// <returns>The result of combining <paramref name="hashCode"/> with <paramref name="text"/> using the FNV-1a algorithm</returns> internal static int CombineFNVHash(int hashCode, string text) { foreach (char ch in text) { hashCode = unchecked((hashCode ^ ch) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Combine a char with an existing FNV-1a hash code /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="hashCode">The accumulated hash code</param> /// <param name="ch">The new character to combine</param> /// <returns>The result of combining <paramref name="hashCode"/> with <paramref name="ch"/> using the FNV-1a algorithm</returns> internal static int CombineFNVHash(int hashCode, char ch) { return unchecked((hashCode ^ ch) * Hash.FnvPrime); } } }
// 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 Microsoft.CodeAnalysis; namespace Roslyn.Utilities { internal static class Hash { /// <summary> /// This is how VB Anonymous Types combine hash values for fields. /// </summary> internal static int Combine(int newKey, int currentKey) { return unchecked((currentKey * (int)0xA5555529) + newKey); } internal static int Combine(bool newKeyPart, int currentKey) { return Combine(currentKey, newKeyPart ? 1 : 0); } /// <summary> /// This is how VB Anonymous Types combine hash values for fields. /// PERF: Do not use with enum types because that involves multiple /// unnecessary boxing operations. Unfortunately, we can't constrain /// T to "non-enum", so we'll use a more restrictive constraint. /// </summary> internal static int Combine<T>(T newKeyPart, int currentKey) where T : class? { int hash = unchecked(currentKey * (int)0xA5555529); if (newKeyPart != null) { return unchecked(hash + newKeyPart.GetHashCode()); } return hash; } internal static int CombineValues<T>(IEnumerable<T>? values, int maxItemsToHash = int.MaxValue) { if (values == null) { return 0; } var hashCode = 0; var count = 0; foreach (var value in values) { if (count++ >= maxItemsToHash) { break; } // Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible). if (value != null) { hashCode = Hash.Combine(value.GetHashCode(), hashCode); } } return hashCode; } internal static int CombineValues<T>(T[]? values, int maxItemsToHash = int.MaxValue) { if (values == null) { return 0; } var maxSize = Math.Min(maxItemsToHash, values.Length); var hashCode = 0; for (int i = 0; i < maxSize; i++) { T value = values[i]; // Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible). if (value != null) { hashCode = Hash.Combine(value.GetHashCode(), hashCode); } } return hashCode; } internal static int CombineValues<T>(ImmutableArray<T> values, int maxItemsToHash = int.MaxValue) { if (values.IsDefaultOrEmpty) { return 0; } var hashCode = 0; var count = 0; foreach (var value in values) { if (count++ >= maxItemsToHash) { break; } // Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible). if (value != null) { hashCode = Hash.Combine(value.GetHashCode(), hashCode); } } return hashCode; } internal static int CombineValues(IEnumerable<string?>? values, StringComparer stringComparer, int maxItemsToHash = int.MaxValue) { if (values == null) { return 0; } var hashCode = 0; var count = 0; foreach (var value in values) { if (count++ >= maxItemsToHash) { break; } if (value != null) { hashCode = Hash.Combine(stringComparer.GetHashCode(value), hashCode); } } return hashCode; } /// <summary> /// The offset bias value used in the FNV-1a algorithm /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> internal const int FnvOffsetBias = unchecked((int)2166136261); /// <summary> /// The generative factor used in the FNV-1a algorithm /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> internal const int FnvPrime = 16777619; /// <summary> /// Compute the FNV-1a hash of a sequence of bytes /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="data">The sequence of bytes</param> /// <returns>The FNV-1a hash of <paramref name="data"/></returns> internal static int GetFNVHashCode(byte[] data) { int hashCode = Hash.FnvOffsetBias; for (int i = 0; i < data.Length; i++) { hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Compute the FNV-1a hash of a sequence of bytes and determines if the byte /// sequence is valid ASCII and hence the hash code matches a char sequence /// encoding the same text. /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="data">The sequence of bytes that are likely to be ASCII text.</param> /// <param name="isAscii">True if the sequence contains only characters in the ASCII range.</param> /// <returns>The FNV-1a hash of <paramref name="data"/></returns> internal static int GetFNVHashCode(ReadOnlySpan<byte> data, out bool isAscii) { int hashCode = Hash.FnvOffsetBias; byte asciiMask = 0; for (int i = 0; i < data.Length; i++) { byte b = data[i]; asciiMask |= b; hashCode = unchecked((hashCode ^ b) * Hash.FnvPrime); } isAscii = (asciiMask & 0x80) == 0; return hashCode; } /// <summary> /// Compute the FNV-1a hash of a sequence of bytes /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="data">The sequence of bytes</param> /// <returns>The FNV-1a hash of <paramref name="data"/></returns> internal static int GetFNVHashCode(ImmutableArray<byte> data) { int hashCode = Hash.FnvOffsetBias; for (int i = 0; i < data.Length; i++) { hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Compute the hashcode of a sub-string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// Note: FNV-1a was developed and tuned for 8-bit sequences. We're using it here /// for 16-bit Unicode chars on the understanding that the majority of chars will /// fit into 8-bits and, therefore, the algorithm will retain its desirable traits /// for generating hash codes. /// </summary> internal static int GetFNVHashCode(ReadOnlySpan<char> data) { int hashCode = Hash.FnvOffsetBias; for (int i = 0; i < data.Length; i++) { hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Compute the hashcode of a sub-string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// Note: FNV-1a was developed and tuned for 8-bit sequences. We're using it here /// for 16-bit Unicode chars on the understanding that the majority of chars will /// fit into 8-bits and, therefore, the algorithm will retain its desirable traits /// for generating hash codes. /// </summary> /// <param name="text">The input string</param> /// <param name="start">The start index of the first character to hash</param> /// <param name="length">The number of characters, beginning with <paramref name="start"/> to hash</param> /// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending after <paramref name="length"/> characters.</returns> internal static int GetFNVHashCode(string text, int start, int length) => GetFNVHashCode(text.AsSpan(start, length)); internal static int GetCaseInsensitiveFNVHashCode(string text) { return GetCaseInsensitiveFNVHashCode(text.AsSpan(0, text.Length)); } internal static int GetCaseInsensitiveFNVHashCode(ReadOnlySpan<char> data) { int hashCode = Hash.FnvOffsetBias; for (int i = 0; i < data.Length; i++) { hashCode = unchecked((hashCode ^ CaseInsensitiveComparison.ToLower(data[i])) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Compute the hashcode of a sub-string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="text">The input string</param> /// <param name="start">The start index of the first character to hash</param> /// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending at the end of the string.</returns> internal static int GetFNVHashCode(string text, int start) { return GetFNVHashCode(text, start, length: text.Length - start); } /// <summary> /// Compute the hashcode of a string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="text">The input string</param> /// <returns>The FNV-1a hash code of <paramref name="text"/></returns> internal static int GetFNVHashCode(string text) { return CombineFNVHash(Hash.FnvOffsetBias, text); } /// <summary> /// Compute the hashcode of a string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="text">The input string</param> /// <returns>The FNV-1a hash code of <paramref name="text"/></returns> internal static int GetFNVHashCode(System.Text.StringBuilder text) { int hashCode = Hash.FnvOffsetBias; int end = text.Length; for (int i = 0; i < end; i++) { hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Compute the hashcode of a sub string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="text">The input string as a char array</param> /// <param name="start">The start index of the first character to hash</param> /// <param name="length">The number of characters, beginning with <paramref name="start"/> to hash</param> /// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending after <paramref name="length"/> characters.</returns> internal static int GetFNVHashCode(char[] text, int start, int length) { int hashCode = Hash.FnvOffsetBias; int end = start + length; for (int i = start; i < end; i++) { hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Compute the hashcode of a single character using the FNV-1a algorithm /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// Note: In general, this isn't any more useful than "char.GetHashCode". However, /// it may be needed if you need to generate the same hash code as a string or /// substring with just a single character. /// </summary> /// <param name="ch">The character to hash</param> /// <returns>The FNV-1a hash code of the character.</returns> internal static int GetFNVHashCode(char ch) { return Hash.CombineFNVHash(Hash.FnvOffsetBias, ch); } /// <summary> /// Combine a string with an existing FNV-1a hash code /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="hashCode">The accumulated hash code</param> /// <param name="text">The string to combine</param> /// <returns>The result of combining <paramref name="hashCode"/> with <paramref name="text"/> using the FNV-1a algorithm</returns> internal static int CombineFNVHash(int hashCode, string text) { foreach (char ch in text) { hashCode = unchecked((hashCode ^ ch) * Hash.FnvPrime); } return hashCode; } /// <summary> /// Combine a char with an existing FNV-1a hash code /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="hashCode">The accumulated hash code</param> /// <param name="ch">The new character to combine</param> /// <returns>The result of combining <paramref name="hashCode"/> with <paramref name="ch"/> using the FNV-1a algorithm</returns> internal static int CombineFNVHash(int hashCode, char ch) { return unchecked((hashCode ^ ch) * Hash.FnvPrime); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.FunctionPointerTypeSymbolKey.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.Reflection.Metadata; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class FunctionPointerTypeSymbolKey { public static void Create(IFunctionPointerTypeSymbol symbol, SymbolKeyWriter visitor) { var callingConvention = symbol.Signature.CallingConvention; visitor.WriteInteger((int)callingConvention); if (callingConvention == SignatureCallingConvention.Unmanaged) { visitor.WriteSymbolKeyArray(symbol.Signature.UnmanagedCallingConventionTypes); } visitor.WriteRefKind(symbol.Signature.RefKind); visitor.WriteSymbolKey(symbol.Signature.ReturnType); visitor.WriteRefKindArray(symbol.Signature.Parameters); visitor.WriteParameterTypesArray(symbol.Signature.Parameters); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var callingConvention = (SignatureCallingConvention)reader.ReadInteger(); var callingConventionModifiers = ImmutableArray<INamedTypeSymbol>.Empty; if (callingConvention == SignatureCallingConvention.Unmanaged) { using var modifiersBuilder = reader.ReadSymbolKeyArray<INamedTypeSymbol>(out var conventionTypesFailureReason); if (conventionTypesFailureReason != null) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} {nameof(callingConventionModifiers)} failed -> {conventionTypesFailureReason})"; return default; } callingConventionModifiers = modifiersBuilder.ToImmutable(); } var returnRefKind = reader.ReadRefKind(); var returnType = reader.ReadSymbolKey(out var returnTypeFailureReason); using var paramRefKinds = reader.ReadRefKindArray(); using var parameterTypes = reader.ReadSymbolKeyArray<ITypeSymbol>(out var parameterTypesFailureReason); if (returnTypeFailureReason != null) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} {nameof(returnType)} failed -> {returnTypeFailureReason})"; return default; } if (parameterTypesFailureReason != null) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} {nameof(parameterTypes)} failed -> {parameterTypesFailureReason})"; return default; } if (parameterTypes.IsDefault) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} no parameter types)"; return default; } if (returnType.GetAnySymbol() is not ITypeSymbol returnTypeSymbol) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} no return type)"; return default; } if (reader.Compilation.Language == LanguageNames.VisualBasic) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} is not supported in {LanguageNames.VisualBasic})"; return default; } failureReason = null; return new SymbolKeyResolution(reader.Compilation.CreateFunctionPointerTypeSymbol( returnTypeSymbol, returnRefKind, parameterTypes.ToImmutable(), paramRefKinds.ToImmutable(), callingConvention, callingConventionModifiers)); } } } }
// 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.Reflection.Metadata; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class FunctionPointerTypeSymbolKey { public static void Create(IFunctionPointerTypeSymbol symbol, SymbolKeyWriter visitor) { var callingConvention = symbol.Signature.CallingConvention; visitor.WriteInteger((int)callingConvention); if (callingConvention == SignatureCallingConvention.Unmanaged) { visitor.WriteSymbolKeyArray(symbol.Signature.UnmanagedCallingConventionTypes); } visitor.WriteRefKind(symbol.Signature.RefKind); visitor.WriteSymbolKey(symbol.Signature.ReturnType); visitor.WriteRefKindArray(symbol.Signature.Parameters); visitor.WriteParameterTypesArray(symbol.Signature.Parameters); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var callingConvention = (SignatureCallingConvention)reader.ReadInteger(); var callingConventionModifiers = ImmutableArray<INamedTypeSymbol>.Empty; if (callingConvention == SignatureCallingConvention.Unmanaged) { using var modifiersBuilder = reader.ReadSymbolKeyArray<INamedTypeSymbol>(out var conventionTypesFailureReason); if (conventionTypesFailureReason != null) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} {nameof(callingConventionModifiers)} failed -> {conventionTypesFailureReason})"; return default; } callingConventionModifiers = modifiersBuilder.ToImmutable(); } var returnRefKind = reader.ReadRefKind(); var returnType = reader.ReadSymbolKey(out var returnTypeFailureReason); using var paramRefKinds = reader.ReadRefKindArray(); using var parameterTypes = reader.ReadSymbolKeyArray<ITypeSymbol>(out var parameterTypesFailureReason); if (returnTypeFailureReason != null) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} {nameof(returnType)} failed -> {returnTypeFailureReason})"; return default; } if (parameterTypesFailureReason != null) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} {nameof(parameterTypes)} failed -> {parameterTypesFailureReason})"; return default; } if (parameterTypes.IsDefault) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} no parameter types)"; return default; } if (returnType.GetAnySymbol() is not ITypeSymbol returnTypeSymbol) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} no return type)"; return default; } if (reader.Compilation.Language == LanguageNames.VisualBasic) { failureReason = $"({nameof(FunctionPointerTypeSymbolKey)} is not supported in {LanguageNames.VisualBasic})"; return default; } failureReason = null; return new SymbolKeyResolution(reader.Compilation.CreateFunctionPointerTypeSymbol( returnTypeSymbol, returnRefKind, parameterTypes.ToImmutable(), paramRefKinds.ToImmutable(), callingConvention, callingConventionModifiers)); } } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/Core/Portable/Desktop/DesktopAssemblyIdentityComparer.Fx.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. #define NDP4_AUTO_VERSION_ROLLFORWARD using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis { // TODO: Consider reducing the table memory footprint. public partial class DesktopAssemblyIdentityComparer { private sealed class FrameworkAssemblyDictionary : Dictionary<string, FrameworkAssemblyDictionary.Value> { public FrameworkAssemblyDictionary() : base(SimpleNameComparer) { } public struct Value { public readonly ImmutableArray<byte> PublicKeyToken; public readonly AssemblyVersion Version; public Value(ImmutableArray<byte> publicKeyToken, AssemblyVersion version) { this.PublicKeyToken = publicKeyToken; this.Version = version; } } public void Add( string name, ImmutableArray<byte> publicKeyToken, AssemblyVersion version) { Add(name, new Value(publicKeyToken, version)); } } private sealed class FrameworkRetargetingDictionary : Dictionary<FrameworkRetargetingDictionary.Key, List<FrameworkRetargetingDictionary.Value>> { public FrameworkRetargetingDictionary() { } public struct Key : IEquatable<Key> { public readonly string Name; public readonly ImmutableArray<byte> PublicKeyToken; public Key(string name, ImmutableArray<byte> publicKeyToken) { this.Name = name; this.PublicKeyToken = publicKeyToken; } public bool Equals(Key other) { return SimpleNameComparer.Equals(this.Name, other.Name) && this.PublicKeyToken.SequenceEqual(other.PublicKeyToken); } public override bool Equals(object? obj) { return obj is Key && Equals((Key)obj); } public override int GetHashCode() { return SimpleNameComparer.GetHashCode(Name) ^ PublicKeyToken[0]; } } public struct Value { public readonly AssemblyVersion VersionLow; public readonly AssemblyVersion VersionHigh; public readonly string NewName; public readonly ImmutableArray<byte> NewPublicKeyToken; public readonly AssemblyVersion NewVersion; public readonly bool IsPortable; public Value( AssemblyVersion versionLow, AssemblyVersion versionHigh, string newName, ImmutableArray<byte> newPublicKeyToken, AssemblyVersion newVersion, bool isPortable) { VersionLow = versionLow; VersionHigh = versionHigh; NewName = newName; NewPublicKeyToken = newPublicKeyToken; NewVersion = newVersion; IsPortable = isPortable; } } public void Add( string name, ImmutableArray<byte> publicKeyToken, AssemblyVersion versionLow, object versionHighNull, string newName, ImmutableArray<byte> newPublicKeyToken, AssemblyVersion newVersion) { List<Value>? values; var key = new Key(name, publicKeyToken); if (!TryGetValue(key, out values)) { Add(key, values = new List<Value>()); } values.Add(new Value(versionLow, versionHigh: default, newName, newPublicKeyToken, newVersion, isPortable: false)); } public void Add( string name, ImmutableArray<byte> publicKeyToken, AssemblyVersion versionLow, AssemblyVersion versionHigh, string newName, ImmutableArray<byte> newPublicKeyToken, AssemblyVersion newVersion, bool isPortable) { List<Value>? values; var key = new Key(name, publicKeyToken); if (!TryGetValue(key, out values)) { Add(key, values = new List<Value>()); } values.Add(new Value(versionLow, versionHigh, newName, newPublicKeyToken, newVersion, isPortable)); } public bool TryGetValue(AssemblyIdentity identity, out Value value) { List<Value>? values; if (!TryGetValue(new Key(identity.Name, identity.PublicKeyToken), out values)) { value = default; return false; } for (int i = 0; i < values.Count; i++) { value = values[i]; var version = (AssemblyVersion)identity.Version; if (value.VersionHigh.Major == 0) { Debug.Assert(value.VersionHigh == default(AssemblyVersion)); if (version == value.VersionLow) { return true; } } else if (version >= value.VersionLow && version <= value.VersionHigh) { return true; } } value = default; return false; } } private static readonly ImmutableArray<byte> s_NETCF_PUBLIC_KEY_TOKEN_1 = ImmutableArray.Create(new byte[] { 0x1c, 0x9e, 0x25, 0x96, 0x86, 0xf9, 0x21, 0xe0 }); private static readonly ImmutableArray<byte> s_NETCF_PUBLIC_KEY_TOKEN_2 = ImmutableArray.Create(new byte[] { 0x5f, 0xd5, 0x7c, 0x54, 0x3a, 0x9c, 0x02, 0x47 }); private static readonly ImmutableArray<byte> s_NETCF_PUBLIC_KEY_TOKEN_3 = ImmutableArray.Create(new byte[] { 0x96, 0x9d, 0xb8, 0x05, 0x3d, 0x33, 0x22, 0xac }); private static readonly ImmutableArray<byte> s_SQL_PUBLIC_KEY_TOKEN = ImmutableArray.Create(new byte[] { 0x89, 0x84, 0x5d, 0xcd, 0x80, 0x80, 0xcc, 0x91 }); private static readonly ImmutableArray<byte> s_SQL_MOBILE_PUBLIC_KEY_TOKEN = ImmutableArray.Create(new byte[] { 0x3b, 0xe2, 0x35, 0xdf, 0x1c, 0x8d, 0x2a, 0xd3 }); private static readonly ImmutableArray<byte> s_ECMA_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 }); private static readonly ImmutableArray<byte> s_SHAREDLIB_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 }); private static readonly ImmutableArray<byte> s_MICROSOFT_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[] { 0xb0, 0x3f, 0x5f, 0x7f, 0x11, 0xd5, 0x0a, 0x3a }); private static readonly ImmutableArray<byte> s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[] { 0x7c, 0xec, 0x85, 0xd7, 0xbe, 0xa7, 0x79, 0x8e }); private static readonly ImmutableArray<byte> s_SILVERLIGHT_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 }); private static readonly ImmutableArray<byte> s_RIA_SERVICES_KEY_TOKEN = ImmutableArray.Create(new byte[] { 0xdd, 0xd0, 0xda, 0x4d, 0x3e, 0x67, 0x82, 0x17 }); private static readonly AssemblyVersion s_VER_VS_COMPATIBILITY_ASSEMBLYVERSION_STR_L = new AssemblyVersion(8, 0, 0, 0); private static readonly AssemblyVersion s_VER_VS_ASSEMBLYVERSION_STR_L = new AssemblyVersion(10, 0, 0, 0); private static readonly AssemblyVersion s_VER_SQL_ASSEMBLYVERSION_STR_L = new AssemblyVersion(9, 0, 242, 0); private static readonly AssemblyVersion s_VER_LINQ_ASSEMBLYVERSION_STR_L = new AssemblyVersion(3, 0, 0, 0); private static readonly AssemblyVersion s_VER_LINQ_ASSEMBLYVERSION_STR_2_L = new AssemblyVersion(3, 5, 0, 0); private static readonly AssemblyVersion s_VER_SQL_ORCAS_ASSEMBLYVERSION_STR_L = new AssemblyVersion(3, 5, 0, 0); private static readonly AssemblyVersion s_VER_ASSEMBLYVERSION_STR_L = new AssemblyVersion(4, 0, 0, 0); private static readonly AssemblyVersion s_VER_VC_STLCLR_ASSEMBLYVERSION_STR_L = new AssemblyVersion(2, 0, 0, 0); private const string NULL = null; private const bool TRUE = true; // Replace: // "([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)" -> new AssemblyVersion($1, $2, $3, $4) // ,[ ]+FxPolicyHelper::AppXBinder_[A-Z]+ -> // " -> " (whole word, case sensitive) // :: -> . // copied from ndp\clr\src\fusion\binder\fxretarget.cpp private static readonly FrameworkRetargetingDictionary s_arRetargetPolicy = new FrameworkRetargetingDictionary() { // ECMA v1.0 redirect {"System", s_ECMA_PUBLICKEY_STR_L, new AssemblyVersion(1, 0, 0, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_ECMA_PUBLICKEY_STR_L, new AssemblyVersion(1, 0, 0, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Compat framework redirect {"System", s_NETCF_PUBLIC_KEY_TOKEN_1, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(7, 0, 5000, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"System", s_NETCF_PUBLIC_KEY_TOKEN_1, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(7, 0, 5500, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"Microsoft.WindowsCE.Forms", s_NETCF_PUBLIC_KEY_TOKEN_1, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_NETCF_PUBLIC_KEY_TOKEN_3, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.WindowsCE.Forms", s_NETCF_PUBLIC_KEY_TOKEN_1, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_NETCF_PUBLIC_KEY_TOKEN_3, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.WindowsCE.Forms", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_NETCF_PUBLIC_KEY_TOKEN_3, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.WindowsCE.Forms", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_NETCF_PUBLIC_KEY_TOKEN_3, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.WindowsCE.Forms", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_NETCF_PUBLIC_KEY_TOKEN_3, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.WindowsCE.Forms", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_NETCF_PUBLIC_KEY_TOKEN_3, s_VER_ASSEMBLYVERSION_STR_L}, // Compat framework name redirect {"System.Data.SqlClient", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlClient", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Common", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Common", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms.DataGrid", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, "System.Windows.Forms", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms.DataGrid", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, "System.Windows.Forms", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // v2.0 Compact framework redirect {"System", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Messaging", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlClient", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Common", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms.DataGrid", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), "System.Windows.Forms", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(8, 0, 0, 0), new AssemblyVersion(8, 0, 10, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, // v3.5 Compact framework redirect {"System", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Messaging", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlClient", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms.DataGrid", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), "System.Windows.Forms", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(8, 1, 0, 0), new AssemblyVersion(8, 1, 5, 0), "Microsoft.VisualBasic", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, // SQL Everywhere redirect for Orcas {"System.Data.SqlClient", s_SQL_MOBILE_PUBLIC_KEY_TOKEN, new AssemblyVersion(3, 5, 0, 0), NULL, "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlServerCe", s_SQL_MOBILE_PUBLIC_KEY_TOKEN, new AssemblyVersion(3, 5, 0, 0), NULL, NULL, s_SQL_PUBLIC_KEY_TOKEN, s_VER_SQL_ORCAS_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlServerCe", s_SQL_MOBILE_PUBLIC_KEY_TOKEN, new AssemblyVersion(3, 5, 1, 0), new AssemblyVersion(3, 5, 200, 999), NULL, s_SQL_PUBLIC_KEY_TOKEN, s_VER_SQL_ORCAS_ASSEMBLYVERSION_STR_L}, // SQL CE redirect {"System.Data.SqlClient", s_SQL_MOBILE_PUBLIC_KEY_TOKEN, new AssemblyVersion(3, 0, 3600, 0), NULL, "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlServerCe", s_SQL_MOBILE_PUBLIC_KEY_TOKEN, new AssemblyVersion(3, 0, 3600, 0), NULL, NULL, s_SQL_PUBLIC_KEY_TOKEN, s_VER_SQL_ASSEMBLYVERSION_STR_L}, // Linq and friends redirect {"system.xml.linq", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_LINQ_ASSEMBLYVERSION_STR_2_L}, {"system.data.DataSetExtensions", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_LINQ_ASSEMBLYVERSION_STR_2_L}, {"System.Core", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_LINQ_ASSEMBLYVERSION_STR_2_L}, {"System.ServiceModel", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_LINQ_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Serialization", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_LINQ_ASSEMBLYVERSION_STR_L}, // Portable Library redirects {"mscorlib", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.ComponentModel.Composition", s_SILVERLIGHT_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.ComponentModel.DataAnnotations",s_RIA_SERVICES_KEY_TOKEN, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Core", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Net", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Numerics", s_SILVERLIGHT_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"Microsoft.CSharp", s_SILVERLIGHT_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Runtime.Serialization", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.ServiceModel", s_SILVERLIGHT_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.ServiceModel.Web", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Xml", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Xml.Linq", s_SILVERLIGHT_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Xml.Serialization", s_SILVERLIGHT_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Windows", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, }; // Copied from ndp\clr\src\inc\fxretarget.h private static readonly FrameworkAssemblyDictionary s_arFxPolicy = new FrameworkAssemblyDictionary() { {"Accessibility", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"CustomMarshalers", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"ISymWrapper", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.JScript", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic.Compatibility", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic.Compatibility.Data", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualC", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"mscorlib", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Configuration", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Configuration.Install", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.OracleClient", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlXml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Deployment", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Design", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.DirectoryServices", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.DirectoryServices.Protocols", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing.Design", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.EnterpriseServices", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Management", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Messaging", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Remoting", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Serialization.Formatters.Soap", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Security", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceProcess", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Transactions", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Mobile", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.RegularExpressions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Has to be supported in AppX, because it is in transitive closure of supported assemblies {"System.Windows.Forms", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, #if NDP4_AUTO_VERSION_ROLLFORWARD // Post-Everett FX 2.0 assemblies: {"AspNetMMCExt", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"sysglobl", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Build.Engine", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Build.Framework", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // FX 3.0 assemblies: // Note: we shipped .NET 4.0 with entries in this list for PresentationCFFRasterizer and System.ServiceModel.Install // even though these assemblies did not ship with .NET 4.0. To maintain 100% compatibility with 4.0 we will keep // these in .NET 4.5, but we should remove them in a future SxS version of the Framework. {"PresentationCFFRasterizer", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // See note above {"PresentationCore", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework.Aero", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework.Classic", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework.Luna", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework.Royale", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationUI", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"ReachFramework", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Printing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Speech", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"UIAutomationClient", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"UIAutomationClientsideProviders", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"UIAutomationProvider", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"UIAutomationTypes", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"WindowsBase", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"WindowsFormsIntegration", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"SMDiagnostics", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IdentityModel", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IdentityModel.Selectors", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IO.Log", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Serialization", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Install", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // See note above {"System.ServiceModel.WasHosting", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Workflow.Activities", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Workflow.ComponentModel", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Workflow.Runtime", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Transactions.Bridge", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Transactions.Bridge.Dtc", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // FX 3.5 assemblies: {"System.AddIn", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.AddIn.Contract", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ComponentModel.Composition", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Shipping out-of-band {"System.Core", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.DataSetExtensions", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Linq", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml.Linq", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.DirectoryServices.AccountManagement", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Management.Instrumentation", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Web", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Needed for portable libraries {"System.Web.Extensions", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Extensions.Design", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Presentation", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.WorkflowServices", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Microsoft.Data.Entity.Build.Tasks.dll should not be unified on purpose - it is supported SxS, i.e. both 3.5 and 4.0 versions can be loaded into CLR 4.0+. // {"Microsoft.Data.Entity.Build.Tasks", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L}, // FX 3.5 SP1 assemblies: {"System.ComponentModel.DataAnnotations", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Entity", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Entity.Design", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Services", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Services.Client", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Services.Design", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Abstractions", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.DynamicData", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.DynamicData.Design", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Entity", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Entity.Design", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Routing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // FX 4.0 assemblies: {"Microsoft.Build", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.CSharp", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Dynamic", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Numerics", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xaml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Microsoft.Workflow.Compiler.exe: // System.Workflow.ComponentModel.dll started to depend on Microsoft.Workflow.Compiler.exe in 4.0 RTM {"Microsoft.Workflow.Compiler", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // FX 4.5 assemblies: {"Microsoft.Activities.Build", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Build.Conversion.v4.0", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Build.Tasks.v4.0", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Build.Utilities.v4.0", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Internal.Tasks.Dataflow", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic.Activities.Compiler", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualC.STLCLR", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VC_STLCLR_ASSEMBLYVERSION_STR_L}, {"Microsoft.Windows.ApplicationServer.Applications", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationBuildTasks", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework.Aero2", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework.AeroLite", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework-SystemCore", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework-SystemData", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework-SystemDrawing", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework-SystemXml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework-SystemXmlLinq", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Activities", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Activities.Core.Presentation", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Activities.DurableInstancing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Activities.Presentation", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ComponentModel.Composition.Registration", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Device", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IdentityModel.Services", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IO.Compression", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IO.Compression.FileSystem", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net.Http", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net.Http.WebRequest", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection.Context", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Caching", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.DurableInstancing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.WindowsRuntime", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.WindowsRuntime.UI.Xaml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Activation", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Activities", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Channels", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Discovery", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Internals", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Routing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.ServiceMoniker40", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.ApplicationServices", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Has to be supported in AppX, because it is in transitive closure of supported assemblies {"System.Web.DataVisualization", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.DataVisualization.Design", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Controls.Ribbon", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms.DataVisualization", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms.DataVisualization.Design", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Input.Manipulations", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xaml.Hosting", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"XamlBuildTask", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"XsdBuildTask", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Numerics.Vectors", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // FX 4.5 facade assemblies: {"System.Collections", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Collections.Concurrent", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ComponentModel", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ComponentModel.Annotations", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ComponentModel.EventBasedAsync", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Diagnostics.Contracts", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Diagnostics.Debug", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Diagnostics.Tools", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Diagnostics.Tracing", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Dynamic.Runtime", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Globalization", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IO", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Linq", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Linq.Expressions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Linq.Parallel", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Linq.Queryable", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net.Http.Rtc", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net.NetworkInformation", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net.Primitives", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net.Requests", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ObjectModel", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection.Emit", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection.Emit.ILGeneration", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection.Emit.Lightweight", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection.Extensions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection.Primitives", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Resources.ResourceManager", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Extensions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Handles", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.InteropServices", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.InteropServices.WindowsRuntime", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Numerics", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Serialization.Json", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Serialization.Primitives", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Serialization.Xml", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Security.Principal", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Duplex", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Http", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.NetTcp", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Primitives", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Security", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Text.Encoding", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Text.Encoding.Extensions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Text.RegularExpressions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Threading", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Threading.Tasks", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Threading.Tasks.Parallel", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Threading.Timer", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml.ReaderWriter", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml.XDocument", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml.XmlSerializer", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Manually added facades {"System.Windows", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml.Serialization", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, #endif // NDP4_AUTO_VERSION_ROLLFORWARD }; } }
// 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. #define NDP4_AUTO_VERSION_ROLLFORWARD using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis { // TODO: Consider reducing the table memory footprint. public partial class DesktopAssemblyIdentityComparer { private sealed class FrameworkAssemblyDictionary : Dictionary<string, FrameworkAssemblyDictionary.Value> { public FrameworkAssemblyDictionary() : base(SimpleNameComparer) { } public struct Value { public readonly ImmutableArray<byte> PublicKeyToken; public readonly AssemblyVersion Version; public Value(ImmutableArray<byte> publicKeyToken, AssemblyVersion version) { this.PublicKeyToken = publicKeyToken; this.Version = version; } } public void Add( string name, ImmutableArray<byte> publicKeyToken, AssemblyVersion version) { Add(name, new Value(publicKeyToken, version)); } } private sealed class FrameworkRetargetingDictionary : Dictionary<FrameworkRetargetingDictionary.Key, List<FrameworkRetargetingDictionary.Value>> { public FrameworkRetargetingDictionary() { } public struct Key : IEquatable<Key> { public readonly string Name; public readonly ImmutableArray<byte> PublicKeyToken; public Key(string name, ImmutableArray<byte> publicKeyToken) { this.Name = name; this.PublicKeyToken = publicKeyToken; } public bool Equals(Key other) { return SimpleNameComparer.Equals(this.Name, other.Name) && this.PublicKeyToken.SequenceEqual(other.PublicKeyToken); } public override bool Equals(object? obj) { return obj is Key && Equals((Key)obj); } public override int GetHashCode() { return SimpleNameComparer.GetHashCode(Name) ^ PublicKeyToken[0]; } } public struct Value { public readonly AssemblyVersion VersionLow; public readonly AssemblyVersion VersionHigh; public readonly string NewName; public readonly ImmutableArray<byte> NewPublicKeyToken; public readonly AssemblyVersion NewVersion; public readonly bool IsPortable; public Value( AssemblyVersion versionLow, AssemblyVersion versionHigh, string newName, ImmutableArray<byte> newPublicKeyToken, AssemblyVersion newVersion, bool isPortable) { VersionLow = versionLow; VersionHigh = versionHigh; NewName = newName; NewPublicKeyToken = newPublicKeyToken; NewVersion = newVersion; IsPortable = isPortable; } } public void Add( string name, ImmutableArray<byte> publicKeyToken, AssemblyVersion versionLow, object versionHighNull, string newName, ImmutableArray<byte> newPublicKeyToken, AssemblyVersion newVersion) { List<Value>? values; var key = new Key(name, publicKeyToken); if (!TryGetValue(key, out values)) { Add(key, values = new List<Value>()); } values.Add(new Value(versionLow, versionHigh: default, newName, newPublicKeyToken, newVersion, isPortable: false)); } public void Add( string name, ImmutableArray<byte> publicKeyToken, AssemblyVersion versionLow, AssemblyVersion versionHigh, string newName, ImmutableArray<byte> newPublicKeyToken, AssemblyVersion newVersion, bool isPortable) { List<Value>? values; var key = new Key(name, publicKeyToken); if (!TryGetValue(key, out values)) { Add(key, values = new List<Value>()); } values.Add(new Value(versionLow, versionHigh, newName, newPublicKeyToken, newVersion, isPortable)); } public bool TryGetValue(AssemblyIdentity identity, out Value value) { List<Value>? values; if (!TryGetValue(new Key(identity.Name, identity.PublicKeyToken), out values)) { value = default; return false; } for (int i = 0; i < values.Count; i++) { value = values[i]; var version = (AssemblyVersion)identity.Version; if (value.VersionHigh.Major == 0) { Debug.Assert(value.VersionHigh == default(AssemblyVersion)); if (version == value.VersionLow) { return true; } } else if (version >= value.VersionLow && version <= value.VersionHigh) { return true; } } value = default; return false; } } private static readonly ImmutableArray<byte> s_NETCF_PUBLIC_KEY_TOKEN_1 = ImmutableArray.Create(new byte[] { 0x1c, 0x9e, 0x25, 0x96, 0x86, 0xf9, 0x21, 0xe0 }); private static readonly ImmutableArray<byte> s_NETCF_PUBLIC_KEY_TOKEN_2 = ImmutableArray.Create(new byte[] { 0x5f, 0xd5, 0x7c, 0x54, 0x3a, 0x9c, 0x02, 0x47 }); private static readonly ImmutableArray<byte> s_NETCF_PUBLIC_KEY_TOKEN_3 = ImmutableArray.Create(new byte[] { 0x96, 0x9d, 0xb8, 0x05, 0x3d, 0x33, 0x22, 0xac }); private static readonly ImmutableArray<byte> s_SQL_PUBLIC_KEY_TOKEN = ImmutableArray.Create(new byte[] { 0x89, 0x84, 0x5d, 0xcd, 0x80, 0x80, 0xcc, 0x91 }); private static readonly ImmutableArray<byte> s_SQL_MOBILE_PUBLIC_KEY_TOKEN = ImmutableArray.Create(new byte[] { 0x3b, 0xe2, 0x35, 0xdf, 0x1c, 0x8d, 0x2a, 0xd3 }); private static readonly ImmutableArray<byte> s_ECMA_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 }); private static readonly ImmutableArray<byte> s_SHAREDLIB_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 }); private static readonly ImmutableArray<byte> s_MICROSOFT_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[] { 0xb0, 0x3f, 0x5f, 0x7f, 0x11, 0xd5, 0x0a, 0x3a }); private static readonly ImmutableArray<byte> s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[] { 0x7c, 0xec, 0x85, 0xd7, 0xbe, 0xa7, 0x79, 0x8e }); private static readonly ImmutableArray<byte> s_SILVERLIGHT_PUBLICKEY_STR_L = ImmutableArray.Create(new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 }); private static readonly ImmutableArray<byte> s_RIA_SERVICES_KEY_TOKEN = ImmutableArray.Create(new byte[] { 0xdd, 0xd0, 0xda, 0x4d, 0x3e, 0x67, 0x82, 0x17 }); private static readonly AssemblyVersion s_VER_VS_COMPATIBILITY_ASSEMBLYVERSION_STR_L = new AssemblyVersion(8, 0, 0, 0); private static readonly AssemblyVersion s_VER_VS_ASSEMBLYVERSION_STR_L = new AssemblyVersion(10, 0, 0, 0); private static readonly AssemblyVersion s_VER_SQL_ASSEMBLYVERSION_STR_L = new AssemblyVersion(9, 0, 242, 0); private static readonly AssemblyVersion s_VER_LINQ_ASSEMBLYVERSION_STR_L = new AssemblyVersion(3, 0, 0, 0); private static readonly AssemblyVersion s_VER_LINQ_ASSEMBLYVERSION_STR_2_L = new AssemblyVersion(3, 5, 0, 0); private static readonly AssemblyVersion s_VER_SQL_ORCAS_ASSEMBLYVERSION_STR_L = new AssemblyVersion(3, 5, 0, 0); private static readonly AssemblyVersion s_VER_ASSEMBLYVERSION_STR_L = new AssemblyVersion(4, 0, 0, 0); private static readonly AssemblyVersion s_VER_VC_STLCLR_ASSEMBLYVERSION_STR_L = new AssemblyVersion(2, 0, 0, 0); private const string NULL = null; private const bool TRUE = true; // Replace: // "([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)" -> new AssemblyVersion($1, $2, $3, $4) // ,[ ]+FxPolicyHelper::AppXBinder_[A-Z]+ -> // " -> " (whole word, case sensitive) // :: -> . // copied from ndp\clr\src\fusion\binder\fxretarget.cpp private static readonly FrameworkRetargetingDictionary s_arRetargetPolicy = new FrameworkRetargetingDictionary() { // ECMA v1.0 redirect {"System", s_ECMA_PUBLICKEY_STR_L, new AssemblyVersion(1, 0, 0, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_ECMA_PUBLICKEY_STR_L, new AssemblyVersion(1, 0, 0, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Compat framework redirect {"System", s_NETCF_PUBLIC_KEY_TOKEN_1, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(7, 0, 5000, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"System", s_NETCF_PUBLIC_KEY_TOKEN_1, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(7, 0, 5500, 0), NULL, NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"Microsoft.WindowsCE.Forms", s_NETCF_PUBLIC_KEY_TOKEN_1, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_NETCF_PUBLIC_KEY_TOKEN_3, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.WindowsCE.Forms", s_NETCF_PUBLIC_KEY_TOKEN_1, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_NETCF_PUBLIC_KEY_TOKEN_3, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.WindowsCE.Forms", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_NETCF_PUBLIC_KEY_TOKEN_3, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.WindowsCE.Forms", s_NETCF_PUBLIC_KEY_TOKEN_2, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_NETCF_PUBLIC_KEY_TOKEN_3, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.WindowsCE.Forms", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, NULL, s_NETCF_PUBLIC_KEY_TOKEN_3, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.WindowsCE.Forms", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, NULL, s_NETCF_PUBLIC_KEY_TOKEN_3, s_VER_ASSEMBLYVERSION_STR_L}, // Compat framework name redirect {"System.Data.SqlClient", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlClient", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Common", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Common", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms.DataGrid", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5000, 0), NULL, "System.Windows.Forms", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms.DataGrid", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(1, 0, 5500, 0), NULL, "System.Windows.Forms", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // v2.0 Compact framework redirect {"System", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Messaging", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlClient", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Common", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms.DataGrid", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(2, 0, 0, 0), new AssemblyVersion(2, 0, 10, 0), "System.Windows.Forms", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(8, 0, 0, 0), new AssemblyVersion(8, 0, 10, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, // v3.5 Compact framework redirect {"System", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Messaging", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlClient", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms.DataGrid", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), "System.Windows.Forms", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(8, 1, 0, 0), new AssemblyVersion(8, 1, 5, 0), "Microsoft.VisualBasic", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, // SQL Everywhere redirect for Orcas {"System.Data.SqlClient", s_SQL_MOBILE_PUBLIC_KEY_TOKEN, new AssemblyVersion(3, 5, 0, 0), NULL, "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlServerCe", s_SQL_MOBILE_PUBLIC_KEY_TOKEN, new AssemblyVersion(3, 5, 0, 0), NULL, NULL, s_SQL_PUBLIC_KEY_TOKEN, s_VER_SQL_ORCAS_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlServerCe", s_SQL_MOBILE_PUBLIC_KEY_TOKEN, new AssemblyVersion(3, 5, 1, 0), new AssemblyVersion(3, 5, 200, 999), NULL, s_SQL_PUBLIC_KEY_TOKEN, s_VER_SQL_ORCAS_ASSEMBLYVERSION_STR_L}, // SQL CE redirect {"System.Data.SqlClient", s_SQL_MOBILE_PUBLIC_KEY_TOKEN, new AssemblyVersion(3, 0, 3600, 0), NULL, "System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlServerCe", s_SQL_MOBILE_PUBLIC_KEY_TOKEN, new AssemblyVersion(3, 0, 3600, 0), NULL, NULL, s_SQL_PUBLIC_KEY_TOKEN, s_VER_SQL_ASSEMBLYVERSION_STR_L}, // Linq and friends redirect {"system.xml.linq", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_LINQ_ASSEMBLYVERSION_STR_2_L}, {"system.data.DataSetExtensions", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_LINQ_ASSEMBLYVERSION_STR_2_L}, {"System.Core", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_LINQ_ASSEMBLYVERSION_STR_2_L}, {"System.ServiceModel", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_LINQ_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Serialization", s_NETCF_PUBLIC_KEY_TOKEN_3, new AssemblyVersion(3, 5, 0, 0), new AssemblyVersion(3, 9, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_LINQ_ASSEMBLYVERSION_STR_L}, // Portable Library redirects {"mscorlib", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.ComponentModel.Composition", s_SILVERLIGHT_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.ComponentModel.DataAnnotations",s_RIA_SERVICES_KEY_TOKEN, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Core", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Net", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Numerics", s_SILVERLIGHT_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"Microsoft.CSharp", s_SILVERLIGHT_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Runtime.Serialization", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.ServiceModel", s_SILVERLIGHT_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.ServiceModel.Web", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Xml", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Xml.Linq", s_SILVERLIGHT_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Xml.Serialization", s_SILVERLIGHT_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, {"System.Windows", s_SILVERLIGHT_PLATFORM_PUBLICKEY_STR_L, new AssemblyVersion(2, 0, 5, 0), new AssemblyVersion(99, 0, 0, 0), NULL, s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L, TRUE}, }; // Copied from ndp\clr\src\inc\fxretarget.h private static readonly FrameworkAssemblyDictionary s_arFxPolicy = new FrameworkAssemblyDictionary() { {"Accessibility", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"CustomMarshalers", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"ISymWrapper", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.JScript", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic.Compatibility", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic.Compatibility.Data", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualC", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"mscorlib", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Configuration", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Configuration.Install", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.OracleClient", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.SqlXml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Deployment", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Design", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.DirectoryServices", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.DirectoryServices.Protocols", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Drawing.Design", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.EnterpriseServices", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Management", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Messaging", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Remoting", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Serialization.Formatters.Soap", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Security", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceProcess", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Transactions", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Mobile", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.RegularExpressions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Services", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Has to be supported in AppX, because it is in transitive closure of supported assemblies {"System.Windows.Forms", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, #if NDP4_AUTO_VERSION_ROLLFORWARD // Post-Everett FX 2.0 assemblies: {"AspNetMMCExt", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"sysglobl", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Build.Engine", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Build.Framework", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // FX 3.0 assemblies: // Note: we shipped .NET 4.0 with entries in this list for PresentationCFFRasterizer and System.ServiceModel.Install // even though these assemblies did not ship with .NET 4.0. To maintain 100% compatibility with 4.0 we will keep // these in .NET 4.5, but we should remove them in a future SxS version of the Framework. {"PresentationCFFRasterizer", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // See note above {"PresentationCore", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework.Aero", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework.Classic", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework.Luna", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework.Royale", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationUI", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"ReachFramework", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Printing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Speech", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"UIAutomationClient", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"UIAutomationClientsideProviders", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"UIAutomationProvider", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"UIAutomationTypes", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"WindowsBase", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"WindowsFormsIntegration", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"SMDiagnostics", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IdentityModel", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IdentityModel.Selectors", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IO.Log", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Serialization", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Install", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // See note above {"System.ServiceModel.WasHosting", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Workflow.Activities", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Workflow.ComponentModel", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Workflow.Runtime", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Transactions.Bridge", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Transactions.Bridge.Dtc", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // FX 3.5 assemblies: {"System.AddIn", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.AddIn.Contract", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ComponentModel.Composition", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Shipping out-of-band {"System.Core", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.DataSetExtensions", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Linq", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml.Linq", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.DirectoryServices.AccountManagement", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Management.Instrumentation", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Web", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Needed for portable libraries {"System.Web.Extensions", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Extensions.Design", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Presentation", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.WorkflowServices", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Microsoft.Data.Entity.Build.Tasks.dll should not be unified on purpose - it is supported SxS, i.e. both 3.5 and 4.0 versions can be loaded into CLR 4.0+. // {"Microsoft.Data.Entity.Build.Tasks", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L}, // FX 3.5 SP1 assemblies: {"System.ComponentModel.DataAnnotations", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Entity", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Entity.Design", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Services", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Services.Client", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Data.Services.Design", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Abstractions", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.DynamicData", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.DynamicData.Design", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Entity", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Entity.Design", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.Routing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // FX 4.0 assemblies: {"Microsoft.Build", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.CSharp", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Dynamic", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Numerics", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xaml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Microsoft.Workflow.Compiler.exe: // System.Workflow.ComponentModel.dll started to depend on Microsoft.Workflow.Compiler.exe in 4.0 RTM {"Microsoft.Workflow.Compiler", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // FX 4.5 assemblies: {"Microsoft.Activities.Build", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Build.Conversion.v4.0", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Build.Tasks.v4.0", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Build.Utilities.v4.0", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.Internal.Tasks.Dataflow", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualBasic.Activities.Compiler", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VS_ASSEMBLYVERSION_STR_L}, {"Microsoft.VisualC.STLCLR", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_VC_STLCLR_ASSEMBLYVERSION_STR_L}, {"Microsoft.Windows.ApplicationServer.Applications", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationBuildTasks", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework.Aero2", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework.AeroLite", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework-SystemCore", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework-SystemData", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework-SystemDrawing", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework-SystemXml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"PresentationFramework-SystemXmlLinq", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Activities", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Activities.Core.Presentation", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Activities.DurableInstancing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Activities.Presentation", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ComponentModel.Composition.Registration", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Device", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IdentityModel.Services", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IO.Compression", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IO.Compression.FileSystem", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net.Http", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net.Http.WebRequest", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection.Context", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Caching", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.DurableInstancing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.WindowsRuntime", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.WindowsRuntime.UI.Xaml", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Activation", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Activities", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Channels", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Discovery", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Internals", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Routing", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.ServiceMoniker40", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.ApplicationServices", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Has to be supported in AppX, because it is in transitive closure of supported assemblies {"System.Web.DataVisualization", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Web.DataVisualization.Design", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Controls.Ribbon", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms.DataVisualization", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Forms.DataVisualization.Design", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Windows.Input.Manipulations", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xaml.Hosting", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"XamlBuildTask", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"XsdBuildTask", s_SHAREDLIB_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Numerics.Vectors", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // FX 4.5 facade assemblies: {"System.Collections", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Collections.Concurrent", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ComponentModel", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ComponentModel.Annotations", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ComponentModel.EventBasedAsync", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Diagnostics.Contracts", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Diagnostics.Debug", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Diagnostics.Tools", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Diagnostics.Tracing", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Dynamic.Runtime", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Globalization", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.IO", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Linq", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Linq.Expressions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Linq.Parallel", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Linq.Queryable", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net.Http.Rtc", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net.NetworkInformation", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net.Primitives", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Net.Requests", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ObjectModel", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection.Emit", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection.Emit.ILGeneration", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection.Emit.Lightweight", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection.Extensions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Reflection.Primitives", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Resources.ResourceManager", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Extensions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Handles", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.InteropServices", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.InteropServices.WindowsRuntime", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Numerics", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Serialization.Json", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Serialization.Primitives", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Runtime.Serialization.Xml", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Security.Principal", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Duplex", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Http", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.NetTcp", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Primitives", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.ServiceModel.Security", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Text.Encoding", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Text.Encoding.Extensions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Text.RegularExpressions", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Threading", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Threading.Tasks", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Threading.Tasks.Parallel", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Threading.Timer", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml.ReaderWriter", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml.XDocument", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml.XmlSerializer", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, // Manually added facades {"System.Windows", s_MICROSOFT_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, {"System.Xml.Serialization", s_ECMA_PUBLICKEY_STR_L, s_VER_ASSEMBLYVERSION_STR_L}, #endif // NDP4_AUTO_VERSION_ROLLFORWARD }; } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Analyzers/VisualBasic/Analyzers/RemoveUnusedParametersAndValues/VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer.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.Diagnostics Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedParametersAndValues <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend NotInheritable Class VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer Inherits AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer Public Sub New() MyBase.New(unusedValueExpressionStatementOption:=VisualBasicCodeStyleOptions.UnusedValueExpressionStatement, unusedValueAssignmentOption:=VisualBasicCodeStyleOptions.UnusedValueAssignment, LanguageNames.VisualBasic) End Sub Protected Overrides Function IsRecordDeclaration(node As SyntaxNode) As Boolean Return False End Function Protected Overrides Function SupportsDiscard(tree As SyntaxTree) As Boolean Return False End Function Protected Overrides Function MethodHasHandlesClause(method As IMethodSymbol) As Boolean Return method.DeclaringSyntaxReferences().Any(Function(decl) Return TryCast(decl.GetSyntax(), MethodStatementSyntax)?.HandlesClause IsNot Nothing End Function) End Function Protected Overrides Function IsIfConditionalDirective(node As SyntaxNode) As Boolean Return TryCast(node, IfDirectiveTriviaSyntax) IsNot Nothing End Function Protected Overrides Function IsCallStatement(expressionStatement As IExpressionStatementOperation) As Boolean Return TryCast(expressionStatement.Syntax, CallStatementSyntax) IsNot Nothing End Function Protected Overrides Function IsExpressionOfExpressionBody(expressionStatementOperation As IExpressionStatementOperation) As Boolean ' VB does not support expression body Return False End Function Protected Overrides Function GetDefinitionLocationToFade(unusedDefinition As IOperation) As Location Return unusedDefinition.Syntax.GetLocation() 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.Diagnostics Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedParametersAndValues <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend NotInheritable Class VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer Inherits AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer Public Sub New() MyBase.New(unusedValueExpressionStatementOption:=VisualBasicCodeStyleOptions.UnusedValueExpressionStatement, unusedValueAssignmentOption:=VisualBasicCodeStyleOptions.UnusedValueAssignment, LanguageNames.VisualBasic) End Sub Protected Overrides Function IsRecordDeclaration(node As SyntaxNode) As Boolean Return False End Function Protected Overrides Function SupportsDiscard(tree As SyntaxTree) As Boolean Return False End Function Protected Overrides Function MethodHasHandlesClause(method As IMethodSymbol) As Boolean Return method.DeclaringSyntaxReferences().Any(Function(decl) Return TryCast(decl.GetSyntax(), MethodStatementSyntax)?.HandlesClause IsNot Nothing End Function) End Function Protected Overrides Function IsIfConditionalDirective(node As SyntaxNode) As Boolean Return TryCast(node, IfDirectiveTriviaSyntax) IsNot Nothing End Function Protected Overrides Function IsCallStatement(expressionStatement As IExpressionStatementOperation) As Boolean Return TryCast(expressionStatement.Syntax, CallStatementSyntax) IsNot Nothing End Function Protected Overrides Function IsExpressionOfExpressionBody(expressionStatementOperation As IExpressionStatementOperation) As Boolean ' VB does not support expression body Return False End Function Protected Overrides Function GetDefinitionLocationToFade(unusedDefinition As IOperation) As Location Return unusedDefinition.Syntax.GetLocation() End Function End Class End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/Core/Portable/Symbols/Attributes/UnmanagedCallersOnlyAttributeData.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.Linq; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis { internal sealed class UnmanagedCallersOnlyAttributeData { internal static readonly UnmanagedCallersOnlyAttributeData Uninitialized = new UnmanagedCallersOnlyAttributeData(callingConventionTypes: ImmutableHashSet<INamedTypeSymbolInternal>.Empty); internal static readonly UnmanagedCallersOnlyAttributeData AttributePresentDataNotBound = new UnmanagedCallersOnlyAttributeData(callingConventionTypes: ImmutableHashSet<INamedTypeSymbolInternal>.Empty); private static readonly UnmanagedCallersOnlyAttributeData PlatformDefault = new UnmanagedCallersOnlyAttributeData(callingConventionTypes: ImmutableHashSet<INamedTypeSymbolInternal>.Empty); public const string CallConvsPropertyName = "CallConvs"; internal static UnmanagedCallersOnlyAttributeData Create(ImmutableHashSet<INamedTypeSymbolInternal>? callingConventionTypes) => callingConventionTypes switch { null or { IsEmpty: true } => PlatformDefault, _ => new UnmanagedCallersOnlyAttributeData(callingConventionTypes) }; public readonly ImmutableHashSet<INamedTypeSymbolInternal> CallingConventionTypes; private UnmanagedCallersOnlyAttributeData(ImmutableHashSet<INamedTypeSymbolInternal> callingConventionTypes) { CallingConventionTypes = callingConventionTypes; } internal static bool IsCallConvsTypedConstant(string key, bool isField, in TypedConstant value) { return isField && key == CallConvsPropertyName && value.Kind == TypedConstantKind.Array && (value.Values.IsDefaultOrEmpty || value.Values.All(v => v.Kind == TypedConstantKind.Type)); } } }
 // 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.Linq; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis { internal sealed class UnmanagedCallersOnlyAttributeData { internal static readonly UnmanagedCallersOnlyAttributeData Uninitialized = new UnmanagedCallersOnlyAttributeData(callingConventionTypes: ImmutableHashSet<INamedTypeSymbolInternal>.Empty); internal static readonly UnmanagedCallersOnlyAttributeData AttributePresentDataNotBound = new UnmanagedCallersOnlyAttributeData(callingConventionTypes: ImmutableHashSet<INamedTypeSymbolInternal>.Empty); private static readonly UnmanagedCallersOnlyAttributeData PlatformDefault = new UnmanagedCallersOnlyAttributeData(callingConventionTypes: ImmutableHashSet<INamedTypeSymbolInternal>.Empty); public const string CallConvsPropertyName = "CallConvs"; internal static UnmanagedCallersOnlyAttributeData Create(ImmutableHashSet<INamedTypeSymbolInternal>? callingConventionTypes) => callingConventionTypes switch { null or { IsEmpty: true } => PlatformDefault, _ => new UnmanagedCallersOnlyAttributeData(callingConventionTypes) }; public readonly ImmutableHashSet<INamedTypeSymbolInternal> CallingConventionTypes; private UnmanagedCallersOnlyAttributeData(ImmutableHashSet<INamedTypeSymbolInternal> callingConventionTypes) { CallingConventionTypes = callingConventionTypes; } internal static bool IsCallConvsTypedConstant(string key, bool isField, in TypedConstant value) { return isField && key == CallConvsPropertyName && value.Kind == TypedConstantKind.Array && (value.Values.IsDefaultOrEmpty || value.Values.All(v => v.Kind == TypedConstantKind.Type)); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/Core/Portable/EditAndContinue/EditAndContinueCapabilities.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.Immutable; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// The capabilities that the runtime has with respect to edit and continue /// </summary> [Flags] internal enum EditAndContinueCapabilities { None = 0, /// <summary> /// Edit and continue is generally available with the set of capabilities that Mono 6, .NET Framework and .NET 5 have in common. /// </summary> Baseline = 1 << 0, /// <summary> /// Adding a static or instance method to an existing type. /// </summary> AddMethodToExistingType = 1 << 1, /// <summary> /// Adding a static field to an existing type. /// </summary> AddStaticFieldToExistingType = 1 << 2, /// <summary> /// Adding an instance field to an existing type. /// </summary> AddInstanceFieldToExistingType = 1 << 3, /// <summary> /// Creating a new type definition. /// </summary> NewTypeDefinition = 1 << 4, /// <summary> /// Adding, updating and deleting of custom attributes (as distinct from pseudo-custom attributes) /// </summary> ChangeCustomAttributes = 1 << 5, /// <summary> /// Whether the runtime supports updating the Param table, and hence related edits (eg parameter renames) /// </summary> UpdateParameters = 1 << 6, } internal static class EditAndContinueCapabilitiesParser { public static EditAndContinueCapabilities Parse(ImmutableArray<string> capabilities) { var caps = EditAndContinueCapabilities.None; foreach (var capability in capabilities) { caps |= capability switch { "Baseline" => EditAndContinueCapabilities.Baseline, "AddMethodToExistingType" => EditAndContinueCapabilities.AddMethodToExistingType, "AddStaticFieldToExistingType" => EditAndContinueCapabilities.AddStaticFieldToExistingType, "AddInstanceFieldToExistingType" => EditAndContinueCapabilities.AddInstanceFieldToExistingType, "NewTypeDefinition" => EditAndContinueCapabilities.NewTypeDefinition, "ChangeCustomAttributes" => EditAndContinueCapabilities.ChangeCustomAttributes, "UpdateParameters" => EditAndContinueCapabilities.UpdateParameters, // To make it eaiser for runtimes to specify more broad capabilities "AddDefinitionToExistingType" => EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddInstanceFieldToExistingType, _ => EditAndContinueCapabilities.None }; } return caps; } } }
// 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.Immutable; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// The capabilities that the runtime has with respect to edit and continue /// </summary> [Flags] internal enum EditAndContinueCapabilities { None = 0, /// <summary> /// Edit and continue is generally available with the set of capabilities that Mono 6, .NET Framework and .NET 5 have in common. /// </summary> Baseline = 1 << 0, /// <summary> /// Adding a static or instance method to an existing type. /// </summary> AddMethodToExistingType = 1 << 1, /// <summary> /// Adding a static field to an existing type. /// </summary> AddStaticFieldToExistingType = 1 << 2, /// <summary> /// Adding an instance field to an existing type. /// </summary> AddInstanceFieldToExistingType = 1 << 3, /// <summary> /// Creating a new type definition. /// </summary> NewTypeDefinition = 1 << 4, /// <summary> /// Adding, updating and deleting of custom attributes (as distinct from pseudo-custom attributes) /// </summary> ChangeCustomAttributes = 1 << 5, /// <summary> /// Whether the runtime supports updating the Param table, and hence related edits (eg parameter renames) /// </summary> UpdateParameters = 1 << 6, } internal static class EditAndContinueCapabilitiesParser { public static EditAndContinueCapabilities Parse(ImmutableArray<string> capabilities) { var caps = EditAndContinueCapabilities.None; foreach (var capability in capabilities) { caps |= capability switch { "Baseline" => EditAndContinueCapabilities.Baseline, "AddMethodToExistingType" => EditAndContinueCapabilities.AddMethodToExistingType, "AddStaticFieldToExistingType" => EditAndContinueCapabilities.AddStaticFieldToExistingType, "AddInstanceFieldToExistingType" => EditAndContinueCapabilities.AddInstanceFieldToExistingType, "NewTypeDefinition" => EditAndContinueCapabilities.NewTypeDefinition, "ChangeCustomAttributes" => EditAndContinueCapabilities.ChangeCustomAttributes, "UpdateParameters" => EditAndContinueCapabilities.UpdateParameters, // To make it eaiser for runtimes to specify more broad capabilities "AddDefinitionToExistingType" => EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddInstanceFieldToExistingType, _ => EditAndContinueCapabilities.None }; } return caps; } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/VisualBasic/Portable/BoundTree/BoundInterpolatedStringExpression.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 Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundInterpolatedStringExpression Public ReadOnly Property HasInterpolations As Boolean Get ' $"" ' $"TEXT" ' $"TEXT{INTERPOLATION}..." ' $"{INTERPOLATION}" ' $"{INTERPOLATION}TEXT..." ' The parser will never produce two adjacent text elements so in for non-synthetic trees this should only need ' to examine the first two elements at most. For Each item In Contents If item.Kind = BoundKind.Interpolation Then Return True Next Return False End Get End Property Public ReadOnly Property IsEmpty() As Boolean Get Return Contents.Length = 0 End Get End Property #If DEBUG Then Private Sub Validate() Debug.Assert(Type.SpecialType = SpecialType.System_String) Debug.Assert(Not Contents.Where(Function(content) content.Kind <> BoundKind.Interpolation AndAlso content.Kind <> BoundKind.Literal).Any()) End Sub #End If 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 Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundInterpolatedStringExpression Public ReadOnly Property HasInterpolations As Boolean Get ' $"" ' $"TEXT" ' $"TEXT{INTERPOLATION}..." ' $"{INTERPOLATION}" ' $"{INTERPOLATION}TEXT..." ' The parser will never produce two adjacent text elements so in for non-synthetic trees this should only need ' to examine the first two elements at most. For Each item In Contents If item.Kind = BoundKind.Interpolation Then Return True Next Return False End Get End Property Public ReadOnly Property IsEmpty() As Boolean Get Return Contents.Length = 0 End Get End Property #If DEBUG Then Private Sub Validate() Debug.Assert(Type.SpecialType = SpecialType.System_String) Debug.Assert(Not Contents.Where(Function(content) content.Kind <> BoundKind.Interpolation AndAlso content.Kind <> BoundKind.Literal).Any()) End Sub #End If End Class End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/CSharp/Portable/Symbols/MetadataOrSourceAssemblySymbol.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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents source or metadata assembly. /// </summary> internal abstract class MetadataOrSourceAssemblySymbol : NonMissingAssemblySymbol { /// <summary> /// An array of cached Cor types defined in this assembly. /// Lazily filled by GetDeclaredSpecialType method. /// </summary> private NamedTypeSymbol[] _lazySpecialTypes; /// <summary> /// How many Cor types have we cached so far. /// </summary> private int _cachedSpecialTypes; private NativeIntegerTypeSymbol[] _lazyNativeIntegerTypes; /// <summary> /// Lookup declaration for predefined CorLib type in this Assembly. /// </summary> /// <param name="type"></param> /// <returns></returns> internal sealed override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type) { #if DEBUG foreach (var module in this.Modules) { Debug.Assert(module.GetReferencedAssemblies().Length == 0); } #endif if (_lazySpecialTypes == null || (object)_lazySpecialTypes[(int)type] == null) { MetadataTypeName emittedName = MetadataTypeName.FromFullName(type.GetMetadataName(), useCLSCompliantNameArityEncoding: true); ModuleSymbol module = this.Modules[0]; NamedTypeSymbol result = module.LookupTopLevelMetadataType(ref emittedName); if (result.Kind != SymbolKind.ErrorType && result.DeclaredAccessibility != Accessibility.Public) { result = new MissingMetadataTypeSymbol.TopLevel(module, ref emittedName, type); } RegisterDeclaredSpecialType(result); } return _lazySpecialTypes[(int)type]; } /// <summary> /// Register declaration of predefined CorLib type in this Assembly. /// </summary> /// <param name="corType"></param> internal sealed override void RegisterDeclaredSpecialType(NamedTypeSymbol corType) { SpecialType typeId = corType.SpecialType; Debug.Assert(typeId != SpecialType.None); Debug.Assert(ReferenceEquals(corType.ContainingAssembly, this)); Debug.Assert(corType.ContainingModule.Ordinal == 0); Debug.Assert(ReferenceEquals(this.CorLibrary, this)); if (_lazySpecialTypes == null) { Interlocked.CompareExchange(ref _lazySpecialTypes, new NamedTypeSymbol[(int)SpecialType.Count + 1], null); } if ((object)Interlocked.CompareExchange(ref _lazySpecialTypes[(int)typeId], corType, null) != null) { Debug.Assert(ReferenceEquals(corType, _lazySpecialTypes[(int)typeId]) || (corType.Kind == SymbolKind.ErrorType && _lazySpecialTypes[(int)typeId].Kind == SymbolKind.ErrorType)); } else { Interlocked.Increment(ref _cachedSpecialTypes); Debug.Assert(_cachedSpecialTypes > 0 && _cachedSpecialTypes <= (int)SpecialType.Count); } } /// <summary> /// Continue looking for declaration of predefined CorLib type in this Assembly /// while symbols for new type declarations are constructed. /// </summary> internal override bool KeepLookingForDeclaredSpecialTypes { get { return ReferenceEquals(this.CorLibrary, this) && _cachedSpecialTypes < (int)SpecialType.Count; } } private ICollection<string> _lazyTypeNames; private ICollection<string> _lazyNamespaceNames; public override ICollection<string> TypeNames { get { if (_lazyTypeNames == null) { Interlocked.CompareExchange(ref _lazyTypeNames, UnionCollection<string>.Create(this.Modules, m => m.TypeNames), null); } return _lazyTypeNames; } } internal sealed override NamedTypeSymbol GetNativeIntegerType(NamedTypeSymbol underlyingType) { if (_lazyNativeIntegerTypes == null) { Interlocked.CompareExchange(ref _lazyNativeIntegerTypes, new NativeIntegerTypeSymbol[2], null); } int index = underlyingType.SpecialType switch { SpecialType.System_IntPtr => 0, SpecialType.System_UIntPtr => 1, _ => throw ExceptionUtilities.UnexpectedValue(underlyingType.SpecialType), }; if (_lazyNativeIntegerTypes[index] is null) { Interlocked.CompareExchange(ref _lazyNativeIntegerTypes[index], new NativeIntegerTypeSymbol(underlyingType), null); } return _lazyNativeIntegerTypes[index]; } public override ICollection<string> NamespaceNames { get { if (_lazyNamespaceNames == null) { Interlocked.CompareExchange(ref _lazyNamespaceNames, UnionCollection<string>.Create(this.Modules, m => m.NamespaceNames), null); } return _lazyNamespaceNames; } } /// <summary> /// Not yet known value is represented by ErrorTypeSymbol.UnknownResultType /// </summary> private Symbol[] _lazySpecialTypeMembers; /// <summary> /// Lookup member declaration in predefined CorLib type in this Assembly. Only valid if this /// assembly is the Cor Library /// </summary> internal override Symbol GetDeclaredSpecialTypeMember(SpecialMember member) { #if DEBUG foreach (var module in this.Modules) { Debug.Assert(module.GetReferencedAssemblies().Length == 0); } #endif if (_lazySpecialTypeMembers == null || ReferenceEquals(_lazySpecialTypeMembers[(int)member], ErrorTypeSymbol.UnknownResultType)) { if (_lazySpecialTypeMembers == null) { var specialTypeMembers = new Symbol[(int)SpecialMember.Count]; for (int i = 0; i < specialTypeMembers.Length; i++) { specialTypeMembers[i] = ErrorTypeSymbol.UnknownResultType; } Interlocked.CompareExchange(ref _lazySpecialTypeMembers, specialTypeMembers, null); } var descriptor = SpecialMembers.GetDescriptor(member); NamedTypeSymbol type = GetDeclaredSpecialType((SpecialType)descriptor.DeclaringTypeId); Symbol result = null; if (!type.IsErrorType()) { result = CSharpCompilation.GetRuntimeMember(type, descriptor, CSharpCompilation.SpecialMembersSignatureComparer.Instance, accessWithinOpt: null); } Interlocked.CompareExchange(ref _lazySpecialTypeMembers[(int)member], result, ErrorTypeSymbol.UnknownResultType); } return _lazySpecialTypeMembers[(int)member]; } /// <summary> /// Determine whether this assembly has been granted access to <paramref name="potentialGiverOfAccess"></paramref>. /// Assumes that the public key has been determined. The result will be cached. /// </summary> /// <param name="potentialGiverOfAccess"></param> /// <returns></returns> /// <remarks></remarks> protected IVTConclusion MakeFinalIVTDetermination(AssemblySymbol potentialGiverOfAccess) { IVTConclusion result; if (AssembliesToWhichInternalAccessHasBeenDetermined.TryGetValue(potentialGiverOfAccess, out result)) return result; result = IVTConclusion.NoRelationshipClaimed; // returns an empty list if there was no IVT attribute at all for the given name // A name w/o a key is represented by a list with an entry that is empty IEnumerable<ImmutableArray<byte>> publicKeys = potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(this.Name); // We have an easy out here. Suppose the assembly wanting access is // being compiled as a module. You can only strong-name an assembly. So we are going to optimistically // assume that it is going to be compiled into an assembly with a matching strong name, if necessary. if (publicKeys.Any() && this.IsNetModule()) { return IVTConclusion.Match; } // look for one that works, if none work, then return the failure for the last one examined. foreach (var key in publicKeys) { // We pass the public key of this assembly explicitly so PerformIVTCheck does not need // to get it from this.Identity, which would trigger an infinite recursion. result = potentialGiverOfAccess.Identity.PerformIVTCheck(this.PublicKey, key); Debug.Assert(result != IVTConclusion.NoRelationshipClaimed); if (result == IVTConclusion.Match || result == IVTConclusion.OneSignedOneNot) { break; } } AssembliesToWhichInternalAccessHasBeenDetermined.TryAdd(potentialGiverOfAccess, result); return result; } //EDMAURER This is a cache mapping from assemblies which we have analyzed whether or not they grant //internals access to us to the conclusion reached. private ConcurrentDictionary<AssemblySymbol, IVTConclusion> _assembliesToWhichInternalAccessHasBeenAnalyzed; private ConcurrentDictionary<AssemblySymbol, IVTConclusion> AssembliesToWhichInternalAccessHasBeenDetermined { get { if (_assembliesToWhichInternalAccessHasBeenAnalyzed == null) Interlocked.CompareExchange(ref _assembliesToWhichInternalAccessHasBeenAnalyzed, new ConcurrentDictionary<AssemblySymbol, IVTConclusion>(), null); return _assembliesToWhichInternalAccessHasBeenAnalyzed; } } internal virtual bool IsNetModule() => 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.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents source or metadata assembly. /// </summary> internal abstract class MetadataOrSourceAssemblySymbol : NonMissingAssemblySymbol { /// <summary> /// An array of cached Cor types defined in this assembly. /// Lazily filled by GetDeclaredSpecialType method. /// </summary> private NamedTypeSymbol[] _lazySpecialTypes; /// <summary> /// How many Cor types have we cached so far. /// </summary> private int _cachedSpecialTypes; private NativeIntegerTypeSymbol[] _lazyNativeIntegerTypes; /// <summary> /// Lookup declaration for predefined CorLib type in this Assembly. /// </summary> /// <param name="type"></param> /// <returns></returns> internal sealed override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type) { #if DEBUG foreach (var module in this.Modules) { Debug.Assert(module.GetReferencedAssemblies().Length == 0); } #endif if (_lazySpecialTypes == null || (object)_lazySpecialTypes[(int)type] == null) { MetadataTypeName emittedName = MetadataTypeName.FromFullName(type.GetMetadataName(), useCLSCompliantNameArityEncoding: true); ModuleSymbol module = this.Modules[0]; NamedTypeSymbol result = module.LookupTopLevelMetadataType(ref emittedName); if (result.Kind != SymbolKind.ErrorType && result.DeclaredAccessibility != Accessibility.Public) { result = new MissingMetadataTypeSymbol.TopLevel(module, ref emittedName, type); } RegisterDeclaredSpecialType(result); } return _lazySpecialTypes[(int)type]; } /// <summary> /// Register declaration of predefined CorLib type in this Assembly. /// </summary> /// <param name="corType"></param> internal sealed override void RegisterDeclaredSpecialType(NamedTypeSymbol corType) { SpecialType typeId = corType.SpecialType; Debug.Assert(typeId != SpecialType.None); Debug.Assert(ReferenceEquals(corType.ContainingAssembly, this)); Debug.Assert(corType.ContainingModule.Ordinal == 0); Debug.Assert(ReferenceEquals(this.CorLibrary, this)); if (_lazySpecialTypes == null) { Interlocked.CompareExchange(ref _lazySpecialTypes, new NamedTypeSymbol[(int)SpecialType.Count + 1], null); } if ((object)Interlocked.CompareExchange(ref _lazySpecialTypes[(int)typeId], corType, null) != null) { Debug.Assert(ReferenceEquals(corType, _lazySpecialTypes[(int)typeId]) || (corType.Kind == SymbolKind.ErrorType && _lazySpecialTypes[(int)typeId].Kind == SymbolKind.ErrorType)); } else { Interlocked.Increment(ref _cachedSpecialTypes); Debug.Assert(_cachedSpecialTypes > 0 && _cachedSpecialTypes <= (int)SpecialType.Count); } } /// <summary> /// Continue looking for declaration of predefined CorLib type in this Assembly /// while symbols for new type declarations are constructed. /// </summary> internal override bool KeepLookingForDeclaredSpecialTypes { get { return ReferenceEquals(this.CorLibrary, this) && _cachedSpecialTypes < (int)SpecialType.Count; } } private ICollection<string> _lazyTypeNames; private ICollection<string> _lazyNamespaceNames; public override ICollection<string> TypeNames { get { if (_lazyTypeNames == null) { Interlocked.CompareExchange(ref _lazyTypeNames, UnionCollection<string>.Create(this.Modules, m => m.TypeNames), null); } return _lazyTypeNames; } } internal sealed override NamedTypeSymbol GetNativeIntegerType(NamedTypeSymbol underlyingType) { if (_lazyNativeIntegerTypes == null) { Interlocked.CompareExchange(ref _lazyNativeIntegerTypes, new NativeIntegerTypeSymbol[2], null); } int index = underlyingType.SpecialType switch { SpecialType.System_IntPtr => 0, SpecialType.System_UIntPtr => 1, _ => throw ExceptionUtilities.UnexpectedValue(underlyingType.SpecialType), }; if (_lazyNativeIntegerTypes[index] is null) { Interlocked.CompareExchange(ref _lazyNativeIntegerTypes[index], new NativeIntegerTypeSymbol(underlyingType), null); } return _lazyNativeIntegerTypes[index]; } public override ICollection<string> NamespaceNames { get { if (_lazyNamespaceNames == null) { Interlocked.CompareExchange(ref _lazyNamespaceNames, UnionCollection<string>.Create(this.Modules, m => m.NamespaceNames), null); } return _lazyNamespaceNames; } } /// <summary> /// Not yet known value is represented by ErrorTypeSymbol.UnknownResultType /// </summary> private Symbol[] _lazySpecialTypeMembers; /// <summary> /// Lookup member declaration in predefined CorLib type in this Assembly. Only valid if this /// assembly is the Cor Library /// </summary> internal override Symbol GetDeclaredSpecialTypeMember(SpecialMember member) { #if DEBUG foreach (var module in this.Modules) { Debug.Assert(module.GetReferencedAssemblies().Length == 0); } #endif if (_lazySpecialTypeMembers == null || ReferenceEquals(_lazySpecialTypeMembers[(int)member], ErrorTypeSymbol.UnknownResultType)) { if (_lazySpecialTypeMembers == null) { var specialTypeMembers = new Symbol[(int)SpecialMember.Count]; for (int i = 0; i < specialTypeMembers.Length; i++) { specialTypeMembers[i] = ErrorTypeSymbol.UnknownResultType; } Interlocked.CompareExchange(ref _lazySpecialTypeMembers, specialTypeMembers, null); } var descriptor = SpecialMembers.GetDescriptor(member); NamedTypeSymbol type = GetDeclaredSpecialType((SpecialType)descriptor.DeclaringTypeId); Symbol result = null; if (!type.IsErrorType()) { result = CSharpCompilation.GetRuntimeMember(type, descriptor, CSharpCompilation.SpecialMembersSignatureComparer.Instance, accessWithinOpt: null); } Interlocked.CompareExchange(ref _lazySpecialTypeMembers[(int)member], result, ErrorTypeSymbol.UnknownResultType); } return _lazySpecialTypeMembers[(int)member]; } /// <summary> /// Determine whether this assembly has been granted access to <paramref name="potentialGiverOfAccess"></paramref>. /// Assumes that the public key has been determined. The result will be cached. /// </summary> /// <param name="potentialGiverOfAccess"></param> /// <returns></returns> /// <remarks></remarks> protected IVTConclusion MakeFinalIVTDetermination(AssemblySymbol potentialGiverOfAccess) { IVTConclusion result; if (AssembliesToWhichInternalAccessHasBeenDetermined.TryGetValue(potentialGiverOfAccess, out result)) return result; result = IVTConclusion.NoRelationshipClaimed; // returns an empty list if there was no IVT attribute at all for the given name // A name w/o a key is represented by a list with an entry that is empty IEnumerable<ImmutableArray<byte>> publicKeys = potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(this.Name); // We have an easy out here. Suppose the assembly wanting access is // being compiled as a module. You can only strong-name an assembly. So we are going to optimistically // assume that it is going to be compiled into an assembly with a matching strong name, if necessary. if (publicKeys.Any() && this.IsNetModule()) { return IVTConclusion.Match; } // look for one that works, if none work, then return the failure for the last one examined. foreach (var key in publicKeys) { // We pass the public key of this assembly explicitly so PerformIVTCheck does not need // to get it from this.Identity, which would trigger an infinite recursion. result = potentialGiverOfAccess.Identity.PerformIVTCheck(this.PublicKey, key); Debug.Assert(result != IVTConclusion.NoRelationshipClaimed); if (result == IVTConclusion.Match || result == IVTConclusion.OneSignedOneNot) { break; } } AssembliesToWhichInternalAccessHasBeenDetermined.TryAdd(potentialGiverOfAccess, result); return result; } //EDMAURER This is a cache mapping from assemblies which we have analyzed whether or not they grant //internals access to us to the conclusion reached. private ConcurrentDictionary<AssemblySymbol, IVTConclusion> _assembliesToWhichInternalAccessHasBeenAnalyzed; private ConcurrentDictionary<AssemblySymbol, IVTConclusion> AssembliesToWhichInternalAccessHasBeenDetermined { get { if (_assembliesToWhichInternalAccessHasBeenAnalyzed == null) Interlocked.CompareExchange(ref _assembliesToWhichInternalAccessHasBeenAnalyzed, new ConcurrentDictionary<AssemblySymbol, IVTConclusion>(), null); return _assembliesToWhichInternalAccessHasBeenAnalyzed; } } internal virtual bool IsNetModule() => false; } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/Test/Utilities/CSharp/CSharpTestSource.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.Linq; namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { /// <summary> /// Represents the source code used for a C# test. Allows us to have single helpers that enable all the different ways /// we typically provide source in testing. /// </summary> public readonly struct CSharpTestSource { public static CSharpTestSource None => new CSharpTestSource(null); public object Value { get; } private CSharpTestSource(object value) { Value = value; } public SyntaxTree[] GetSyntaxTrees(CSharpParseOptions parseOptions, string sourceFileName = "") { switch (Value) { case string source: return new[] { CSharpTestBase.Parse(source, filename: sourceFileName, parseOptions) }; case string[] sources: Debug.Assert(string.IsNullOrEmpty(sourceFileName)); return CSharpTestBase.Parse(parseOptions, sources); case (string source, string fileName): Debug.Assert(string.IsNullOrEmpty(sourceFileName)); return new[] { CSharpTestBase.Parse(source, fileName, parseOptions) }; case (string Source, string FileName)[] sources: Debug.Assert(string.IsNullOrEmpty(sourceFileName)); return sources.Select(source => CSharpTestBase.Parse(source.Source, source.FileName, parseOptions)).ToArray(); case SyntaxTree tree: Debug.Assert(parseOptions == null); Debug.Assert(string.IsNullOrEmpty(sourceFileName)); return new[] { tree }; case SyntaxTree[] trees: Debug.Assert(parseOptions == null); Debug.Assert(string.IsNullOrEmpty(sourceFileName)); return trees; case CSharpTestSource[] testSources: return testSources.SelectMany(s => s.GetSyntaxTrees(parseOptions, sourceFileName)).ToArray(); case null: return Array.Empty<SyntaxTree>(); default: throw new Exception($"Unexpected value: {Value}"); } } public static implicit operator CSharpTestSource(string source) => new CSharpTestSource(source); public static implicit operator CSharpTestSource(string[] source) => new CSharpTestSource(source); public static implicit operator CSharpTestSource((string Source, string FileName) source) => new CSharpTestSource(source); public static implicit operator CSharpTestSource((string Source, string FileName)[] source) => new CSharpTestSource(source); public static implicit operator CSharpTestSource(SyntaxTree source) => new CSharpTestSource(source); public static implicit operator CSharpTestSource(SyntaxTree[] source) => new CSharpTestSource(source); public static implicit operator CSharpTestSource(List<SyntaxTree> source) => new CSharpTestSource(source.ToArray()); public static implicit operator CSharpTestSource(ImmutableArray<SyntaxTree> source) => new CSharpTestSource(source.ToArray()); public static implicit operator CSharpTestSource(CSharpTestSource[] source) => new CSharpTestSource(source); } }
// 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.Linq; namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { /// <summary> /// Represents the source code used for a C# test. Allows us to have single helpers that enable all the different ways /// we typically provide source in testing. /// </summary> public readonly struct CSharpTestSource { public static CSharpTestSource None => new CSharpTestSource(null); public object Value { get; } private CSharpTestSource(object value) { Value = value; } public SyntaxTree[] GetSyntaxTrees(CSharpParseOptions parseOptions, string sourceFileName = "") { switch (Value) { case string source: return new[] { CSharpTestBase.Parse(source, filename: sourceFileName, parseOptions) }; case string[] sources: Debug.Assert(string.IsNullOrEmpty(sourceFileName)); return CSharpTestBase.Parse(parseOptions, sources); case (string source, string fileName): Debug.Assert(string.IsNullOrEmpty(sourceFileName)); return new[] { CSharpTestBase.Parse(source, fileName, parseOptions) }; case (string Source, string FileName)[] sources: Debug.Assert(string.IsNullOrEmpty(sourceFileName)); return sources.Select(source => CSharpTestBase.Parse(source.Source, source.FileName, parseOptions)).ToArray(); case SyntaxTree tree: Debug.Assert(parseOptions == null); Debug.Assert(string.IsNullOrEmpty(sourceFileName)); return new[] { tree }; case SyntaxTree[] trees: Debug.Assert(parseOptions == null); Debug.Assert(string.IsNullOrEmpty(sourceFileName)); return trees; case CSharpTestSource[] testSources: return testSources.SelectMany(s => s.GetSyntaxTrees(parseOptions, sourceFileName)).ToArray(); case null: return Array.Empty<SyntaxTree>(); default: throw new Exception($"Unexpected value: {Value}"); } } public static implicit operator CSharpTestSource(string source) => new CSharpTestSource(source); public static implicit operator CSharpTestSource(string[] source) => new CSharpTestSource(source); public static implicit operator CSharpTestSource((string Source, string FileName) source) => new CSharpTestSource(source); public static implicit operator CSharpTestSource((string Source, string FileName)[] source) => new CSharpTestSource(source); public static implicit operator CSharpTestSource(SyntaxTree source) => new CSharpTestSource(source); public static implicit operator CSharpTestSource(SyntaxTree[] source) => new CSharpTestSource(source); public static implicit operator CSharpTestSource(List<SyntaxTree> source) => new CSharpTestSource(source.ToArray()); public static implicit operator CSharpTestSource(ImmutableArray<SyntaxTree> source) => new CSharpTestSource(source.ToArray()); public static implicit operator CSharpTestSource(CSharpTestSource[] source) => new CSharpTestSource(source); } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/Core/Portable/AddImport/Remote/AbstractAddImportFeatureService_Remote.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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.SymbolSearch; namespace Microsoft.CodeAnalysis.AddImport { /// <summary> /// Used to supply the OOP server a callback that it can use to search for ReferenceAssemblies or /// nuget packages. We can't necessarily do that search directly in the OOP server as our /// 'SymbolSearchEngine' may actually be running in a *different* process (there is no guarantee /// that all remote work happens in the same process). /// /// This does mean, currently, that when we call over to OOP to do a search, it will bounce /// back to VS, which will then bounce back out to OOP to perform the Nuget/ReferenceAssembly /// portion of the search. Ideally we could keep this all OOP. /// </summary> [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteMissingImportDiscoveryService)), Shared] internal sealed class RemoteMissingImportDiscoveryServiceCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteMissingImportDiscoveryService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteMissingImportDiscoveryServiceCallbackDispatcher() { } private ISymbolSearchService GetService(RemoteServiceCallbackId callbackId) => (ISymbolSearchService)GetCallback(callbackId); public ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(RemoteServiceCallbackId callbackId, string source, string name, int arity, CancellationToken cancellationToken) => GetService(callbackId).FindPackagesWithTypeAsync(source, name, arity, cancellationToken); public ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(RemoteServiceCallbackId callbackId, string source, string name, CancellationToken cancellationToken) => GetService(callbackId).FindPackagesWithAssemblyAsync(source, name, cancellationToken); public ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(RemoteServiceCallbackId callbackId, string name, int arity, CancellationToken cancellationToken) => GetService(callbackId).FindReferenceAssembliesWithTypeAsync(name, arity, 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.SymbolSearch; namespace Microsoft.CodeAnalysis.AddImport { /// <summary> /// Used to supply the OOP server a callback that it can use to search for ReferenceAssemblies or /// nuget packages. We can't necessarily do that search directly in the OOP server as our /// 'SymbolSearchEngine' may actually be running in a *different* process (there is no guarantee /// that all remote work happens in the same process). /// /// This does mean, currently, that when we call over to OOP to do a search, it will bounce /// back to VS, which will then bounce back out to OOP to perform the Nuget/ReferenceAssembly /// portion of the search. Ideally we could keep this all OOP. /// </summary> [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteMissingImportDiscoveryService)), Shared] internal sealed class RemoteMissingImportDiscoveryServiceCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteMissingImportDiscoveryService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteMissingImportDiscoveryServiceCallbackDispatcher() { } private ISymbolSearchService GetService(RemoteServiceCallbackId callbackId) => (ISymbolSearchService)GetCallback(callbackId); public ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(RemoteServiceCallbackId callbackId, string source, string name, int arity, CancellationToken cancellationToken) => GetService(callbackId).FindPackagesWithTypeAsync(source, name, arity, cancellationToken); public ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(RemoteServiceCallbackId callbackId, string source, string name, CancellationToken cancellationToken) => GetService(callbackId).FindPackagesWithAssemblyAsync(source, name, cancellationToken); public ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(RemoteServiceCallbackId callbackId, string name, int arity, CancellationToken cancellationToken) => GetService(callbackId).FindReferenceAssembliesWithTypeAsync(name, arity, cancellationToken); } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/FunctionKeywordRecommender.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.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Function" keyword in member declaration contexts ''' </summary> Friend Class FunctionKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Function", VBFeaturesResources.Declares_the_name_parameters_and_code_that_define_a_Function_procedure_that_is_a_procedure_that_returns_a_value_to_the_calling_code)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, CancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsTypeMemberDeclarationKeywordContext OrElse context.IsInterfaceMemberDeclarationKeywordContext Then Dim modifiers = context.ModifierCollectionFacts If modifiers.OverridableSharedOrPartialKeyword.Kind = SyntaxKind.PartialKeyword Then Return ImmutableArray(Of RecommendedKeyword).Empty End If If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Method Or PossibleDeclarationTypes.IteratorFunction) Then Return s_keywords End If End If If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken If targetToken.IsKindOrHasMatchingText(SyntaxKind.ExitKeyword) AndAlso context.IsInStatementBlockOfKind(SyntaxKind.FunctionBlock, SyntaxKind.MultiLineFunctionLambdaExpression) AndAlso Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then Return s_keywords End If Return ImmutableArray(Of RecommendedKeyword).Empty 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.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Function" keyword in member declaration contexts ''' </summary> Friend Class FunctionKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Function", VBFeaturesResources.Declares_the_name_parameters_and_code_that_define_a_Function_procedure_that_is_a_procedure_that_returns_a_value_to_the_calling_code)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, CancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsTypeMemberDeclarationKeywordContext OrElse context.IsInterfaceMemberDeclarationKeywordContext Then Dim modifiers = context.ModifierCollectionFacts If modifiers.OverridableSharedOrPartialKeyword.Kind = SyntaxKind.PartialKeyword Then Return ImmutableArray(Of RecommendedKeyword).Empty End If If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Method Or PossibleDeclarationTypes.IteratorFunction) Then Return s_keywords End If End If If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken If targetToken.IsKindOrHasMatchingText(SyntaxKind.ExitKeyword) AndAlso context.IsInStatementBlockOfKind(SyntaxKind.FunctionBlock, SyntaxKind.MultiLineFunctionLambdaExpression) AndAlso Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then Return s_keywords End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Scripting/Core/ScriptMetadataResolver.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. #pragma warning disable 436 // The type 'RelativePathResolver' conflicts with imported type using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Scripting.Hosting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting { using static ParameterValidationHelpers; public sealed class ScriptMetadataResolver : MetadataReferenceResolver, IEquatable<ScriptMetadataResolver> { public static ScriptMetadataResolver Default { get; } = new ScriptMetadataResolver( RuntimeMetadataReferenceResolver.CreateCurrentPlatformResolver(ImmutableArray<string>.Empty, baseDirectory: null)); private readonly RuntimeMetadataReferenceResolver _resolver; public ImmutableArray<string> SearchPaths => _resolver.PathResolver.SearchPaths; public string BaseDirectory => _resolver.PathResolver.BaseDirectory; internal ScriptMetadataResolver(RuntimeMetadataReferenceResolver resolver) { _resolver = resolver; } public ScriptMetadataResolver WithSearchPaths(params string[] searchPaths) => WithSearchPaths(searchPaths.AsImmutableOrEmpty()); public ScriptMetadataResolver WithSearchPaths(IEnumerable<string> searchPaths) => WithSearchPaths(searchPaths.AsImmutableOrEmpty()); public ScriptMetadataResolver WithSearchPaths(ImmutableArray<string> searchPaths) { if (SearchPaths == searchPaths) { return this; } return new ScriptMetadataResolver(_resolver.WithRelativePathResolver( _resolver.PathResolver.WithSearchPaths(ToImmutableArrayChecked(searchPaths, nameof(searchPaths))))); } public ScriptMetadataResolver WithBaseDirectory(string? baseDirectory) { if (BaseDirectory == baseDirectory) { return this; } if (baseDirectory != null) { CompilerPathUtilities.RequireAbsolutePath(baseDirectory, nameof(baseDirectory)); } return new ScriptMetadataResolver(_resolver.WithRelativePathResolver( _resolver.PathResolver.WithBaseDirectory(baseDirectory))); } public override bool ResolveMissingAssemblies => _resolver.ResolveMissingAssemblies; public override PortableExecutableReference? ResolveMissingAssembly(MetadataReference definition, AssemblyIdentity referenceIdentity) => _resolver.ResolveMissingAssembly(definition, referenceIdentity); public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string? baseFilePath, MetadataReferenceProperties properties) => _resolver.ResolveReference(reference, baseFilePath, properties); public bool Equals(ScriptMetadataResolver? other) => _resolver.Equals(other); public override bool Equals(object? other) => Equals(other as ScriptMetadataResolver); public override int GetHashCode() => _resolver.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. #pragma warning disable 436 // The type 'RelativePathResolver' conflicts with imported type using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Scripting.Hosting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting { using static ParameterValidationHelpers; public sealed class ScriptMetadataResolver : MetadataReferenceResolver, IEquatable<ScriptMetadataResolver> { public static ScriptMetadataResolver Default { get; } = new ScriptMetadataResolver( RuntimeMetadataReferenceResolver.CreateCurrentPlatformResolver(ImmutableArray<string>.Empty, baseDirectory: null)); private readonly RuntimeMetadataReferenceResolver _resolver; public ImmutableArray<string> SearchPaths => _resolver.PathResolver.SearchPaths; public string BaseDirectory => _resolver.PathResolver.BaseDirectory; internal ScriptMetadataResolver(RuntimeMetadataReferenceResolver resolver) { _resolver = resolver; } public ScriptMetadataResolver WithSearchPaths(params string[] searchPaths) => WithSearchPaths(searchPaths.AsImmutableOrEmpty()); public ScriptMetadataResolver WithSearchPaths(IEnumerable<string> searchPaths) => WithSearchPaths(searchPaths.AsImmutableOrEmpty()); public ScriptMetadataResolver WithSearchPaths(ImmutableArray<string> searchPaths) { if (SearchPaths == searchPaths) { return this; } return new ScriptMetadataResolver(_resolver.WithRelativePathResolver( _resolver.PathResolver.WithSearchPaths(ToImmutableArrayChecked(searchPaths, nameof(searchPaths))))); } public ScriptMetadataResolver WithBaseDirectory(string? baseDirectory) { if (BaseDirectory == baseDirectory) { return this; } if (baseDirectory != null) { CompilerPathUtilities.RequireAbsolutePath(baseDirectory, nameof(baseDirectory)); } return new ScriptMetadataResolver(_resolver.WithRelativePathResolver( _resolver.PathResolver.WithBaseDirectory(baseDirectory))); } public override bool ResolveMissingAssemblies => _resolver.ResolveMissingAssemblies; public override PortableExecutableReference? ResolveMissingAssembly(MetadataReference definition, AssemblyIdentity referenceIdentity) => _resolver.ResolveMissingAssembly(definition, referenceIdentity); public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string? baseFilePath, MetadataReferenceProperties properties) => _resolver.ResolveReference(reference, baseFilePath, properties); public bool Equals(ScriptMetadataResolver? other) => _resolver.Equals(other); public override bool Equals(object? other) => Equals(other as ScriptMetadataResolver); public override int GetHashCode() => _resolver.GetHashCode(); } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/VisualStudio/Core/Def/Implementation/CodeCleanup/AbstractCodeCleanUpFixer.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.Immutable; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Editor.CodeCleanup; using Microsoft.VisualStudio.Language.CodeCleanUp; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using __VSHPROPID8 = Microsoft.VisualStudio.Shell.Interop.__VSHPROPID8; using IVsHierarchyItemManager = Microsoft.VisualStudio.Shell.IVsHierarchyItemManager; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeCleanup { /// <summary> /// Roslyn implementations of <see cref="ICodeCleanUpFixer"/> extend this class. Since other extensions could also /// be implementing the <see cref="ICodeCleanUpFixer"/> interface, this abstract base class allows Roslyn to operate /// on MEF instances of fixers known to be relevant in the context of Roslyn languages. /// </summary> internal abstract class AbstractCodeCleanUpFixer : ICodeCleanUpFixer { protected const string FormatDocumentFixId = nameof(FormatDocumentFixId); protected const string RemoveUnusedImportsFixId = nameof(RemoveUnusedImportsFixId); protected const string SortImportsFixId = nameof(SortImportsFixId); private readonly IThreadingContext _threadingContext; private readonly VisualStudioWorkspaceImpl _workspace; private readonly IVsHierarchyItemManager _vsHierarchyItemManager; protected AbstractCodeCleanUpFixer( IThreadingContext threadingContext, VisualStudioWorkspaceImpl workspace, IVsHierarchyItemManager vsHierarchyItemManager) { _threadingContext = threadingContext; _workspace = workspace; _vsHierarchyItemManager = vsHierarchyItemManager; } public Task<bool> FixAsync(ICodeCleanUpScope scope, ICodeCleanUpExecutionContext context) => scope switch { TextBufferCodeCleanUpScope textBufferScope => FixTextBufferAsync(textBufferScope, context), IVsHierarchyCodeCleanupScope hierarchyContentScope => FixHierarchyContentAsync(hierarchyContentScope, context), _ => Task.FromResult(false), }; private async Task<bool> FixHierarchyContentAsync(IVsHierarchyCodeCleanupScope hierarchyContent, ICodeCleanUpExecutionContext context) { var hierarchy = hierarchyContent.Hierarchy; if (hierarchy == null) { return await FixSolutionAsync(_workspace.CurrentSolution, context).ConfigureAwait(true); } // Map the hierarchy to a ProjectId. For hierarchies mapping to multitargeted projects, we first try to // get the project in the most recent active context, but fall back to the first target framework if no // active context is available. var hierarchyToProjectMap = _workspace.Services.GetRequiredService<IHierarchyItemToProjectIdMap>(); await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(context.OperationContext.UserCancellationToken); ProjectId? projectId = null; if (ErrorHandler.Succeeded(hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext, out var contextProjectNameObject)) && contextProjectNameObject is string contextProjectName) { projectId = _workspace.GetProjectWithHierarchyAndName(hierarchy, contextProjectName)?.Id; } if (projectId is null) { var projectHierarchyItem = _vsHierarchyItemManager.GetHierarchyItem(hierarchyContent.Hierarchy, (uint)VSConstants.VSITEMID.Root); if (!hierarchyToProjectMap.TryGetProjectId(projectHierarchyItem, targetFrameworkMoniker: null, out projectId)) { return false; } } var itemId = hierarchyContent.ItemId; if (itemId == (uint)VSConstants.VSITEMID.Root) { await TaskScheduler.Default; var project = _workspace.CurrentSolution.GetProject(projectId); if (project == null) { return false; } return await FixProjectAsync(project, context).ConfigureAwait(true); } else if (hierarchy.GetCanonicalName(itemId, out var path) == 0) { var attr = File.GetAttributes(path); if (attr.HasFlag(FileAttributes.Directory)) { // directory // TODO: this one will be implemented later // https://github.com/dotnet/roslyn/issues/30165 } else { // Handle code cleanup for a single document await TaskScheduler.Default; var solution = _workspace.CurrentSolution; var documentIds = solution.GetDocumentIdsWithFilePath(path); var documentId = documentIds.FirstOrDefault(id => id.ProjectId == projectId); if (documentId is null) { return false; } return await FixDocumentAsync(solution.GetRequiredDocument(documentId), context).ConfigureAwait(true); } } return false; } private Task<bool> FixSolutionAsync(Solution solution, ICodeCleanUpExecutionContext context) { return FixAsync(solution.Workspace, ApplyFixAsync, context); // Local function Task<Solution> ApplyFixAsync(ProgressTracker progressTracker, CancellationToken cancellationToken) { return FixSolutionAsync(solution, context.EnabledFixIds, progressTracker, cancellationToken); } } private Task<bool> FixProjectAsync(Project project, ICodeCleanUpExecutionContext context) { return FixAsync(project.Solution.Workspace, ApplyFixAsync, context); // Local function async Task<Solution> ApplyFixAsync(ProgressTracker progressTracker, CancellationToken cancellationToken) { var newProject = await FixProjectAsync(project, context.EnabledFixIds, progressTracker, addProgressItemsForDocuments: true, cancellationToken).ConfigureAwait(true); return newProject.Solution; } } private Task<bool> FixDocumentAsync(Document document, ICodeCleanUpExecutionContext context) { return FixAsync(document.Project.Solution.Workspace, ApplyFixAsync, context); // Local function async Task<Solution> ApplyFixAsync(ProgressTracker progressTracker, CancellationToken cancellationToken) { var newDocument = await FixDocumentAsync(document, context.EnabledFixIds, progressTracker, cancellationToken).ConfigureAwait(true); return newDocument.Project.Solution; } } private Task<bool> FixTextBufferAsync(TextBufferCodeCleanUpScope textBufferScope, ICodeCleanUpExecutionContext context) { var buffer = textBufferScope.SubjectBuffer; // Let LSP handle code cleanup in the cloud scenario if (buffer.IsInLspEditorContext()) { return SpecializedTasks.False; } var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return SpecializedTasks.False; } var workspace = buffer.GetWorkspace(); Contract.ThrowIfNull(workspace); return FixAsync(workspace, ApplyFixAsync, context); // Local function async Task<Solution> ApplyFixAsync(ProgressTracker progressTracker, CancellationToken cancellationToken) { var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); Contract.ThrowIfNull(document); var newDoc = await FixDocumentAsync(document, context.EnabledFixIds, progressTracker, cancellationToken).ConfigureAwait(true); return newDoc.Project.Solution; } } private async Task<bool> FixAsync( Workspace workspace, Func<ProgressTracker, CancellationToken, Task<Solution>> applyFixAsync, ICodeCleanUpExecutionContext context) { using (var scope = context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Waiting_for_background_work_to_finish)) { var workspaceStatusService = workspace.Services.GetService<IWorkspaceStatusService>(); if (workspaceStatusService != null) { await workspaceStatusService.WaitUntilFullyLoadedAsync(context.OperationContext.UserCancellationToken).ConfigureAwait(true); } } using (var scope = context.OperationContext.AddScope(allowCancellation: true, description: EditorFeaturesResources.Applying_changes)) { var cancellationToken = context.OperationContext.UserCancellationToken; var progressTracker = new ProgressTracker((description, completed, total) => { if (scope != null) { scope.Description = description; scope.Progress.Report(new VisualStudio.Utilities.ProgressInfo(completed, total)); } }); var solution = await applyFixAsync(progressTracker, cancellationToken).ConfigureAwait(true); await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return workspace.TryApplyChanges(solution, progressTracker); } } private async Task<Solution> FixSolutionAsync( Solution solution, FixIdContainer enabledFixIds, ProgressTracker progressTracker, CancellationToken cancellationToken) { // Prepopulate the solution progress tracker with the total number of documents to process foreach (var projectId in solution.ProjectIds) { var project = solution.GetRequiredProject(projectId); if (!CanCleanupProject(project)) { continue; } progressTracker.AddItems(project.DocumentIds.Count); } foreach (var projectId in solution.ProjectIds) { cancellationToken.ThrowIfCancellationRequested(); var project = solution.GetRequiredProject(projectId); var newProject = await FixProjectAsync(project, enabledFixIds, progressTracker, addProgressItemsForDocuments: false, cancellationToken).ConfigureAwait(false); solution = newProject.Solution; } return solution; } private async Task<Project> FixProjectAsync( Project project, FixIdContainer enabledFixIds, ProgressTracker progressTracker, bool addProgressItemsForDocuments, CancellationToken cancellationToken) { if (!CanCleanupProject(project)) { return project; } if (addProgressItemsForDocuments) { progressTracker.AddItems(project.DocumentIds.Count); } foreach (var documentId in project.DocumentIds) { cancellationToken.ThrowIfCancellationRequested(); var document = project.GetRequiredDocument(documentId); progressTracker.Description = document.Name; // FixDocumentAsync reports progress within a document, but we limit progress reporting for a project // to the current document. var documentProgressTracker = new ProgressTracker(); var fixedDocument = await FixDocumentAsync(document, enabledFixIds, documentProgressTracker, cancellationToken).ConfigureAwait(false); project = fixedDocument.Project; progressTracker.ItemCompleted(); } return project; } private static bool CanCleanupProject(Project project) => project.LanguageServices.GetService<ICodeCleanupService>() != null; private async Task<Document> FixDocumentAsync( Document document, FixIdContainer enabledFixIds, ProgressTracker progressTracker, CancellationToken cancellationToken) { if (document.IsGeneratedCode(cancellationToken)) { return document; } var codeCleanupService = document.GetRequiredLanguageService<ICodeCleanupService>(); var allDiagnostics = codeCleanupService.GetAllDiagnostics(); var enabedDiagnosticSets = ArrayBuilder<DiagnosticSet>.GetInstance(); foreach (var diagnostic in allDiagnostics.Diagnostics) { foreach (var diagnosticId in diagnostic.DiagnosticIds) { if (enabledFixIds.IsFixIdEnabled(diagnosticId)) { enabedDiagnosticSets.Add(diagnostic); break; } } } var isFormatDocumentEnabled = enabledFixIds.IsFixIdEnabled(FormatDocumentFixId); var isRemoveUnusedUsingsEnabled = enabledFixIds.IsFixIdEnabled(RemoveUnusedImportsFixId); var isSortUsingsEnabled = enabledFixIds.IsFixIdEnabled(SortImportsFixId); var enabledDiagnostics = new EnabledDiagnosticOptions( isFormatDocumentEnabled, enabedDiagnosticSets.ToImmutableArray(), new OrganizeUsingsSet(isRemoveUnusedUsingsEnabled, isSortUsingsEnabled)); return await codeCleanupService.CleanupAsync( document, enabledDiagnostics, progressTracker, cancellationToken).ConfigureAwait(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. using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Editor.CodeCleanup; using Microsoft.VisualStudio.Language.CodeCleanUp; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using __VSHPROPID8 = Microsoft.VisualStudio.Shell.Interop.__VSHPROPID8; using IVsHierarchyItemManager = Microsoft.VisualStudio.Shell.IVsHierarchyItemManager; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeCleanup { /// <summary> /// Roslyn implementations of <see cref="ICodeCleanUpFixer"/> extend this class. Since other extensions could also /// be implementing the <see cref="ICodeCleanUpFixer"/> interface, this abstract base class allows Roslyn to operate /// on MEF instances of fixers known to be relevant in the context of Roslyn languages. /// </summary> internal abstract class AbstractCodeCleanUpFixer : ICodeCleanUpFixer { protected const string FormatDocumentFixId = nameof(FormatDocumentFixId); protected const string RemoveUnusedImportsFixId = nameof(RemoveUnusedImportsFixId); protected const string SortImportsFixId = nameof(SortImportsFixId); private readonly IThreadingContext _threadingContext; private readonly VisualStudioWorkspaceImpl _workspace; private readonly IVsHierarchyItemManager _vsHierarchyItemManager; protected AbstractCodeCleanUpFixer( IThreadingContext threadingContext, VisualStudioWorkspaceImpl workspace, IVsHierarchyItemManager vsHierarchyItemManager) { _threadingContext = threadingContext; _workspace = workspace; _vsHierarchyItemManager = vsHierarchyItemManager; } public Task<bool> FixAsync(ICodeCleanUpScope scope, ICodeCleanUpExecutionContext context) => scope switch { TextBufferCodeCleanUpScope textBufferScope => FixTextBufferAsync(textBufferScope, context), IVsHierarchyCodeCleanupScope hierarchyContentScope => FixHierarchyContentAsync(hierarchyContentScope, context), _ => Task.FromResult(false), }; private async Task<bool> FixHierarchyContentAsync(IVsHierarchyCodeCleanupScope hierarchyContent, ICodeCleanUpExecutionContext context) { var hierarchy = hierarchyContent.Hierarchy; if (hierarchy == null) { return await FixSolutionAsync(_workspace.CurrentSolution, context).ConfigureAwait(true); } // Map the hierarchy to a ProjectId. For hierarchies mapping to multitargeted projects, we first try to // get the project in the most recent active context, but fall back to the first target framework if no // active context is available. var hierarchyToProjectMap = _workspace.Services.GetRequiredService<IHierarchyItemToProjectIdMap>(); await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(context.OperationContext.UserCancellationToken); ProjectId? projectId = null; if (ErrorHandler.Succeeded(hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext, out var contextProjectNameObject)) && contextProjectNameObject is string contextProjectName) { projectId = _workspace.GetProjectWithHierarchyAndName(hierarchy, contextProjectName)?.Id; } if (projectId is null) { var projectHierarchyItem = _vsHierarchyItemManager.GetHierarchyItem(hierarchyContent.Hierarchy, (uint)VSConstants.VSITEMID.Root); if (!hierarchyToProjectMap.TryGetProjectId(projectHierarchyItem, targetFrameworkMoniker: null, out projectId)) { return false; } } var itemId = hierarchyContent.ItemId; if (itemId == (uint)VSConstants.VSITEMID.Root) { await TaskScheduler.Default; var project = _workspace.CurrentSolution.GetProject(projectId); if (project == null) { return false; } return await FixProjectAsync(project, context).ConfigureAwait(true); } else if (hierarchy.GetCanonicalName(itemId, out var path) == 0) { var attr = File.GetAttributes(path); if (attr.HasFlag(FileAttributes.Directory)) { // directory // TODO: this one will be implemented later // https://github.com/dotnet/roslyn/issues/30165 } else { // Handle code cleanup for a single document await TaskScheduler.Default; var solution = _workspace.CurrentSolution; var documentIds = solution.GetDocumentIdsWithFilePath(path); var documentId = documentIds.FirstOrDefault(id => id.ProjectId == projectId); if (documentId is null) { return false; } return await FixDocumentAsync(solution.GetRequiredDocument(documentId), context).ConfigureAwait(true); } } return false; } private Task<bool> FixSolutionAsync(Solution solution, ICodeCleanUpExecutionContext context) { return FixAsync(solution.Workspace, ApplyFixAsync, context); // Local function Task<Solution> ApplyFixAsync(ProgressTracker progressTracker, CancellationToken cancellationToken) { return FixSolutionAsync(solution, context.EnabledFixIds, progressTracker, cancellationToken); } } private Task<bool> FixProjectAsync(Project project, ICodeCleanUpExecutionContext context) { return FixAsync(project.Solution.Workspace, ApplyFixAsync, context); // Local function async Task<Solution> ApplyFixAsync(ProgressTracker progressTracker, CancellationToken cancellationToken) { var newProject = await FixProjectAsync(project, context.EnabledFixIds, progressTracker, addProgressItemsForDocuments: true, cancellationToken).ConfigureAwait(true); return newProject.Solution; } } private Task<bool> FixDocumentAsync(Document document, ICodeCleanUpExecutionContext context) { return FixAsync(document.Project.Solution.Workspace, ApplyFixAsync, context); // Local function async Task<Solution> ApplyFixAsync(ProgressTracker progressTracker, CancellationToken cancellationToken) { var newDocument = await FixDocumentAsync(document, context.EnabledFixIds, progressTracker, cancellationToken).ConfigureAwait(true); return newDocument.Project.Solution; } } private Task<bool> FixTextBufferAsync(TextBufferCodeCleanUpScope textBufferScope, ICodeCleanUpExecutionContext context) { var buffer = textBufferScope.SubjectBuffer; // Let LSP handle code cleanup in the cloud scenario if (buffer.IsInLspEditorContext()) { return SpecializedTasks.False; } var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return SpecializedTasks.False; } var workspace = buffer.GetWorkspace(); Contract.ThrowIfNull(workspace); return FixAsync(workspace, ApplyFixAsync, context); // Local function async Task<Solution> ApplyFixAsync(ProgressTracker progressTracker, CancellationToken cancellationToken) { var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); Contract.ThrowIfNull(document); var newDoc = await FixDocumentAsync(document, context.EnabledFixIds, progressTracker, cancellationToken).ConfigureAwait(true); return newDoc.Project.Solution; } } private async Task<bool> FixAsync( Workspace workspace, Func<ProgressTracker, CancellationToken, Task<Solution>> applyFixAsync, ICodeCleanUpExecutionContext context) { using (var scope = context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Waiting_for_background_work_to_finish)) { var workspaceStatusService = workspace.Services.GetService<IWorkspaceStatusService>(); if (workspaceStatusService != null) { await workspaceStatusService.WaitUntilFullyLoadedAsync(context.OperationContext.UserCancellationToken).ConfigureAwait(true); } } using (var scope = context.OperationContext.AddScope(allowCancellation: true, description: EditorFeaturesResources.Applying_changes)) { var cancellationToken = context.OperationContext.UserCancellationToken; var progressTracker = new ProgressTracker((description, completed, total) => { if (scope != null) { scope.Description = description; scope.Progress.Report(new VisualStudio.Utilities.ProgressInfo(completed, total)); } }); var solution = await applyFixAsync(progressTracker, cancellationToken).ConfigureAwait(true); await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return workspace.TryApplyChanges(solution, progressTracker); } } private async Task<Solution> FixSolutionAsync( Solution solution, FixIdContainer enabledFixIds, ProgressTracker progressTracker, CancellationToken cancellationToken) { // Prepopulate the solution progress tracker with the total number of documents to process foreach (var projectId in solution.ProjectIds) { var project = solution.GetRequiredProject(projectId); if (!CanCleanupProject(project)) { continue; } progressTracker.AddItems(project.DocumentIds.Count); } foreach (var projectId in solution.ProjectIds) { cancellationToken.ThrowIfCancellationRequested(); var project = solution.GetRequiredProject(projectId); var newProject = await FixProjectAsync(project, enabledFixIds, progressTracker, addProgressItemsForDocuments: false, cancellationToken).ConfigureAwait(false); solution = newProject.Solution; } return solution; } private async Task<Project> FixProjectAsync( Project project, FixIdContainer enabledFixIds, ProgressTracker progressTracker, bool addProgressItemsForDocuments, CancellationToken cancellationToken) { if (!CanCleanupProject(project)) { return project; } if (addProgressItemsForDocuments) { progressTracker.AddItems(project.DocumentIds.Count); } foreach (var documentId in project.DocumentIds) { cancellationToken.ThrowIfCancellationRequested(); var document = project.GetRequiredDocument(documentId); progressTracker.Description = document.Name; // FixDocumentAsync reports progress within a document, but we limit progress reporting for a project // to the current document. var documentProgressTracker = new ProgressTracker(); var fixedDocument = await FixDocumentAsync(document, enabledFixIds, documentProgressTracker, cancellationToken).ConfigureAwait(false); project = fixedDocument.Project; progressTracker.ItemCompleted(); } return project; } private static bool CanCleanupProject(Project project) => project.LanguageServices.GetService<ICodeCleanupService>() != null; private async Task<Document> FixDocumentAsync( Document document, FixIdContainer enabledFixIds, ProgressTracker progressTracker, CancellationToken cancellationToken) { if (document.IsGeneratedCode(cancellationToken)) { return document; } var codeCleanupService = document.GetRequiredLanguageService<ICodeCleanupService>(); var allDiagnostics = codeCleanupService.GetAllDiagnostics(); var enabedDiagnosticSets = ArrayBuilder<DiagnosticSet>.GetInstance(); foreach (var diagnostic in allDiagnostics.Diagnostics) { foreach (var diagnosticId in diagnostic.DiagnosticIds) { if (enabledFixIds.IsFixIdEnabled(diagnosticId)) { enabedDiagnosticSets.Add(diagnostic); break; } } } var isFormatDocumentEnabled = enabledFixIds.IsFixIdEnabled(FormatDocumentFixId); var isRemoveUnusedUsingsEnabled = enabledFixIds.IsFixIdEnabled(RemoveUnusedImportsFixId); var isSortUsingsEnabled = enabledFixIds.IsFixIdEnabled(SortImportsFixId); var enabledDiagnostics = new EnabledDiagnosticOptions( isFormatDocumentEnabled, enabedDiagnosticSets.ToImmutableArray(), new OrganizeUsingsSet(isRemoveUnusedUsingsEnabled, isSortUsingsEnabled)); return await codeCleanupService.CleanupAsync( document, enabledDiagnostics, progressTracker, cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/RecommendationHelpers.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.CompilerServices Imports System.Text Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders Friend Module RecommendationHelpers Friend Function IsOnErrorStatement(node As SyntaxNode) As Boolean Return TypeOf node Is OnErrorGoToStatementSyntax OrElse TypeOf node Is OnErrorResumeNextStatementSyntax End Function ''' <summary> ''' Returns the parent of the node given. node may be null, which will cause this function to return null. ''' </summary> <Extension()> Friend Function GetParentOrNull(node As SyntaxNode) As SyntaxNode Return If(node Is Nothing, Nothing, node.Parent) End Function <Extension()> Friend Function IsFollowingCompleteAsNewClause(token As SyntaxToken) As Boolean Dim asNewClause = token.GetAncestor(Of AsNewClauseSyntax)() If asNewClause Is Nothing Then Return False End If Dim lastToken As SyntaxToken Select Case asNewClause.NewExpression.Kind Case SyntaxKind.ObjectCreationExpression Dim objectCreation = DirectCast(asNewClause.NewExpression, ObjectCreationExpressionSyntax) lastToken = If(objectCreation.ArgumentList IsNot Nothing, objectCreation.ArgumentList.CloseParenToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case SyntaxKind.AnonymousObjectCreationExpression Dim anonymousObjectCreation = DirectCast(asNewClause.NewExpression, AnonymousObjectCreationExpressionSyntax) lastToken = If(anonymousObjectCreation.Initializer IsNot Nothing, anonymousObjectCreation.Initializer.CloseBraceToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case SyntaxKind.ArrayCreationExpression Dim arrayCreation = DirectCast(asNewClause.NewExpression, ArrayCreationExpressionSyntax) lastToken = If(arrayCreation.Initializer IsNot Nothing, arrayCreation.Initializer.CloseBraceToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case Else Throw ExceptionUtilities.UnexpectedValue(asNewClause.NewExpression.Kind) End Select Return token = lastToken End Function <Extension()> Private Function IsLastTokenOfObjectCreation(token As SyntaxToken, objectCreation As ObjectCreationExpressionSyntax) As Boolean If objectCreation Is Nothing Then Return False End If Dim lastToken = If(objectCreation.ArgumentList IsNot Nothing, objectCreation.ArgumentList.CloseParenToken, objectCreation.Type.GetLastToken(includeZeroWidth:=True)) Return token = lastToken End Function <Extension()> Friend Function IsFollowingCompleteObjectCreationInitializer(token As SyntaxToken) As Boolean Dim variableDeclarator = token.GetAncestor(Of VariableDeclaratorSyntax)() If variableDeclarator Is Nothing Then Return False End If Dim objectCreation = token.GetAncestors(Of ObjectCreationExpressionSyntax)() _ .Where(Function(oc) oc.Parent IsNot Nothing AndAlso oc.Parent.Kind <> SyntaxKind.AsNewClause AndAlso variableDeclarator.Initializer IsNot Nothing AndAlso variableDeclarator.Initializer.Value Is oc) _ .FirstOrDefault() Return token.IsLastTokenOfObjectCreation(objectCreation) End Function <Extension()> Friend Function IsFollowingCompleteObjectCreation(token As SyntaxToken) As Boolean Dim objectCreation = token.GetAncestor(Of ObjectCreationExpressionSyntax)() Return token.IsLastTokenOfObjectCreation(objectCreation) End Function <Extension()> Friend Function LastJoinKey(collection As SeparatedSyntaxList(Of JoinConditionSyntax)) As ExpressionSyntax Dim lastJoinCondition = collection.LastOrDefault() If lastJoinCondition IsNot Nothing Then Return lastJoinCondition.Right Else Return Nothing End If End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As IdentifierNameSyntax) As Boolean Return _ identifierSyntax IsNot Nothing AndAlso token = identifierSyntax.Identifier AndAlso identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As ModifiedIdentifierSyntax) As Boolean Return _ identifierSyntax IsNot Nothing AndAlso token = identifierSyntax.Identifier AndAlso identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, node As SyntaxNode) As Boolean If node Is Nothing Then Return False End If Dim identifierName = TryCast(node, IdentifierNameSyntax) If token.IsFromIdentifierNode(identifierName) Then Return True End If Dim modifiedIdentifierName = TryCast(node, ModifiedIdentifierSyntax) If token.IsFromIdentifierNode(modifiedIdentifierName) Then Return True End If Return False End Function <Extension()> Friend Function IsFromIdentifierNode(Of TParent As SyntaxNode)(token As SyntaxToken, identifierNodeSelector As Func(Of TParent, SyntaxNode)) As Boolean Dim ancestor = token.GetAncestor(Of TParent)() If ancestor Is Nothing Then Return False End If Return token.IsFromIdentifierNode(identifierNodeSelector(ancestor)) End Function Friend Function CreateRecommendedKeywordForIntrinsicOperator(kind As SyntaxKind, firstLine As String, glyph As Glyph, intrinsicOperator As AbstractIntrinsicOperatorDocumentation, Optional semanticModel As SemanticModel = Nothing, Optional position As Integer = -1) As RecommendedKeyword Return New RecommendedKeyword(SyntaxFacts.GetText(kind), glyph, Function(c) Dim stringBuilder As New StringBuilder stringBuilder.AppendLine(firstLine) stringBuilder.AppendLine(intrinsicOperator.DocumentationText) Dim appendParts = Sub(parts As IEnumerable(Of SymbolDisplayPart)) For Each part In parts stringBuilder.Append(part.ToString()) Next End Sub appendParts(intrinsicOperator.PrefixParts) For i = 0 To intrinsicOperator.ParameterCount - 1 If i <> 0 Then stringBuilder.Append(", ") End If appendParts(intrinsicOperator.GetParameterDisplayParts(i)) Next appendParts(intrinsicOperator.GetSuffix(semanticModel, position, Nothing, c)) Return stringBuilder.ToString().ToSymbolDisplayParts() End Function, isIntrinsic:=True) 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 System.Runtime.CompilerServices Imports System.Text Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders Friend Module RecommendationHelpers Friend Function IsOnErrorStatement(node As SyntaxNode) As Boolean Return TypeOf node Is OnErrorGoToStatementSyntax OrElse TypeOf node Is OnErrorResumeNextStatementSyntax End Function ''' <summary> ''' Returns the parent of the node given. node may be null, which will cause this function to return null. ''' </summary> <Extension()> Friend Function GetParentOrNull(node As SyntaxNode) As SyntaxNode Return If(node Is Nothing, Nothing, node.Parent) End Function <Extension()> Friend Function IsFollowingCompleteAsNewClause(token As SyntaxToken) As Boolean Dim asNewClause = token.GetAncestor(Of AsNewClauseSyntax)() If asNewClause Is Nothing Then Return False End If Dim lastToken As SyntaxToken Select Case asNewClause.NewExpression.Kind Case SyntaxKind.ObjectCreationExpression Dim objectCreation = DirectCast(asNewClause.NewExpression, ObjectCreationExpressionSyntax) lastToken = If(objectCreation.ArgumentList IsNot Nothing, objectCreation.ArgumentList.CloseParenToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case SyntaxKind.AnonymousObjectCreationExpression Dim anonymousObjectCreation = DirectCast(asNewClause.NewExpression, AnonymousObjectCreationExpressionSyntax) lastToken = If(anonymousObjectCreation.Initializer IsNot Nothing, anonymousObjectCreation.Initializer.CloseBraceToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case SyntaxKind.ArrayCreationExpression Dim arrayCreation = DirectCast(asNewClause.NewExpression, ArrayCreationExpressionSyntax) lastToken = If(arrayCreation.Initializer IsNot Nothing, arrayCreation.Initializer.CloseBraceToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case Else Throw ExceptionUtilities.UnexpectedValue(asNewClause.NewExpression.Kind) End Select Return token = lastToken End Function <Extension()> Private Function IsLastTokenOfObjectCreation(token As SyntaxToken, objectCreation As ObjectCreationExpressionSyntax) As Boolean If objectCreation Is Nothing Then Return False End If Dim lastToken = If(objectCreation.ArgumentList IsNot Nothing, objectCreation.ArgumentList.CloseParenToken, objectCreation.Type.GetLastToken(includeZeroWidth:=True)) Return token = lastToken End Function <Extension()> Friend Function IsFollowingCompleteObjectCreationInitializer(token As SyntaxToken) As Boolean Dim variableDeclarator = token.GetAncestor(Of VariableDeclaratorSyntax)() If variableDeclarator Is Nothing Then Return False End If Dim objectCreation = token.GetAncestors(Of ObjectCreationExpressionSyntax)() _ .Where(Function(oc) oc.Parent IsNot Nothing AndAlso oc.Parent.Kind <> SyntaxKind.AsNewClause AndAlso variableDeclarator.Initializer IsNot Nothing AndAlso variableDeclarator.Initializer.Value Is oc) _ .FirstOrDefault() Return token.IsLastTokenOfObjectCreation(objectCreation) End Function <Extension()> Friend Function IsFollowingCompleteObjectCreation(token As SyntaxToken) As Boolean Dim objectCreation = token.GetAncestor(Of ObjectCreationExpressionSyntax)() Return token.IsLastTokenOfObjectCreation(objectCreation) End Function <Extension()> Friend Function LastJoinKey(collection As SeparatedSyntaxList(Of JoinConditionSyntax)) As ExpressionSyntax Dim lastJoinCondition = collection.LastOrDefault() If lastJoinCondition IsNot Nothing Then Return lastJoinCondition.Right Else Return Nothing End If End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As IdentifierNameSyntax) As Boolean Return _ identifierSyntax IsNot Nothing AndAlso token = identifierSyntax.Identifier AndAlso identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As ModifiedIdentifierSyntax) As Boolean Return _ identifierSyntax IsNot Nothing AndAlso token = identifierSyntax.Identifier AndAlso identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, node As SyntaxNode) As Boolean If node Is Nothing Then Return False End If Dim identifierName = TryCast(node, IdentifierNameSyntax) If token.IsFromIdentifierNode(identifierName) Then Return True End If Dim modifiedIdentifierName = TryCast(node, ModifiedIdentifierSyntax) If token.IsFromIdentifierNode(modifiedIdentifierName) Then Return True End If Return False End Function <Extension()> Friend Function IsFromIdentifierNode(Of TParent As SyntaxNode)(token As SyntaxToken, identifierNodeSelector As Func(Of TParent, SyntaxNode)) As Boolean Dim ancestor = token.GetAncestor(Of TParent)() If ancestor Is Nothing Then Return False End If Return token.IsFromIdentifierNode(identifierNodeSelector(ancestor)) End Function Friend Function CreateRecommendedKeywordForIntrinsicOperator(kind As SyntaxKind, firstLine As String, glyph As Glyph, intrinsicOperator As AbstractIntrinsicOperatorDocumentation, Optional semanticModel As SemanticModel = Nothing, Optional position As Integer = -1) As RecommendedKeyword Return New RecommendedKeyword(SyntaxFacts.GetText(kind), glyph, Function(c) Dim stringBuilder As New StringBuilder stringBuilder.AppendLine(firstLine) stringBuilder.AppendLine(intrinsicOperator.DocumentationText) Dim appendParts = Sub(parts As IEnumerable(Of SymbolDisplayPart)) For Each part In parts stringBuilder.Append(part.ToString()) Next End Sub appendParts(intrinsicOperator.PrefixParts) For i = 0 To intrinsicOperator.ParameterCount - 1 If i <> 0 Then stringBuilder.Append(", ") End If appendParts(intrinsicOperator.GetParameterDisplayParts(i)) Next appendParts(intrinsicOperator.GetSuffix(semanticModel, position, Nothing, c)) Return stringBuilder.ToString().ToSymbolDisplayParts() End Function, isIntrinsic:=True) End Function End Module End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/CapturedSymbol.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 Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class CapturedSymbolReplacement { public readonly bool IsReusable; public CapturedSymbolReplacement(bool isReusable) { this.IsReusable = isReusable; } /// <summary> /// Rewrite the replacement expression for the hoisted local so all synthesized field are accessed as members /// of the appropriate frame. /// </summary> public abstract BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame); } internal sealed class CapturedToFrameSymbolReplacement : CapturedSymbolReplacement { public readonly LambdaCapturedVariable HoistedField; public CapturedToFrameSymbolReplacement(LambdaCapturedVariable hoistedField, bool isReusable) : base(isReusable) { this.HoistedField = hoistedField; } public override BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame) { var frame = makeFrame(this.HoistedField.ContainingType); var field = this.HoistedField.AsMember((NamedTypeSymbol)frame.Type); return new BoundFieldAccess(node, frame, field, constantValueOpt: null); } } internal sealed class CapturedToStateMachineFieldReplacement : CapturedSymbolReplacement { public readonly StateMachineFieldSymbol HoistedField; public CapturedToStateMachineFieldReplacement(StateMachineFieldSymbol hoistedField, bool isReusable) : base(isReusable) { this.HoistedField = hoistedField; } public override BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame) { var frame = makeFrame(this.HoistedField.ContainingType); var field = this.HoistedField.AsMember((NamedTypeSymbol)frame.Type); return new BoundFieldAccess(node, frame, field, constantValueOpt: null); } } internal sealed class CapturedToExpressionSymbolReplacement : CapturedSymbolReplacement { private readonly BoundExpression _replacement; public readonly ImmutableArray<StateMachineFieldSymbol> HoistedFields; public CapturedToExpressionSymbolReplacement(BoundExpression replacement, ImmutableArray<StateMachineFieldSymbol> hoistedFields, bool isReusable) : base(isReusable) { _replacement = replacement; this.HoistedFields = hoistedFields; } public override BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame) { // By returning the same replacement each time, it is possible we // are constructing a DAG instead of a tree for the translation. // Because the bound trees are immutable that is usually harmless. return _replacement; } } }
// 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 Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class CapturedSymbolReplacement { public readonly bool IsReusable; public CapturedSymbolReplacement(bool isReusable) { this.IsReusable = isReusable; } /// <summary> /// Rewrite the replacement expression for the hoisted local so all synthesized field are accessed as members /// of the appropriate frame. /// </summary> public abstract BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame); } internal sealed class CapturedToFrameSymbolReplacement : CapturedSymbolReplacement { public readonly LambdaCapturedVariable HoistedField; public CapturedToFrameSymbolReplacement(LambdaCapturedVariable hoistedField, bool isReusable) : base(isReusable) { this.HoistedField = hoistedField; } public override BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame) { var frame = makeFrame(this.HoistedField.ContainingType); var field = this.HoistedField.AsMember((NamedTypeSymbol)frame.Type); return new BoundFieldAccess(node, frame, field, constantValueOpt: null); } } internal sealed class CapturedToStateMachineFieldReplacement : CapturedSymbolReplacement { public readonly StateMachineFieldSymbol HoistedField; public CapturedToStateMachineFieldReplacement(StateMachineFieldSymbol hoistedField, bool isReusable) : base(isReusable) { this.HoistedField = hoistedField; } public override BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame) { var frame = makeFrame(this.HoistedField.ContainingType); var field = this.HoistedField.AsMember((NamedTypeSymbol)frame.Type); return new BoundFieldAccess(node, frame, field, constantValueOpt: null); } } internal sealed class CapturedToExpressionSymbolReplacement : CapturedSymbolReplacement { private readonly BoundExpression _replacement; public readonly ImmutableArray<StateMachineFieldSymbol> HoistedFields; public CapturedToExpressionSymbolReplacement(BoundExpression replacement, ImmutableArray<StateMachineFieldSymbol> hoistedFields, bool isReusable) : base(isReusable) { _replacement = replacement; this.HoistedFields = hoistedFields; } public override BoundExpression Replacement(SyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame) { // By returning the same replacement each time, it is possible we // are constructing a DAG instead of a tree for the translation. // Because the bound trees are immutable that is usually harmless. return _replacement; } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/EditorFeatures/VisualBasicTest/IntroduceUsingStatement/IntroduceUsingStatementTests.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.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.IntroduceUsingStatement Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.IntroduceUsingStatement <Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceUsingStatement)> Public NotInheritable Class IntroduceUsingStatementTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(ByVal workspace As Workspace, ByVal parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicIntroduceUsingStatementCodeRefactoringProvider End Function <Theory> <InlineData("D[||]im name = disposable")> <InlineData("Dim[||] name = disposable")> <InlineData("Dim [||]name = disposable")> <InlineData("Dim na[||]me = disposable")> <InlineData("Dim name[||] = disposable")> <InlineData("Dim name [||]= disposable")> <InlineData("Dim name =[||] disposable")> <InlineData("Dim name = [||]disposable")> <InlineData("[|Dim name = disposable|]")> <InlineData("Dim name = disposable[||]")> <InlineData("Dim name = disposable[||]")> Public Async Function RefactoringIsAvailableForSelection(ByVal declaration As String) As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) " & declaration & " End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForVerticalSelection() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) [| " & " Dim name = disposable |] End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtStartOfStatementWithPrecedingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable [||]Dim name = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtStartOfLineWithPrecedingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable [||] Dim name = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtEndOfStatementWithFollowingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim name = disposable[||] Dim ignore = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using Dim ignore = disposable End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtEndOfLineWithFollowingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim name = disposable [||] Dim ignore = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using Dim ignore = disposable End Sub End Class") End Function <Theory> <InlineData("Dim name = d[||]isposable")> <InlineData("Dim name = disposabl[||]e")> <InlineData("Dim name=[|disposable|]")> Public Async Function RefactoringIsNotAvailableForSelection(ByVal declaration As String) As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) " & declaration & " End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableForDeclarationMissingInitializerExpression() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim name As System.IDisposable =[||] End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableForUsingStatementDeclaration() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Using [||]name = disposable End Using End Sub End Class") End Function <Theory> <InlineData("[||]Dim x = disposable, y = disposable")> <InlineData("Dim [||]x = disposable, y = disposable")> <InlineData("Dim x = disposable, [||]y = disposable")> <InlineData("Dim x = disposable, y = disposable[||]")> Public Async Function RefactoringIsNotAvailableForMultiVariableDeclaration(ByVal declaration As String) As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) " & declaration & " End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForConstrainedGenericTypeParameter() As Task Await TestInRegularAndScriptAsync("Class C(Of T As System.IDisposable) Sub M(disposable As T) Dim x = disposable[||] End Sub End Class", "Class C(Of T As System.IDisposable) Sub M(disposable As T) Using x = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableForUnconstrainedGenericTypeParameter() As Task Await TestMissingAsync("Class C(Of T) Sub M(disposable as T) Dim x = disposable[||] End Sub End Class") End Function <Fact> Public Async Function LeadingCommentTriviaIsPlacedOnUsingStatement() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) ' Comment Dim x = disposable[||] End Sub End Class", "Class C Sub M(disposable As System.IDisposable) ' Comment Using x = disposable End Using End Sub End Class") End Function <Fact> Public Async Function CommentOnTheSameLineStaysOnTheSameLine() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim x = disposable[||] ' Comment End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using x = disposable ' Comment End Using End Sub End Class") End Function <Fact> Public Async Function TrailingCommentTriviaOnNextLineGoesAfterBlock() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim x = disposable[||] ' Comment End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using x = disposable End Using ' Comment End Sub End Class") End Function <Fact> Public Async Function ValidPreprocessorStaysValid() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) #If True Then Dim x = disposable[||] #End If End Sub End Class", "Class C Sub M(disposable As System.IDisposable) #If True Then Using x = disposable End Using #End If End Sub End Class") End Function <Fact> Public Async Function InvalidPreprocessorStaysInvalid() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) #If True Then Dim x = disposable[||] #End If Dim discard = x End Sub End Class", "Class C Sub M(disposable As System.IDisposable) #If True Then Using x = disposable #End If Dim discard = x End Using End Sub End Class") End Function <Fact> Public Async Function StatementsAreSurroundedByMinimalScope() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) M(null) Dim x = disposable[||] M(null) M(x) M(null) End Sub End Class", "Class C Sub M(disposable As System.IDisposable) M(null) Using x = disposable M(null) M(x) End Using M(null) End Sub End Class") End Function <Fact> Public Async Function CommentsAreSurroundedExceptLinesFollowingLastUsage() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim x = disposable[||] ' A M(x) ' B ' C End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using x = disposable ' A M(x) ' B End Using ' C End Sub End Class") End Function <Fact> Public Async Function WorksInSelectCases() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Select Case disposable Case Else Dim x = disposable[||] M(x) End Select End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Select Case disposable Case Else Using x = disposable M(x) End Using End Select End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableOnSingleLineIfStatements() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) If disposable IsNot Nothing Then Dim x = disposable[||] End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableOnSingleLineIfElseClauses() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) If disposable IsNot Nothing Then Else Dim x = disposable[||] End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableOnSingleLineLambda() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) New Action(Function() Dim x = disposable[||]) End Sub End Class") End Function <Fact> <WorkItem(35237, "https://github.com/dotnet/roslyn/issues/35237")> Public Async Function ExpandsToIncludeSurroundedVariableDeclarations() As Task Await TestInRegularAndScriptAsync( "Imports System.IO Class C Sub M() Dim reader = New MemoryStream()[||] Dim buffer = reader.GetBuffer() buffer.Clone() Dim a = 1 End Sub End Class", "Imports System.IO Class C Sub M() Using reader = New MemoryStream() Dim buffer = reader.GetBuffer() buffer.Clone() End Using Dim a = 1 End Sub End Class") End Function <Fact> <WorkItem(35237, "https://github.com/dotnet/roslyn/issues/35237")> Public Async Function ExpandsToIncludeSurroundedMultiVariableDeclarations() As Task Await TestInRegularAndScriptAsync( "Imports System.IO Class C Sub M() Dim reader = New MemoryStream()[||] Dim buffer = reader.GetBuffer() Dim a As Integer = buffer(0), b As Integer = a Dim c = b Dim d = 1 End Sub End Class", "Imports System.IO Class C Sub M() Using reader = New MemoryStream() Dim buffer = reader.GetBuffer() Dim a As Integer = buffer(0), b As Integer = a Dim c = b End Using Dim d = 1 End Sub End Class") 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.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.IntroduceUsingStatement Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.IntroduceUsingStatement <Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceUsingStatement)> Public NotInheritable Class IntroduceUsingStatementTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(ByVal workspace As Workspace, ByVal parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicIntroduceUsingStatementCodeRefactoringProvider End Function <Theory> <InlineData("D[||]im name = disposable")> <InlineData("Dim[||] name = disposable")> <InlineData("Dim [||]name = disposable")> <InlineData("Dim na[||]me = disposable")> <InlineData("Dim name[||] = disposable")> <InlineData("Dim name [||]= disposable")> <InlineData("Dim name =[||] disposable")> <InlineData("Dim name = [||]disposable")> <InlineData("[|Dim name = disposable|]")> <InlineData("Dim name = disposable[||]")> <InlineData("Dim name = disposable[||]")> Public Async Function RefactoringIsAvailableForSelection(ByVal declaration As String) As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) " & declaration & " End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForVerticalSelection() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) [| " & " Dim name = disposable |] End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtStartOfStatementWithPrecedingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable [||]Dim name = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtStartOfLineWithPrecedingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable [||] Dim name = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtEndOfStatementWithFollowingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim name = disposable[||] Dim ignore = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using Dim ignore = disposable End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtEndOfLineWithFollowingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim name = disposable [||] Dim ignore = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using Dim ignore = disposable End Sub End Class") End Function <Theory> <InlineData("Dim name = d[||]isposable")> <InlineData("Dim name = disposabl[||]e")> <InlineData("Dim name=[|disposable|]")> Public Async Function RefactoringIsNotAvailableForSelection(ByVal declaration As String) As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) " & declaration & " End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableForDeclarationMissingInitializerExpression() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim name As System.IDisposable =[||] End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableForUsingStatementDeclaration() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Using [||]name = disposable End Using End Sub End Class") End Function <Theory> <InlineData("[||]Dim x = disposable, y = disposable")> <InlineData("Dim [||]x = disposable, y = disposable")> <InlineData("Dim x = disposable, [||]y = disposable")> <InlineData("Dim x = disposable, y = disposable[||]")> Public Async Function RefactoringIsNotAvailableForMultiVariableDeclaration(ByVal declaration As String) As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) " & declaration & " End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForConstrainedGenericTypeParameter() As Task Await TestInRegularAndScriptAsync("Class C(Of T As System.IDisposable) Sub M(disposable As T) Dim x = disposable[||] End Sub End Class", "Class C(Of T As System.IDisposable) Sub M(disposable As T) Using x = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableForUnconstrainedGenericTypeParameter() As Task Await TestMissingAsync("Class C(Of T) Sub M(disposable as T) Dim x = disposable[||] End Sub End Class") End Function <Fact> Public Async Function LeadingCommentTriviaIsPlacedOnUsingStatement() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) ' Comment Dim x = disposable[||] End Sub End Class", "Class C Sub M(disposable As System.IDisposable) ' Comment Using x = disposable End Using End Sub End Class") End Function <Fact> Public Async Function CommentOnTheSameLineStaysOnTheSameLine() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim x = disposable[||] ' Comment End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using x = disposable ' Comment End Using End Sub End Class") End Function <Fact> Public Async Function TrailingCommentTriviaOnNextLineGoesAfterBlock() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim x = disposable[||] ' Comment End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using x = disposable End Using ' Comment End Sub End Class") End Function <Fact> Public Async Function ValidPreprocessorStaysValid() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) #If True Then Dim x = disposable[||] #End If End Sub End Class", "Class C Sub M(disposable As System.IDisposable) #If True Then Using x = disposable End Using #End If End Sub End Class") End Function <Fact> Public Async Function InvalidPreprocessorStaysInvalid() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) #If True Then Dim x = disposable[||] #End If Dim discard = x End Sub End Class", "Class C Sub M(disposable As System.IDisposable) #If True Then Using x = disposable #End If Dim discard = x End Using End Sub End Class") End Function <Fact> Public Async Function StatementsAreSurroundedByMinimalScope() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) M(null) Dim x = disposable[||] M(null) M(x) M(null) End Sub End Class", "Class C Sub M(disposable As System.IDisposable) M(null) Using x = disposable M(null) M(x) End Using M(null) End Sub End Class") End Function <Fact> Public Async Function CommentsAreSurroundedExceptLinesFollowingLastUsage() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim x = disposable[||] ' A M(x) ' B ' C End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using x = disposable ' A M(x) ' B End Using ' C End Sub End Class") End Function <Fact> Public Async Function WorksInSelectCases() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Select Case disposable Case Else Dim x = disposable[||] M(x) End Select End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Select Case disposable Case Else Using x = disposable M(x) End Using End Select End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableOnSingleLineIfStatements() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) If disposable IsNot Nothing Then Dim x = disposable[||] End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableOnSingleLineIfElseClauses() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) If disposable IsNot Nothing Then Else Dim x = disposable[||] End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableOnSingleLineLambda() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) New Action(Function() Dim x = disposable[||]) End Sub End Class") End Function <Fact> <WorkItem(35237, "https://github.com/dotnet/roslyn/issues/35237")> Public Async Function ExpandsToIncludeSurroundedVariableDeclarations() As Task Await TestInRegularAndScriptAsync( "Imports System.IO Class C Sub M() Dim reader = New MemoryStream()[||] Dim buffer = reader.GetBuffer() buffer.Clone() Dim a = 1 End Sub End Class", "Imports System.IO Class C Sub M() Using reader = New MemoryStream() Dim buffer = reader.GetBuffer() buffer.Clone() End Using Dim a = 1 End Sub End Class") End Function <Fact> <WorkItem(35237, "https://github.com/dotnet/roslyn/issues/35237")> Public Async Function ExpandsToIncludeSurroundedMultiVariableDeclarations() As Task Await TestInRegularAndScriptAsync( "Imports System.IO Class C Sub M() Dim reader = New MemoryStream()[||] Dim buffer = reader.GetBuffer() Dim a As Integer = buffer(0), b As Integer = a Dim c = b Dim d = 1 End Sub End Class", "Imports System.IO Class C Sub M() Using reader = New MemoryStream() Dim buffer = reader.GetBuffer() Dim a As Integer = buffer(0), b As Integer = a Dim c = b End Using Dim d = 1 End Sub End Class") End Function End Class End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/LanguageServer/ProtocolUnitTests/SemanticTokens/SemanticTokensRangeTests.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 enable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens; using Microsoft.VisualStudio.LanguageServer.Protocol; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.SemanticTokens { public class SemanticTokensRangeTests : AbstractSemanticTokensTests { [Fact] public async Task TestGetSemanticTokensRangeAsync() { var markup = @"{|caret:|}// Comment static class C { } "; using var testLspServer = CreateTestLspServer(markup, out var locations); var range = new LSP.Range { Start = new Position(1, 0), End = new Position(2, 0) }; var results = await RunGetSemanticTokensRangeAsync(testLspServer, locations["caret"].First(), range); var expectedResults = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static' 0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "1" }; await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false); Assert.Equal(expectedResults.Data, results.Data); Assert.Equal(expectedResults.ResultId, results.ResultId); } } }
// 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 enable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens; using Microsoft.VisualStudio.LanguageServer.Protocol; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.SemanticTokens { public class SemanticTokensRangeTests : AbstractSemanticTokensTests { [Fact] public async Task TestGetSemanticTokensRangeAsync() { var markup = @"{|caret:|}// Comment static class C { } "; using var testLspServer = CreateTestLspServer(markup, out var locations); var range = new LSP.Range { Start = new Position(1, 0), End = new Position(2, 0) }; var results = await RunGetSemanticTokensRangeAsync(testLspServer, locations["caret"].First(), range); var expectedResults = new LSP.SemanticTokens { Data = new int[] { // Line | Char | Len | Token type | Modifier 1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static' 0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class' 0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{' 0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}' }, ResultId = "1" }; await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false); Assert.Equal(expectedResults.Data, results.Data); Assert.Equal(expectedResults.ResultId, results.ResultId); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEMethodSymbol.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.Reflection Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend Delegate Function GenerateMethodBody( method As EEMethodSymbol, diagnostics As DiagnosticBag, <Out> ByRef properties As ResultProperties) As BoundStatement Friend NotInheritable Class EEMethodSymbol Inherits MethodSymbol Friend ReadOnly TypeMap As TypeSubstitution Friend ReadOnly SubstitutedSourceMethod As MethodSymbol Friend ReadOnly Locals As ImmutableArray(Of LocalSymbol) Friend ReadOnly LocalsForBinding As ImmutableArray(Of LocalSymbol) Private ReadOnly _compilation As VisualBasicCompilation Private ReadOnly _container As EENamedTypeSymbol Private ReadOnly _name As String Private ReadOnly _locations As ImmutableArray(Of Location) Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _meParameter As ParameterSymbol Private ReadOnly _displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable) Private ReadOnly _voidType As NamedTypeSymbol ''' <summary> ''' Invoked at most once to generate the method body. ''' (If the compilation has no errors, it will be invoked ''' exactly once, otherwise it may be skipped.) ''' </summary> Private ReadOnly _generateMethodBody As GenerateMethodBody Private _lazyReturnType As TypeSymbol Private _lazyResultProperties As ResultProperties ' NOTE: This is only used for asserts, so it could be conditional on DEBUG. Private ReadOnly _allTypeParameters As ImmutableArray(Of TypeParameterSymbol) Friend Sub New( compilation As VisualBasicCompilation, container As EENamedTypeSymbol, name As String, location As Location, sourceMethod As MethodSymbol, sourceLocals As ImmutableArray(Of LocalSymbol), sourceLocalsForBinding As ImmutableArray(Of LocalSymbol), sourceDisplayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), voidType As NamedTypeSymbol, generateMethodBody As GenerateMethodBody) Debug.Assert(sourceMethod.IsDefinition) Debug.Assert(TypeSymbol.Equals(sourceMethod.ContainingType, container.SubstitutedSourceType.OriginalDefinition, TypeCompareKind.ConsiderEverything)) Debug.Assert(sourceLocals.All(Function(l) l.ContainingSymbol = sourceMethod)) _compilation = compilation _container = container _name = name _locations = ImmutableArray.Create(location) _voidType = voidType ' What we want is to map all original type parameters to the corresponding new type parameters ' (since the old ones have the wrong owners). Unfortunately, we have a circular dependency: ' 1) Each new type parameter requires the entire map in order to be able to construct its constraint list. ' 2) The map cannot be constructed until all new type parameters exist. ' Our solution is to pass each new type parameter a lazy reference to the type map. We then ' initialize the map as soon as the new type parameters are available - and before they are ' handed out - so that there is never a period where they can require the type map and find ' it uninitialized. Dim sourceMethodTypeParameters = sourceMethod.TypeParameters Dim allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters) Dim getTypeMap As New Func(Of TypeSubstitution)(Function() TypeMap) _typeParameters = sourceMethodTypeParameters.SelectAsArray( Function(tp As TypeParameterSymbol, i As Integer, arg As Object) DirectCast(New EETypeParameterSymbol(Me, tp, i, getTypeMap), TypeParameterSymbol), DirectCast(Nothing, Object)) _allTypeParameters = container.TypeParameters.Concat(_typeParameters) Me.TypeMap = TypeSubstitution.Create(sourceMethod, allSourceTypeParameters, ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(_allTypeParameters)) EENamedTypeSymbol.VerifyTypeParameters(Me, _typeParameters) Dim substitutedSourceType = container.SubstitutedSourceType Me.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType) If _typeParameters.Any() Then Me.SubstitutedSourceMethod = Me.SubstitutedSourceMethod.Construct(_typeParameters.As(Of TypeSymbol)()) End If TypeParameterChecker.Check(Me.SubstitutedSourceMethod, _allTypeParameters) ' Create a map from original parameter to target parameter. Dim parameterBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance() Dim substitutedSourceMeParameter = Me.SubstitutedSourceMethod.MeParameter Dim substitutedSourceHasMeParameter = substitutedSourceMeParameter IsNot Nothing If substitutedSourceHasMeParameter Then _meParameter = MakeParameterSymbol(0, GeneratedNames.MakeStateMachineCapturedMeName(), substitutedSourceMeParameter) ' NOTE: Name doesn't actually matter. Debug.Assert(TypeSymbol.Equals(_meParameter.Type, Me.SubstitutedSourceMethod.ContainingType, TypeCompareKind.ConsiderEverything)) parameterBuilder.Add(_meParameter) End If Dim ordinalOffset = If(substitutedSourceHasMeParameter, 1, 0) For Each substitutedSourceParameter In Me.SubstitutedSourceMethod.Parameters Dim ordinal = substitutedSourceParameter.Ordinal + ordinalOffset Debug.Assert(ordinal = parameterBuilder.Count) Dim parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter) parameterBuilder.Add(parameter) Next _parameters = parameterBuilder.ToImmutableAndFree() Dim localsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() Dim localsMap = PooledDictionary(Of LocalSymbol, LocalSymbol).GetInstance() For Each sourceLocal In sourceLocals Dim local = sourceLocal.ToOtherMethod(Me, Me.TypeMap) localsMap.Add(sourceLocal, local) localsBuilder.Add(local) Next Me.Locals = localsBuilder.ToImmutableAndFree() localsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() For Each sourceLocal In sourceLocalsForBinding Dim local As LocalSymbol = Nothing If Not localsMap.TryGetValue(sourceLocal, local) Then local = sourceLocal.ToOtherMethod(Me, Me.TypeMap) localsMap.Add(sourceLocal, local) End If localsBuilder.Add(local) Next Me.LocalsForBinding = localsBuilder.ToImmutableAndFree() ' Create a map from variable name to display class field. _displayClassVariables = SubstituteDisplayClassVariables(sourceDisplayClassVariables, localsMap, Me, Me.TypeMap) localsMap.Free() _generateMethodBody = generateMethodBody End Sub Private Shared Function SubstituteDisplayClassVariables( oldDisplayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), localsMap As Dictionary(Of LocalSymbol, LocalSymbol), otherMethod As MethodSymbol, typeMap As TypeSubstitution) As ImmutableDictionary(Of String, DisplayClassVariable) ' Create a map from variable name to display class field. Dim newDisplayClassVariables = PooledDictionary(Of String, DisplayClassVariable).GetInstance() For Each pair In oldDisplayClassVariables Dim variable = pair.Value Dim oldDisplayClassInstance = variable.DisplayClassInstance ' Note: we don't call ToOtherMethod in the local case because doing so would produce ' a new LocalSymbol that would not be ReferenceEquals to the one in this.LocalsForBinding. Dim oldDisplayClassInstanceFromLocal = TryCast(oldDisplayClassInstance, DisplayClassInstanceFromLocal) Dim newDisplayClassInstance = If(oldDisplayClassInstanceFromLocal Is Nothing, oldDisplayClassInstance.ToOtherMethod(otherMethod, typeMap), New DisplayClassInstanceFromLocal(DirectCast(localsMap(oldDisplayClassInstanceFromLocal.Local), EELocalSymbol))) variable = variable.SubstituteFields(newDisplayClassInstance, typeMap) newDisplayClassVariables.Add(pair.Key, variable) Next Dim result = newDisplayClassVariables.ToImmutableDictionary() newDisplayClassVariables.Free() Return result End Function Private Function MakeParameterSymbol(ordinal As Integer, name As String, sourceParameter As ParameterSymbol) As ParameterSymbol Return SynthesizedParameterSymbol.Create( Me, sourceParameter.Type, ordinal, sourceParameter.IsByRef, name, sourceParameter.CustomModifiers, sourceParameter.RefCustomModifiers) End Function Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return _typeParameters.Length End Get End Property Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property ImplementationAttributes As MethodImplAttributes Get Return Nothing End Get End Property Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Return False End Get End Property Public Overrides Function GetDllImportData() As DllImportData Return Nothing End Function Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Return Nothing End Get End Property Friend Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean meParameter = Nothing Return True End Function Public Overrides ReadOnly Property IsVararg As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return ReturnType.SpecialType = SpecialType.System_Void End Get End Property Public Overrides ReadOnly Property IsAsync As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get If _lazyReturnType Is Nothing Then Throw New InvalidOperationException() End If Return _lazyReturnType End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(_typeParameters) End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return _typeParameters End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property CallingConvention As Cci.CallingConvention Get Debug.Assert(Me.IsShared) Dim cc = Cci.CallingConvention.Default If Me.IsVararg Then cc = cc Or Cci.CallingConvention.ExtraArguments End If If Me.IsGenericMethod Then cc = cc Or Cci.CallingConvention.Generic End If Return cc End Get End Property Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Internal End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsExternalMethod As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsIterator As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsInitOnly As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Throw ExceptionUtilities.Unreachable End Get End Property Friend Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property Syntax As SyntaxNode Get Return Nothing End Get End Property Friend ReadOnly Property ResultProperties As ResultProperties Get Return _lazyResultProperties End Get End Property #Disable Warning CA1200 ' Avoid using cref tags with a prefix ''' <remarks> ''' The corresponding C# method, ''' <see cref="M:Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.EEMethodSymbol.GenerateMethodBody(Microsoft.CodeAnalysis.CSharp.TypeCompilationState,Microsoft.CodeAnalysis.DiagnosticBag)"/>, ''' invokes the <see cref="LocalRewriter"/> and the <see cref="LambdaRewriter"/> explicitly. ''' In VB, the caller (of this method) does that. ''' </remarks> #Enable Warning CA1200 ' Avoid using cref tags with a prefix Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, <Out> ByRef Optional methodBodyBinder As Binder = Nothing) As BoundBlock Debug.Assert(diagnostics.DiagnosticBag IsNot Nothing) Dim body = _generateMethodBody(Me, diagnostics.DiagnosticBag, _lazyResultProperties) Debug.Assert(body IsNot Nothing) _lazyReturnType = CalculateReturnType(body) ' Can't do this until the return type has been computed. TypeParameterChecker.Check(Me, _allTypeParameters) Dim syntax As SyntaxNode = body.Syntax Dim statementsBuilder = ArrayBuilder(Of BoundStatement).GetInstance() statementsBuilder.Add(body) ' Insert an implicit return statement if necessary. If body.Kind <> BoundKind.ReturnStatement Then statementsBuilder.Add(New BoundReturnStatement(syntax, Nothing, Nothing, Nothing)) End If Dim originalLocalsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() Dim originalLocalsSet = PooledHashSet(Of LocalSymbol).GetInstance() For Each local In LocalsForBinding Debug.Assert(Not originalLocalsSet.Contains(local)) originalLocalsBuilder.Add(local) originalLocalsSet.Add(local) Next For Each local In Me.Locals If originalLocalsSet.Add(local) Then originalLocalsBuilder.Add(local) End If Next originalLocalsSet.Free() Dim originalLocals = originalLocalsBuilder.ToImmutableAndFree() Dim newBody = New BoundBlock(syntax, Nothing, originalLocals, statementsBuilder.ToImmutableAndFree()) If diagnostics.HasAnyErrors() Then Return newBody End If DiagnosticsPass.IssueDiagnostics(newBody, diagnostics.DiagnosticBag, Me) If diagnostics.HasAnyErrors() Then Return newBody End If ' Check for use-site errors (e.g. missing types in the signature). Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Me.CalculateUseSiteInfo() If useSiteInfo.DiagnosticInfo IsNot Nothing Then diagnostics.Add(useSiteInfo, _locations(0)) Return newBody End If Debug.Assert(Not newBody.HasErrors) ' NOTE: In C#, EE rewriting happens AFTER local rewriting. However, that order would be difficult ' to accommodate in VB, so we reverse it. Try ' Rewrite local declaration statement. newBody = LocalDeclarationRewriter.Rewrite(_compilation, _container, newBody) ' Rewrite pseudo-variable references to helper method calls. newBody = DirectCast(PlaceholderLocalRewriter.Rewrite(_compilation, _container, newBody, diagnostics.DiagnosticBag), BoundBlock) If diagnostics.HasAnyErrors() Then Return newBody End If ' Create a map from original local to target local. Dim localMap = PooledDictionary(Of LocalSymbol, LocalSymbol).GetInstance() Dim targetLocals = newBody.Locals Debug.Assert(originalLocals.Length = targetLocals.Length) For i = 0 To originalLocals.Length - 1 Dim originalLocal = originalLocals(i) Dim targetLocal = targetLocals(i) Debug.Assert(TypeOf originalLocal IsNot EELocalSymbol OrElse DirectCast(originalLocal, EELocalSymbol).Ordinal = DirectCast(targetLocal, EELocalSymbol).Ordinal) localMap.Add(originalLocal, targetLocal) Next ' Variables may have been captured by lambdas in the original method ' or in the expression, and we need to preserve the existing values of ' those variables in the expression. This requires rewriting the variables ' in the expression based on the closure classes from both the original ' method and the expression, and generating a preamble that copies ' values into the expression closure classes. ' ' Consider the original method: ' Shared Sub M() ' Dim x, y, z as Integer ' ... ' F(Function() x + y) ' End Sub ' and the expression in the EE: "F(Function() x + z)". ' ' The expression is first rewritten using the closure class and local <1> ' from the original method: F(Function() <1>.x + z) ' Then lambda rewriting introduces a new closure class that includes ' the locals <1> and z, and a corresponding local <2>: F(Function() <2>.<1>.x + <2>.z) ' And a preamble is added to initialize the fields of <2>: ' <2> = New <>c__DisplayClass0() ' <2>.<1> = <1> ' <2>.z = z ' ' Note: The above behavior is actually implemented in the LambdaRewriter and ' is triggered by overriding PreserveOriginalLocals to return "True". ' Create a map from variable name to display class field. Dim displayClassVariables = SubstituteDisplayClassVariables(_displayClassVariables, localMap, Me, Me.TypeMap) ' Rewrite references to "Me" to refer to this method's "Me" parameter. ' Rewrite variables within body to reference existing display classes. newBody = DirectCast(CapturedVariableRewriter.Rewrite( If(Me.SubstitutedSourceMethod.IsShared, Nothing, Me.Parameters(0)), displayClassVariables, newBody, diagnostics.DiagnosticBag), BoundBlock) If diagnostics.HasAnyErrors() Then Return newBody End If ' Insert locals from the original method, followed by any new locals. Dim localBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() For Each originalLocal In Me.Locals Dim targetLocal = localMap(originalLocal) Debug.Assert(TypeOf targetLocal IsNot EELocalSymbol OrElse DirectCast(targetLocal, EELocalSymbol).Ordinal = localBuilder.Count) localBuilder.Add(targetLocal) Next localMap.Free() newBody = newBody.Update(newBody.StatementListSyntax, localBuilder.ToImmutableAndFree(), newBody.Statements) TypeParameterChecker.Check(newBody, _allTypeParameters) Catch ex As BoundTreeVisitor.CancelledByStackGuardException ex.AddAnError(diagnostics) End Try Return newBody End Function Private Function CalculateReturnType(body As BoundStatement) As TypeSymbol Select Case body.Kind Case BoundKind.ReturnStatement Return DirectCast(body, BoundReturnStatement).ExpressionOpt.Type Case BoundKind.ExpressionStatement, BoundKind.RedimStatement Return _voidType Case Else Throw ExceptionUtilities.UnexpectedValue(body.Kind) End Select End Function Friend Overrides Sub AddSynthesizedReturnTypeAttributes(ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedReturnTypeAttributes(attributes) Dim returnType = Me.ReturnType If returnType.ContainsTupleNames() AndAlso DeclaringCompilation.HasTupleNamesAttributes() Then AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(returnType)) End If End Sub Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Return localPosition End Function Friend Overrides ReadOnly Property PreserveOriginalLocals 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.Collections.Immutable Imports System.Reflection Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend Delegate Function GenerateMethodBody( method As EEMethodSymbol, diagnostics As DiagnosticBag, <Out> ByRef properties As ResultProperties) As BoundStatement Friend NotInheritable Class EEMethodSymbol Inherits MethodSymbol Friend ReadOnly TypeMap As TypeSubstitution Friend ReadOnly SubstitutedSourceMethod As MethodSymbol Friend ReadOnly Locals As ImmutableArray(Of LocalSymbol) Friend ReadOnly LocalsForBinding As ImmutableArray(Of LocalSymbol) Private ReadOnly _compilation As VisualBasicCompilation Private ReadOnly _container As EENamedTypeSymbol Private ReadOnly _name As String Private ReadOnly _locations As ImmutableArray(Of Location) Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _meParameter As ParameterSymbol Private ReadOnly _displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable) Private ReadOnly _voidType As NamedTypeSymbol ''' <summary> ''' Invoked at most once to generate the method body. ''' (If the compilation has no errors, it will be invoked ''' exactly once, otherwise it may be skipped.) ''' </summary> Private ReadOnly _generateMethodBody As GenerateMethodBody Private _lazyReturnType As TypeSymbol Private _lazyResultProperties As ResultProperties ' NOTE: This is only used for asserts, so it could be conditional on DEBUG. Private ReadOnly _allTypeParameters As ImmutableArray(Of TypeParameterSymbol) Friend Sub New( compilation As VisualBasicCompilation, container As EENamedTypeSymbol, name As String, location As Location, sourceMethod As MethodSymbol, sourceLocals As ImmutableArray(Of LocalSymbol), sourceLocalsForBinding As ImmutableArray(Of LocalSymbol), sourceDisplayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), voidType As NamedTypeSymbol, generateMethodBody As GenerateMethodBody) Debug.Assert(sourceMethod.IsDefinition) Debug.Assert(TypeSymbol.Equals(sourceMethod.ContainingType, container.SubstitutedSourceType.OriginalDefinition, TypeCompareKind.ConsiderEverything)) Debug.Assert(sourceLocals.All(Function(l) l.ContainingSymbol = sourceMethod)) _compilation = compilation _container = container _name = name _locations = ImmutableArray.Create(location) _voidType = voidType ' What we want is to map all original type parameters to the corresponding new type parameters ' (since the old ones have the wrong owners). Unfortunately, we have a circular dependency: ' 1) Each new type parameter requires the entire map in order to be able to construct its constraint list. ' 2) The map cannot be constructed until all new type parameters exist. ' Our solution is to pass each new type parameter a lazy reference to the type map. We then ' initialize the map as soon as the new type parameters are available - and before they are ' handed out - so that there is never a period where they can require the type map and find ' it uninitialized. Dim sourceMethodTypeParameters = sourceMethod.TypeParameters Dim allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters) Dim getTypeMap As New Func(Of TypeSubstitution)(Function() TypeMap) _typeParameters = sourceMethodTypeParameters.SelectAsArray( Function(tp As TypeParameterSymbol, i As Integer, arg As Object) DirectCast(New EETypeParameterSymbol(Me, tp, i, getTypeMap), TypeParameterSymbol), DirectCast(Nothing, Object)) _allTypeParameters = container.TypeParameters.Concat(_typeParameters) Me.TypeMap = TypeSubstitution.Create(sourceMethod, allSourceTypeParameters, ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(_allTypeParameters)) EENamedTypeSymbol.VerifyTypeParameters(Me, _typeParameters) Dim substitutedSourceType = container.SubstitutedSourceType Me.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType) If _typeParameters.Any() Then Me.SubstitutedSourceMethod = Me.SubstitutedSourceMethod.Construct(_typeParameters.As(Of TypeSymbol)()) End If TypeParameterChecker.Check(Me.SubstitutedSourceMethod, _allTypeParameters) ' Create a map from original parameter to target parameter. Dim parameterBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance() Dim substitutedSourceMeParameter = Me.SubstitutedSourceMethod.MeParameter Dim substitutedSourceHasMeParameter = substitutedSourceMeParameter IsNot Nothing If substitutedSourceHasMeParameter Then _meParameter = MakeParameterSymbol(0, GeneratedNames.MakeStateMachineCapturedMeName(), substitutedSourceMeParameter) ' NOTE: Name doesn't actually matter. Debug.Assert(TypeSymbol.Equals(_meParameter.Type, Me.SubstitutedSourceMethod.ContainingType, TypeCompareKind.ConsiderEverything)) parameterBuilder.Add(_meParameter) End If Dim ordinalOffset = If(substitutedSourceHasMeParameter, 1, 0) For Each substitutedSourceParameter In Me.SubstitutedSourceMethod.Parameters Dim ordinal = substitutedSourceParameter.Ordinal + ordinalOffset Debug.Assert(ordinal = parameterBuilder.Count) Dim parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter) parameterBuilder.Add(parameter) Next _parameters = parameterBuilder.ToImmutableAndFree() Dim localsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() Dim localsMap = PooledDictionary(Of LocalSymbol, LocalSymbol).GetInstance() For Each sourceLocal In sourceLocals Dim local = sourceLocal.ToOtherMethod(Me, Me.TypeMap) localsMap.Add(sourceLocal, local) localsBuilder.Add(local) Next Me.Locals = localsBuilder.ToImmutableAndFree() localsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() For Each sourceLocal In sourceLocalsForBinding Dim local As LocalSymbol = Nothing If Not localsMap.TryGetValue(sourceLocal, local) Then local = sourceLocal.ToOtherMethod(Me, Me.TypeMap) localsMap.Add(sourceLocal, local) End If localsBuilder.Add(local) Next Me.LocalsForBinding = localsBuilder.ToImmutableAndFree() ' Create a map from variable name to display class field. _displayClassVariables = SubstituteDisplayClassVariables(sourceDisplayClassVariables, localsMap, Me, Me.TypeMap) localsMap.Free() _generateMethodBody = generateMethodBody End Sub Private Shared Function SubstituteDisplayClassVariables( oldDisplayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), localsMap As Dictionary(Of LocalSymbol, LocalSymbol), otherMethod As MethodSymbol, typeMap As TypeSubstitution) As ImmutableDictionary(Of String, DisplayClassVariable) ' Create a map from variable name to display class field. Dim newDisplayClassVariables = PooledDictionary(Of String, DisplayClassVariable).GetInstance() For Each pair In oldDisplayClassVariables Dim variable = pair.Value Dim oldDisplayClassInstance = variable.DisplayClassInstance ' Note: we don't call ToOtherMethod in the local case because doing so would produce ' a new LocalSymbol that would not be ReferenceEquals to the one in this.LocalsForBinding. Dim oldDisplayClassInstanceFromLocal = TryCast(oldDisplayClassInstance, DisplayClassInstanceFromLocal) Dim newDisplayClassInstance = If(oldDisplayClassInstanceFromLocal Is Nothing, oldDisplayClassInstance.ToOtherMethod(otherMethod, typeMap), New DisplayClassInstanceFromLocal(DirectCast(localsMap(oldDisplayClassInstanceFromLocal.Local), EELocalSymbol))) variable = variable.SubstituteFields(newDisplayClassInstance, typeMap) newDisplayClassVariables.Add(pair.Key, variable) Next Dim result = newDisplayClassVariables.ToImmutableDictionary() newDisplayClassVariables.Free() Return result End Function Private Function MakeParameterSymbol(ordinal As Integer, name As String, sourceParameter As ParameterSymbol) As ParameterSymbol Return SynthesizedParameterSymbol.Create( Me, sourceParameter.Type, ordinal, sourceParameter.IsByRef, name, sourceParameter.CustomModifiers, sourceParameter.RefCustomModifiers) End Function Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return _typeParameters.Length End Get End Property Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property ImplementationAttributes As MethodImplAttributes Get Return Nothing End Get End Property Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Return False End Get End Property Public Overrides Function GetDllImportData() As DllImportData Return Nothing End Function Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Return Nothing End Get End Property Friend Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean meParameter = Nothing Return True End Function Public Overrides ReadOnly Property IsVararg As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return ReturnType.SpecialType = SpecialType.System_Void End Get End Property Public Overrides ReadOnly Property IsAsync As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get If _lazyReturnType Is Nothing Then Throw New InvalidOperationException() End If Return _lazyReturnType End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(_typeParameters) End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return _typeParameters End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property CallingConvention As Cci.CallingConvention Get Debug.Assert(Me.IsShared) Dim cc = Cci.CallingConvention.Default If Me.IsVararg Then cc = cc Or Cci.CallingConvention.ExtraArguments End If If Me.IsGenericMethod Then cc = cc Or Cci.CallingConvention.Generic End If Return cc End Get End Property Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Internal End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsExternalMethod As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsIterator As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsInitOnly As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Throw ExceptionUtilities.Unreachable End Get End Property Friend Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property Syntax As SyntaxNode Get Return Nothing End Get End Property Friend ReadOnly Property ResultProperties As ResultProperties Get Return _lazyResultProperties End Get End Property #Disable Warning CA1200 ' Avoid using cref tags with a prefix ''' <remarks> ''' The corresponding C# method, ''' <see cref="M:Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.EEMethodSymbol.GenerateMethodBody(Microsoft.CodeAnalysis.CSharp.TypeCompilationState,Microsoft.CodeAnalysis.DiagnosticBag)"/>, ''' invokes the <see cref="LocalRewriter"/> and the <see cref="LambdaRewriter"/> explicitly. ''' In VB, the caller (of this method) does that. ''' </remarks> #Enable Warning CA1200 ' Avoid using cref tags with a prefix Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, <Out> ByRef Optional methodBodyBinder As Binder = Nothing) As BoundBlock Debug.Assert(diagnostics.DiagnosticBag IsNot Nothing) Dim body = _generateMethodBody(Me, diagnostics.DiagnosticBag, _lazyResultProperties) Debug.Assert(body IsNot Nothing) _lazyReturnType = CalculateReturnType(body) ' Can't do this until the return type has been computed. TypeParameterChecker.Check(Me, _allTypeParameters) Dim syntax As SyntaxNode = body.Syntax Dim statementsBuilder = ArrayBuilder(Of BoundStatement).GetInstance() statementsBuilder.Add(body) ' Insert an implicit return statement if necessary. If body.Kind <> BoundKind.ReturnStatement Then statementsBuilder.Add(New BoundReturnStatement(syntax, Nothing, Nothing, Nothing)) End If Dim originalLocalsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() Dim originalLocalsSet = PooledHashSet(Of LocalSymbol).GetInstance() For Each local In LocalsForBinding Debug.Assert(Not originalLocalsSet.Contains(local)) originalLocalsBuilder.Add(local) originalLocalsSet.Add(local) Next For Each local In Me.Locals If originalLocalsSet.Add(local) Then originalLocalsBuilder.Add(local) End If Next originalLocalsSet.Free() Dim originalLocals = originalLocalsBuilder.ToImmutableAndFree() Dim newBody = New BoundBlock(syntax, Nothing, originalLocals, statementsBuilder.ToImmutableAndFree()) If diagnostics.HasAnyErrors() Then Return newBody End If DiagnosticsPass.IssueDiagnostics(newBody, diagnostics.DiagnosticBag, Me) If diagnostics.HasAnyErrors() Then Return newBody End If ' Check for use-site errors (e.g. missing types in the signature). Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Me.CalculateUseSiteInfo() If useSiteInfo.DiagnosticInfo IsNot Nothing Then diagnostics.Add(useSiteInfo, _locations(0)) Return newBody End If Debug.Assert(Not newBody.HasErrors) ' NOTE: In C#, EE rewriting happens AFTER local rewriting. However, that order would be difficult ' to accommodate in VB, so we reverse it. Try ' Rewrite local declaration statement. newBody = LocalDeclarationRewriter.Rewrite(_compilation, _container, newBody) ' Rewrite pseudo-variable references to helper method calls. newBody = DirectCast(PlaceholderLocalRewriter.Rewrite(_compilation, _container, newBody, diagnostics.DiagnosticBag), BoundBlock) If diagnostics.HasAnyErrors() Then Return newBody End If ' Create a map from original local to target local. Dim localMap = PooledDictionary(Of LocalSymbol, LocalSymbol).GetInstance() Dim targetLocals = newBody.Locals Debug.Assert(originalLocals.Length = targetLocals.Length) For i = 0 To originalLocals.Length - 1 Dim originalLocal = originalLocals(i) Dim targetLocal = targetLocals(i) Debug.Assert(TypeOf originalLocal IsNot EELocalSymbol OrElse DirectCast(originalLocal, EELocalSymbol).Ordinal = DirectCast(targetLocal, EELocalSymbol).Ordinal) localMap.Add(originalLocal, targetLocal) Next ' Variables may have been captured by lambdas in the original method ' or in the expression, and we need to preserve the existing values of ' those variables in the expression. This requires rewriting the variables ' in the expression based on the closure classes from both the original ' method and the expression, and generating a preamble that copies ' values into the expression closure classes. ' ' Consider the original method: ' Shared Sub M() ' Dim x, y, z as Integer ' ... ' F(Function() x + y) ' End Sub ' and the expression in the EE: "F(Function() x + z)". ' ' The expression is first rewritten using the closure class and local <1> ' from the original method: F(Function() <1>.x + z) ' Then lambda rewriting introduces a new closure class that includes ' the locals <1> and z, and a corresponding local <2>: F(Function() <2>.<1>.x + <2>.z) ' And a preamble is added to initialize the fields of <2>: ' <2> = New <>c__DisplayClass0() ' <2>.<1> = <1> ' <2>.z = z ' ' Note: The above behavior is actually implemented in the LambdaRewriter and ' is triggered by overriding PreserveOriginalLocals to return "True". ' Create a map from variable name to display class field. Dim displayClassVariables = SubstituteDisplayClassVariables(_displayClassVariables, localMap, Me, Me.TypeMap) ' Rewrite references to "Me" to refer to this method's "Me" parameter. ' Rewrite variables within body to reference existing display classes. newBody = DirectCast(CapturedVariableRewriter.Rewrite( If(Me.SubstitutedSourceMethod.IsShared, Nothing, Me.Parameters(0)), displayClassVariables, newBody, diagnostics.DiagnosticBag), BoundBlock) If diagnostics.HasAnyErrors() Then Return newBody End If ' Insert locals from the original method, followed by any new locals. Dim localBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() For Each originalLocal In Me.Locals Dim targetLocal = localMap(originalLocal) Debug.Assert(TypeOf targetLocal IsNot EELocalSymbol OrElse DirectCast(targetLocal, EELocalSymbol).Ordinal = localBuilder.Count) localBuilder.Add(targetLocal) Next localMap.Free() newBody = newBody.Update(newBody.StatementListSyntax, localBuilder.ToImmutableAndFree(), newBody.Statements) TypeParameterChecker.Check(newBody, _allTypeParameters) Catch ex As BoundTreeVisitor.CancelledByStackGuardException ex.AddAnError(diagnostics) End Try Return newBody End Function Private Function CalculateReturnType(body As BoundStatement) As TypeSymbol Select Case body.Kind Case BoundKind.ReturnStatement Return DirectCast(body, BoundReturnStatement).ExpressionOpt.Type Case BoundKind.ExpressionStatement, BoundKind.RedimStatement Return _voidType Case Else Throw ExceptionUtilities.UnexpectedValue(body.Kind) End Select End Function Friend Overrides Sub AddSynthesizedReturnTypeAttributes(ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedReturnTypeAttributes(attributes) Dim returnType = Me.ReturnType If returnType.ContainsTupleNames() AndAlso DeclaringCompilation.HasTupleNamesAttributes() Then AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(returnType)) End If End Sub Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Return localPosition End Function Friend Overrides ReadOnly Property PreserveOriginalLocals As Boolean Get Return True End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/CSharp/Portable/BoundTree/BoundDagRelationalTest.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.CSharp { internal sealed partial class BoundDagRelationalTest { public BinaryOperatorKind Relation => OperatorKind.Operator(); } }
// 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.CSharp { internal sealed partial class BoundDagRelationalTest { public BinaryOperatorKind Relation => OperatorKind.Operator(); } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/Core/Portable/CodeRefactorings/ICodeRefactoringProviderFactory.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.CodeRefactorings { internal interface ICodeRefactoringProviderFactory { ImmutableArray<CodeRefactoringProvider> GetRefactorings(); } }
// 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.CodeRefactorings { internal interface ICodeRefactoringProviderFactory { ImmutableArray<CodeRefactoringProvider> GetRefactorings(); } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/WinMdTests.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.Reflection.Metadata Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class WinMdTests Inherits ExpressionCompilerTestBase ''' <summary> ''' Handle runtime assemblies rather than Windows.winmd ''' (compile-time assembly) since those are the assemblies ''' loaded in the debuggee. ''' </summary> <WorkItem(981104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981104")> <ConditionalFact(GetType(OSVersionWin8))> Public Sub Win8RuntimeAssemblies() Const source = "Class C Shared Sub M(f As Windows.Storage.StorageFolder, p As Windows.Foundation.Collections.PropertySet) End Sub End Class" Dim comp = CreateEmptyCompilation({source}, options:=TestOptions.DebugDll, references:=WinRtRefs) Dim runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections") Assert.True(runtimeAssemblies.Length >= 2) ' no reference to Windows.winmd WithRuntimeInstance(comp, {MscorlibRef}.Concat(runtimeAssemblies), Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("If(p Is Nothing, f, Nothing)", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0005 IL_0003: ldnull IL_0004: ret IL_0005: ldarg.0 IL_0006: ret }") End Sub) End Sub <Fact> Public Sub Win8OnWin8() CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.WindowsData)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), "Windows.Storage") End Sub <Fact> Public Sub Win8OnWin10() CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsData)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), "Windows.Storage") End Sub <Fact> Public Sub Win10OnWin10() CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsData)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), "Windows") End Sub Private Sub CompileTimeAndRuntimeAssemblies( compileReferences As ImmutableArray(Of MetadataReference), runtimeReferences As ImmutableArray(Of MetadataReference), storageAssemblyName As String) Const source = "Class C Shared Sub M(a As LibraryA.A, b As LibraryB.B, t As Windows.Data.Text.TextSegment, f As Windows.Storage.StorageFolder) End Sub End Class" Dim c0 = CreateEmptyCompilation({source}, compileReferences, TestOptions.DebugDll) WithRuntimeInstance(c0, runtimeReferences, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("If(a, If(b, If(t, f)))", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0010 IL_0004: pop IL_0005: ldarg.1 IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.2 IL_000b: dup IL_000c: brtrue.s IL_0010 IL_000e: pop IL_000f: ldarg.3 IL_0010: ret }") testData = New CompilationTestData() Dim result = context.CompileExpression("f", errorMessage, testData) Assert.Null(errorMessage) Dim methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.3 IL_0001: ret }") ' Check return type is from runtime assembly. Dim assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference() Dim comp = VisualBasicCompilation.Create( assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName(), references:=runtimeReferences.Concat(ImmutableArray.Create(Of MetadataReference)(assemblyReference))) Using metadata = ModuleMetadata.CreateFromImage(result.Assembly) Dim reader = metadata.MetadataReader Dim typeDef = reader.GetTypeDef("<>x") Dim methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0") Dim [module] = DirectCast(comp.GetMember("<>x").ContainingModule, PEModuleSymbol) Dim metadataDecoder = New MetadataDecoder([module]) Dim signatureHeader As SignatureHeader = Nothing Dim metadataException As BadImageFormatException = Nothing Dim parameters = metadataDecoder.GetSignatureForMethod(methodHandle, signatureHeader, metadataException) Assert.Equal(parameters.Length, 5) Dim actualReturnType = parameters(0).Type Assert.Equal(actualReturnType.TypeKind, TypeKind.Class) ' not error Dim expectedReturnType = comp.GetMember("Windows.Storage.StorageFolder") Assert.Equal(expectedReturnType, actualReturnType) Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name) End Using End Sub) End Sub ''' <summary> ''' Assembly-qualified name containing "ContentType=WindowsRuntime", ''' and referencing runtime assembly. ''' </summary> <WorkItem(1116143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116143")> <ConditionalFact(GetType(OSVersionWin8))> Public Sub AssemblyQualifiedName() Const source = "Class C Shared Sub M(f As Windows.Storage.StorageFolder, p As Windows.Foundation.Collections.PropertySet) End Sub End Class" Dim comp = CreateEmptyCompilation({source}, WinRtRefs, TestOptions.DebugDll) Dim runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections") WithRuntimeInstance(comp, {MscorlibRef}.Concat(runtimeAssemblies), Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim aliases = ImmutableArray.Create( VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"), VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime")) Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "If(DirectCast(s.Attributes, Object), d.UniversalTime)", DkmEvaluationFlags.TreatAsExpression, aliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Function Windows.Storage.StorageFolder.get_Attributes() As Windows.Storage.FileAttributes"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""Windows.Foundation.DateTime.UniversalTime As Long"" IL_0031: box ""Long"" IL_0036: ret }") End Sub) End Sub Private Shared Function ToVersion1_3(bytes As Byte()) As Byte() Return ExpressionCompilerTestHelpers.ToVersion1_3(bytes) End Function Private Shared Function ToVersion1_4(bytes As Byte()) As Byte() Return ExpressionCompilerTestHelpers.ToVersion1_4(bytes) 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.Collections.Immutable Imports System.Reflection.Metadata Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class WinMdTests Inherits ExpressionCompilerTestBase ''' <summary> ''' Handle runtime assemblies rather than Windows.winmd ''' (compile-time assembly) since those are the assemblies ''' loaded in the debuggee. ''' </summary> <WorkItem(981104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981104")> <ConditionalFact(GetType(OSVersionWin8))> Public Sub Win8RuntimeAssemblies() Const source = "Class C Shared Sub M(f As Windows.Storage.StorageFolder, p As Windows.Foundation.Collections.PropertySet) End Sub End Class" Dim comp = CreateEmptyCompilation({source}, options:=TestOptions.DebugDll, references:=WinRtRefs) Dim runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections") Assert.True(runtimeAssemblies.Length >= 2) ' no reference to Windows.winmd WithRuntimeInstance(comp, {MscorlibRef}.Concat(runtimeAssemblies), Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("If(p Is Nothing, f, Nothing)", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0005 IL_0003: ldnull IL_0004: ret IL_0005: ldarg.0 IL_0006: ret }") End Sub) End Sub <Fact> Public Sub Win8OnWin8() CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.WindowsData)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), "Windows.Storage") End Sub <Fact> Public Sub Win8OnWin10() CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsData)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), "Windows.Storage") End Sub <Fact> Public Sub Win10OnWin10() CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsData)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), "Windows") End Sub Private Sub CompileTimeAndRuntimeAssemblies( compileReferences As ImmutableArray(Of MetadataReference), runtimeReferences As ImmutableArray(Of MetadataReference), storageAssemblyName As String) Const source = "Class C Shared Sub M(a As LibraryA.A, b As LibraryB.B, t As Windows.Data.Text.TextSegment, f As Windows.Storage.StorageFolder) End Sub End Class" Dim c0 = CreateEmptyCompilation({source}, compileReferences, TestOptions.DebugDll) WithRuntimeInstance(c0, runtimeReferences, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("If(a, If(b, If(t, f)))", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0010 IL_0004: pop IL_0005: ldarg.1 IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.2 IL_000b: dup IL_000c: brtrue.s IL_0010 IL_000e: pop IL_000f: ldarg.3 IL_0010: ret }") testData = New CompilationTestData() Dim result = context.CompileExpression("f", errorMessage, testData) Assert.Null(errorMessage) Dim methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.3 IL_0001: ret }") ' Check return type is from runtime assembly. Dim assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference() Dim comp = VisualBasicCompilation.Create( assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName(), references:=runtimeReferences.Concat(ImmutableArray.Create(Of MetadataReference)(assemblyReference))) Using metadata = ModuleMetadata.CreateFromImage(result.Assembly) Dim reader = metadata.MetadataReader Dim typeDef = reader.GetTypeDef("<>x") Dim methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0") Dim [module] = DirectCast(comp.GetMember("<>x").ContainingModule, PEModuleSymbol) Dim metadataDecoder = New MetadataDecoder([module]) Dim signatureHeader As SignatureHeader = Nothing Dim metadataException As BadImageFormatException = Nothing Dim parameters = metadataDecoder.GetSignatureForMethod(methodHandle, signatureHeader, metadataException) Assert.Equal(parameters.Length, 5) Dim actualReturnType = parameters(0).Type Assert.Equal(actualReturnType.TypeKind, TypeKind.Class) ' not error Dim expectedReturnType = comp.GetMember("Windows.Storage.StorageFolder") Assert.Equal(expectedReturnType, actualReturnType) Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name) End Using End Sub) End Sub ''' <summary> ''' Assembly-qualified name containing "ContentType=WindowsRuntime", ''' and referencing runtime assembly. ''' </summary> <WorkItem(1116143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116143")> <ConditionalFact(GetType(OSVersionWin8))> Public Sub AssemblyQualifiedName() Const source = "Class C Shared Sub M(f As Windows.Storage.StorageFolder, p As Windows.Foundation.Collections.PropertySet) End Sub End Class" Dim comp = CreateEmptyCompilation({source}, WinRtRefs, TestOptions.DebugDll) Dim runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections") WithRuntimeInstance(comp, {MscorlibRef}.Concat(runtimeAssemblies), Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim aliases = ImmutableArray.Create( VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"), VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime")) Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "If(DirectCast(s.Attributes, Object), d.UniversalTime)", DkmEvaluationFlags.TreatAsExpression, aliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Function Windows.Storage.StorageFolder.get_Attributes() As Windows.Storage.FileAttributes"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""Windows.Foundation.DateTime.UniversalTime As Long"" IL_0031: box ""Long"" IL_0036: ret }") End Sub) End Sub Private Shared Function ToVersion1_3(bytes As Byte()) As Byte() Return ExpressionCompilerTestHelpers.ToVersion1_3(bytes) End Function Private Shared Function ToVersion1_4(bytes As Byte()) As Byte() Return ExpressionCompilerTestHelpers.ToVersion1_4(bytes) End Function End Class End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Tools/BuildBoss/PackageReference.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.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { internal struct PackageReference { internal string Name { get; } internal string Version { get; } internal PackageReference(string name, string version) { Name = name; Version = version; } public override string ToString() => $"{Name} - {Version}"; } }
// 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.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { internal struct PackageReference { internal string Name { get; } internal string Version { get; } internal PackageReference(string name, string version) { Name = name; Version = version; } public override string ToString() => $"{Name} - {Version}"; } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Analyzers/CSharp/Tests/UseExplicitTupleName/UseExplicitTupleNameTests.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.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UseExplicitTupleName; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExplicitTupleName { public class UseExplicitTupleNameTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseExplicitTupleNameTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExplicitTupleNameDiagnosticAnalyzer(), new UseExplicitTupleNameCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestNamedTuple1() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.i; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestInArgument() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); Goo(v1.[|Item1|]); } void Goo(int i) { } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); Goo(v1.i); } void Goo(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestNamedTuple2() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|Item2|]; } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestMissingOnMatchingName1() { await TestMissingInRegularAndScriptAsync( @" class C { void M() { (int, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestMissingOnMatchingName2() { await TestMissingInRegularAndScriptAsync( @" class C { void M() { (int Item1, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestWrongCasing() { await TestInRegularAndScriptAsync( @" class C { void M() { (int item1, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }", @" class C { void M() { (int item1, string s) v1 = default((int, string)); var v2 = v1.item1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.{|FixAllInDocument:Item1|}; var v3 = v1.Item2; } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.i; var v3 = v1.s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, int s) v1 = default((int, int)); v1.{|FixAllInDocument:Item1|} = v1.Item2; } }", @" class C { void M() { (int i, int s) v1 = default((int, int)); v1.i = v1.s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFalseOptionImplicitTuple() { await TestDiagnosticMissingAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferExplicitTupleNames, false, NotificationOption2.Warning))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFalseOptionExplicitTuple() { await TestDiagnosticMissingAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|i|]; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferExplicitTupleNames, false, NotificationOption2.Warning))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestOnRestField() { var valueTuple8 = @" namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { } } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> where TRest : struct { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { } } } "; await TestDiagnosticMissingAsync( @" class C { void M() { (int, int, int, int, int, int, int, int) x = default; _ = x.[|Rest|]; } }" + valueTuple8); } } }
// 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.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UseExplicitTupleName; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExplicitTupleName { public class UseExplicitTupleNameTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseExplicitTupleNameTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExplicitTupleNameDiagnosticAnalyzer(), new UseExplicitTupleNameCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestNamedTuple1() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.i; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestInArgument() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); Goo(v1.[|Item1|]); } void Goo(int i) { } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); Goo(v1.i); } void Goo(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestNamedTuple2() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|Item2|]; } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestMissingOnMatchingName1() { await TestMissingInRegularAndScriptAsync( @" class C { void M() { (int, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestMissingOnMatchingName2() { await TestMissingInRegularAndScriptAsync( @" class C { void M() { (int Item1, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestWrongCasing() { await TestInRegularAndScriptAsync( @" class C { void M() { (int item1, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }", @" class C { void M() { (int item1, string s) v1 = default((int, string)); var v2 = v1.item1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.{|FixAllInDocument:Item1|}; var v3 = v1.Item2; } }", @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.i; var v3 = v1.s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @" class C { void M() { (int i, int s) v1 = default((int, int)); v1.{|FixAllInDocument:Item1|} = v1.Item2; } }", @" class C { void M() { (int i, int s) v1 = default((int, int)); v1.i = v1.s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFalseOptionImplicitTuple() { await TestDiagnosticMissingAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferExplicitTupleNames, false, NotificationOption2.Warning))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestFalseOptionExplicitTuple() { await TestDiagnosticMissingAsync( @" class C { void M() { (int i, string s) v1 = default((int, string)); var v2 = v1.[|i|]; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferExplicitTupleNames, false, NotificationOption2.Warning))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] public async Task TestOnRestField() { var valueTuple8 = @" namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { } } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> where TRest : struct { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { } } } "; await TestDiagnosticMissingAsync( @" class C { void M() { (int, int, int, int, int, int, int, int) x = default; _ = x.[|Rest|]; } }" + valueTuple8); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Workspaces/Core/Portable/Workspace/Solution/Checksum.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.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Checksum of data can be used later to see whether two data are same or not /// without actually comparing data itself /// </summary> [DataContract] internal sealed partial class Checksum : IObjectWritable, IEquatable<Checksum> { /// <summary> /// The intended size of the <see cref="HashData"/> structure. /// </summary> public const int HashSize = 20; public static readonly Checksum Null = new(default); [DataMember(Order = 0)] private readonly HashData _checksum; public Checksum(HashData hash) => _checksum = hash; /// <summary> /// Create Checksum from given byte array. if byte array is bigger than <see cref="HashSize"/>, it will be /// truncated to the size. /// </summary> public static Checksum From(byte[] checksum) => From(checksum.AsSpan()); /// <summary> /// Create Checksum from given byte array. if byte array is bigger than <see cref="HashSize"/>, it will be /// truncated to the size. /// </summary> public static Checksum From(ImmutableArray<byte> checksum) => From(checksum.AsSpan()); public static Checksum From(ReadOnlySpan<byte> checksum) { if (checksum.Length == 0) return Null; if (checksum.Length < HashSize) throw new ArgumentException($"checksum must be equal or bigger than the hash size: {HashSize}", nameof(checksum)); Contract.ThrowIfFalse(MemoryMarshal.TryRead(checksum, out HashData hash)); return new Checksum(hash); } public bool Equals(Checksum other) { return other != null && _checksum == other._checksum; } public override bool Equals(object obj) => Equals(obj as Checksum); public override int GetHashCode() => _checksum.GetHashCode(); public string ToBase64String() { #if NETCOREAPP Span<byte> bytes = stackalloc byte[HashSize]; this.WriteTo(bytes); return Convert.ToBase64String(bytes); #else unsafe { var data = new byte[HashSize]; fixed (byte* dataPtr = data) { *(HashData*)dataPtr = _checksum; } return Convert.ToBase64String(data, 0, HashSize); } #endif } public static Checksum FromBase64String(string value) => value == null ? null : From(Convert.FromBase64String(value)); public override string ToString() => ToBase64String(); public static bool operator ==(Checksum left, Checksum right) => EqualityComparer<Checksum>.Default.Equals(left, right); public static bool operator !=(Checksum left, Checksum right) => !(left == right); public static bool operator ==(Checksum left, HashData right) => left._checksum == right; public static bool operator !=(Checksum left, HashData right) => !(left == right); bool IObjectWritable.ShouldReuseInSerialization => true; public void WriteTo(ObjectWriter writer) => _checksum.WriteTo(writer); public void WriteTo(Span<byte> span) { Contract.ThrowIfFalse(span.Length >= HashSize); Contract.ThrowIfFalse(MemoryMarshal.TryWrite(span, ref Unsafe.AsRef(in _checksum))); } public static Checksum ReadFrom(ObjectReader reader) => new(HashData.ReadFrom(reader)); public static Func<Checksum, string> GetChecksumLogInfo { get; } = checksum => checksum.ToString(); public static Func<IEnumerable<Checksum>, string> GetChecksumsLogInfo { get; } = checksums => string.Join("|", checksums.Select(c => c.ToString())); /// <summary> /// This structure stores the 20-byte hash as an inline value rather than requiring the use of /// <c>byte[]</c>. /// </summary> [DataContract] [StructLayout(LayoutKind.Explicit, Size = HashSize)] public readonly struct HashData : IEquatable<HashData> { [FieldOffset(0), DataMember(Order = 0)] private readonly long Data1; [FieldOffset(8), DataMember(Order = 1)] private readonly long Data2; [FieldOffset(16), DataMember(Order = 2)] private readonly int Data3; public HashData(long data1, long data2, int data3) { Data1 = data1; Data2 = data2; Data3 = data3; } public static bool operator ==(HashData x, HashData y) => x.Equals(y); public static bool operator !=(HashData x, HashData y) => !(x == y); public void WriteTo(ObjectWriter writer) { writer.WriteInt64(Data1); writer.WriteInt64(Data2); writer.WriteInt32(Data3); } public static unsafe HashData FromPointer(HashData* hash) => new(hash->Data1, hash->Data2, hash->Data3); public static HashData ReadFrom(ObjectReader reader) => new(reader.ReadInt64(), reader.ReadInt64(), reader.ReadInt32()); public override int GetHashCode() { // The checksum is already a hash. Just read a 4-byte value to get a well-distributed hash code. return (int)Data1; } public override bool Equals(object obj) => obj is HashData other && Equals(other); public bool Equals(HashData other) { return Data1 == other.Data1 && Data2 == other.Data2 && Data3 == other.Data3; } } } }
// 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.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Checksum of data can be used later to see whether two data are same or not /// without actually comparing data itself /// </summary> [DataContract] internal sealed partial class Checksum : IObjectWritable, IEquatable<Checksum> { /// <summary> /// The intended size of the <see cref="HashData"/> structure. /// </summary> public const int HashSize = 20; public static readonly Checksum Null = new(default); [DataMember(Order = 0)] private readonly HashData _checksum; public Checksum(HashData hash) => _checksum = hash; /// <summary> /// Create Checksum from given byte array. if byte array is bigger than <see cref="HashSize"/>, it will be /// truncated to the size. /// </summary> public static Checksum From(byte[] checksum) => From(checksum.AsSpan()); /// <summary> /// Create Checksum from given byte array. if byte array is bigger than <see cref="HashSize"/>, it will be /// truncated to the size. /// </summary> public static Checksum From(ImmutableArray<byte> checksum) => From(checksum.AsSpan()); public static Checksum From(ReadOnlySpan<byte> checksum) { if (checksum.Length == 0) return Null; if (checksum.Length < HashSize) throw new ArgumentException($"checksum must be equal or bigger than the hash size: {HashSize}", nameof(checksum)); Contract.ThrowIfFalse(MemoryMarshal.TryRead(checksum, out HashData hash)); return new Checksum(hash); } public bool Equals(Checksum other) { return other != null && _checksum == other._checksum; } public override bool Equals(object obj) => Equals(obj as Checksum); public override int GetHashCode() => _checksum.GetHashCode(); public string ToBase64String() { #if NETCOREAPP Span<byte> bytes = stackalloc byte[HashSize]; this.WriteTo(bytes); return Convert.ToBase64String(bytes); #else unsafe { var data = new byte[HashSize]; fixed (byte* dataPtr = data) { *(HashData*)dataPtr = _checksum; } return Convert.ToBase64String(data, 0, HashSize); } #endif } public static Checksum FromBase64String(string value) => value == null ? null : From(Convert.FromBase64String(value)); public override string ToString() => ToBase64String(); public static bool operator ==(Checksum left, Checksum right) => EqualityComparer<Checksum>.Default.Equals(left, right); public static bool operator !=(Checksum left, Checksum right) => !(left == right); public static bool operator ==(Checksum left, HashData right) => left._checksum == right; public static bool operator !=(Checksum left, HashData right) => !(left == right); bool IObjectWritable.ShouldReuseInSerialization => true; public void WriteTo(ObjectWriter writer) => _checksum.WriteTo(writer); public void WriteTo(Span<byte> span) { Contract.ThrowIfFalse(span.Length >= HashSize); Contract.ThrowIfFalse(MemoryMarshal.TryWrite(span, ref Unsafe.AsRef(in _checksum))); } public static Checksum ReadFrom(ObjectReader reader) => new(HashData.ReadFrom(reader)); public static Func<Checksum, string> GetChecksumLogInfo { get; } = checksum => checksum.ToString(); public static Func<IEnumerable<Checksum>, string> GetChecksumsLogInfo { get; } = checksums => string.Join("|", checksums.Select(c => c.ToString())); /// <summary> /// This structure stores the 20-byte hash as an inline value rather than requiring the use of /// <c>byte[]</c>. /// </summary> [DataContract] [StructLayout(LayoutKind.Explicit, Size = HashSize)] public readonly struct HashData : IEquatable<HashData> { [FieldOffset(0), DataMember(Order = 0)] private readonly long Data1; [FieldOffset(8), DataMember(Order = 1)] private readonly long Data2; [FieldOffset(16), DataMember(Order = 2)] private readonly int Data3; public HashData(long data1, long data2, int data3) { Data1 = data1; Data2 = data2; Data3 = data3; } public static bool operator ==(HashData x, HashData y) => x.Equals(y); public static bool operator !=(HashData x, HashData y) => !(x == y); public void WriteTo(ObjectWriter writer) { writer.WriteInt64(Data1); writer.WriteInt64(Data2); writer.WriteInt32(Data3); } public static unsafe HashData FromPointer(HashData* hash) => new(hash->Data1, hash->Data2, hash->Data3); public static HashData ReadFrom(ObjectReader reader) => new(reader.ReadInt64(), reader.ReadInt64(), reader.ReadInt32()); public override int GetHashCode() { // The checksum is already a hash. Just read a 4-byte value to get a well-distributed hash code. return (int)Data1; } public override bool Equals(object obj) => obj is HashData other && Equals(other); public bool Equals(HashData other) { return Data1 == other.Data1 && Data2 == other.Data2 && Data3 == other.Data3; } } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/CSharp/Test/Emit/PDB/PDBConstantTests.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.Globalization; using System.IO; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBConstantTests : CSharpTestBase { [Fact] public void StringsWithSurrogateChar() { var source = @" using System; public class T { public static void Main() { const string HighSurrogateCharacter = ""\uD800""; const string LowSurrogateCharacter = ""\uDC00""; const string MatchedSurrogateCharacters = ""\uD800\uDC00""; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Note: U+FFFD is the Unicode 'replacement character' point and is used to replace an incoming character // whose value is unknown or unrepresentable in Unicode. This is what our pdb writer does with // unpaired surrogates. c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <constant name=""HighSurrogateCharacter"" value=""\uFFFD"" type=""String"" /> <constant name=""LowSurrogateCharacter"" value=""\uFFFD"" type=""String"" /> <constant name=""MatchedSurrogateCharacters"" value=""\uD800\uDC00"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""HighSurrogateCharacter"" value=""\uD800"" type=""String"" /> <constant name=""LowSurrogateCharacter"" value=""\uDC00"" type=""String"" /> <constant name=""MatchedSurrogateCharacters"" value=""\uD800\uDC00"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(546862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546862")] [Fact] public void InvalidUnicodeString() { var source = @" using System; public class T { public static void Main() { const string invalidUnicodeString = ""\uD800\0\uDC00""; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Note: U+FFFD is the Unicode 'replacement character' point and is used to replace an incoming character // whose value is unknown or unrepresentable in Unicode. This is what our pdb writer does with // unpaired surrogates. c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <constant name=""invalidUnicodeString"" value=""\uFFFD\u0000\uFFFD"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""invalidUnicodeString"" value=""\uD800\u0000\uDC00"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [Fact] public void AllTypes() { var source = @" using System; using System.Collections.Generic; class X {} public class C<S> { enum EnumI1 : sbyte { A } enum EnumU1 : byte { A } enum EnumI2 : short { A } enum EnumU2 : ushort { A } enum EnumI4 : int { A } enum EnumU4 : uint { A } enum EnumI8 : long { A } enum EnumU8 : ulong { A } public static void F<T>() { const bool B = false; const char C = '\0'; const sbyte I1 = 0; const byte U1 = 0; const short I2 = 0; const ushort U2 = 0; const int I4 = 0; const uint U4 = 0; const long I8 = 0; const ulong U8 = 0; const float R4 = 0; const double R8 = 0; const C<int>.EnumI1 EI1 = 0; const C<int>.EnumU1 EU1 = 0; const C<int>.EnumI2 EI2 = 0; const C<int>.EnumU2 EU2 = 0; const C<int>.EnumI4 EI4 = 0; const C<int>.EnumU4 EU4 = 0; const C<int>.EnumI8 EI8 = 0; const C<int>.EnumU8 EU8 = 0; const string StrWithNul = ""\0""; const string EmptyStr = """"; const string NullStr = null; const object NullObject = null; const dynamic NullDynamic = null; const X NullTypeDef = null; const Action NullTypeRef = null; const Func<Dictionary<int, C<int>>, dynamic, T, List<S>> NullTypeSpec = null; const object[] Array1 = null; const object[,] Array2 = null; const object[][] Array3 = null; const decimal D = 0M; // DateTime const not expressible in C# } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C`1.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C`1"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""NullDynamic"" /> <bucket flags=""000001000"" slotId=""0"" localName=""NullTypeSpec"" /> </dynamicLocals> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""56"" startColumn=""5"" endLine=""56"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <constant name=""B"" value=""0"" type=""Boolean"" /> <constant name=""C"" value=""0"" type=""Char"" /> <constant name=""I1"" value=""0"" type=""SByte"" /> <constant name=""U1"" value=""0"" type=""Byte"" /> <constant name=""I2"" value=""0"" type=""Int16"" /> <constant name=""U2"" value=""0"" type=""UInt16"" /> <constant name=""I4"" value=""0"" type=""Int32"" /> <constant name=""U4"" value=""0"" type=""UInt32"" /> <constant name=""I8"" value=""0"" type=""Int64"" /> <constant name=""U8"" value=""0"" type=""UInt64"" /> <constant name=""R4"" value=""0x00000000"" type=""Single"" /> <constant name=""R8"" value=""0x0000000000000000"" type=""Double"" /> <constant name=""EI1"" value=""0"" signature=""EnumI1{Int32}"" /> <constant name=""EU1"" value=""0"" signature=""EnumU1{Int32}"" /> <constant name=""EI2"" value=""0"" signature=""EnumI2{Int32}"" /> <constant name=""EU2"" value=""0"" signature=""EnumU2{Int32}"" /> <constant name=""EI4"" value=""0"" signature=""EnumI4{Int32}"" /> <constant name=""EU4"" value=""0"" signature=""EnumU4{Int32}"" /> <constant name=""EI8"" value=""0"" signature=""EnumI8{Int32}"" /> <constant name=""EU8"" value=""0"" signature=""EnumU8{Int32}"" /> <constant name=""StrWithNul"" value=""\u0000"" type=""String"" /> <constant name=""EmptyStr"" value="""" type=""String"" /> <constant name=""NullStr"" value=""null"" type=""String"" /> <constant name=""NullObject"" value=""null"" type=""Object"" /> <constant name=""NullDynamic"" value=""null"" type=""Object"" /> <constant name=""NullTypeDef"" value=""null"" signature=""X"" /> <constant name=""NullTypeRef"" value=""null"" signature=""System.Action"" /> <constant name=""NullTypeSpec"" value=""null"" signature=""System.Func`4{System.Collections.Generic.Dictionary`2{Int32, C`1{Int32}}, Object, !!0, System.Collections.Generic.List`1{!0}}"" /> <constant name=""Array1"" value=""null"" signature=""Object[]"" /> <constant name=""Array2"" value=""null"" signature=""Object[,,]"" /> <constant name=""Array3"" value=""null"" signature=""Object[][]"" /> <constant name=""D"" value=""0"" type=""Decimal"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void SimpleLocalConstant() { var text = @" class C { void M() { const int x = 1; { const int y = 2; } } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <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=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <constant name=""x"" value=""1"" type=""Int32"" /> <scope startOffset=""0x1"" endOffset=""0x3""> <constant name=""y"" value=""2"" type=""Int32"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void LambdaLocalConstants() { var text = WithWindowsLineBreaks(@" using System; class C { void M(Action a) { const int x = 1; M(() => { const int y = 2; { const int z = 3; } }); } } "); var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""a""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""54"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""15"" endColumn=""12"" document=""1"" /> <entry offset=""0x27"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x28""> <namespace name=""System"" /> <constant name=""x"" value=""1"" type=""Int32"" /> </scope> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_0""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" parameterNames=""a"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x2"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x3"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <constant name=""y"" value=""2"" type=""Int32"" /> <scope startOffset=""0x1"" endOffset=""0x3""> <constant name=""z"" value=""3"" type=""Int32"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(543342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543342")] [Fact] public void IteratorLocalConstants() { var source = WithWindowsLineBreaks(@" using System.Collections.Generic; class C { IEnumerable<int> M() { const int x = 1; for (int i = 0; i < 10; i++) { const int y = 2; yield return x + y + i; } } } "); // NOTE: Roslyn's output is somewhat different than Dev10's in this case, but // all of the changes look reasonable. The main thing for this test is that // Dev10 creates fields for the locals in the iterator class. Roslyn doesn't // do that - the <constant> in the <scope> is sufficient. var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<>4__this", "<i>5__1" }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x20"" endOffset=""0x67"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> <slot kind=""1"" offset=""37"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x20"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x27"" hidden=""true"" document=""1"" /> <entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x2a"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""36"" document=""1"" /> <entry offset=""0x41"" hidden=""true"" document=""1"" /> <entry offset=""0x48"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x49"" startLine=""9"" startColumn=""33"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0x59"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""31"" document=""1"" /> <entry offset=""0x64"" hidden=""true"" document=""1"" /> <entry offset=""0x67"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x69""> <namespace name=""System.Collections.Generic"" /> <scope startOffset=""0x1f"" endOffset=""0x69""> <constant name=""x"" value=""1"" type=""Int32"" /> <scope startOffset=""0x29"" endOffset=""0x49""> <constant name=""y"" value=""2"" type=""Int32"" /> </scope> </scope> </scope> </method> </methods> </symbols>"); } [Fact] [WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")] public void LocalConstantsTypes() { var text = @" class C { void M() { const object o = null; const string s = ""hello""; const float f = float.MinValue; const double d = double.MaxValue; } } "; using (new CultureContext(new CultureInfo("en-US", useUserOverride: false))) { CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <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=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""o"" value=""null"" type=""Object"" /> <constant name=""s"" value=""hello"" type=""String"" /> <constant name=""f"" value=""0xFF7FFFFF"" type=""Single"" /> <constant name=""d"" value=""0x7FEFFFFFFFFFFFFF"" type=""Double"" /> </scope> </method> </methods> </symbols>"); } } [Fact] public void WRN_PDBConstantStringValueTooLong() { var longStringValue = new string('a', 2049); var source = @" using System; class C { static void Main() { const string goo = """ + longStringValue + @"""; Console.Write(goo); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); var exebits = new MemoryStream(); var pdbbits = new MemoryStream(); var result = compilation.Emit(exebits, pdbbits); result.Diagnostics.Verify(); // old behavior. This new warning was abandoned // // result.Diagnostics.Verify(// warning CS7063: Constant string value of 'goo' is too long to be used in a PDB file. Only the debug experience may be affected. // Diagnostic(ErrorCode.WRN_PDBConstantStringValueTooLong).WithArguments("goo", longStringValue.Substring(0, 20) + "...")); // // //make sure that this warning is suppressable // compilation = CreateCompilationWithMscorlib(text, compOptions: Options.Exe.WithDebugInformationKind(Common.DebugInformationKind.Full).WithOptimizations(false). // WithSpecificDiagnosticOptions(new Dictionary<int, ReportWarning>(){ {(int)ErrorCode.WRN_PDBConstantStringValueTooLong, ReportWarning.Suppress} })); // // result = compilation.Emit(exebits, null, "DontCare", pdbbits, null); // result.Diagnostics.Verify(); // // //make sure that this warning can be turned into an error. // compilation = CreateCompilationWithMscorlib(text, compOptions: Options.Exe.WithDebugInformationKind(Common.DebugInformationKind.Full).WithOptimizations(false). // WithSpecificDiagnosticOptions(new Dictionary<int, ReportWarning>() { { (int)ErrorCode.WRN_PDBConstantStringValueTooLong, ReportWarning.Error } })); // // result = compilation.Emit(exebits, null, "DontCare", pdbbits, null); // Assert.False(result.Success); // result.Diagnostics.Verify( // Diagnostic(ErrorCode.WRN_PDBConstantStringValueTooLong).WithArguments("goo", longStringValue.Substring(0, 20) + "...").WithWarningAsError(true)); } [Fact] public void StringConstantTooLong() { var text = WithWindowsLineBreaks(@" class C { void M() { const string text = @"" this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB""; } } "); var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <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=""43"" startColumn=""5"" endLine=""43"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""43"" startColumn=""5"" endLine=""43"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""text"" value=""\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(178988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/178988")] [Fact] public void StringWithNulCharacter_MaxSupportedLength() { const int length = 2031; string str = new string('x', 9) + "\0" + new string('x', length - 10); string text = @" class C { void M() { const string x = """ + str + @"""; } } "; var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <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=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""x"" value=""" + str.Replace("\0", @"\u0000") + @""" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""x"" value=""" + str.Replace("\0", @"\u0000") + @""" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(178988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/178988")] [Fact] public void StringWithNulCharacter_OverSupportedLength() { const int length = 2032; string str = new string('x', 9) + "\0" + new string('x', length - 10); string text = @" class C { void M() { const string x = """ + str + @"""; } } "; var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <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=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""x"" value=""" + str.Replace("\0", @"\u0000") + @""" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [Fact] public void DecimalLocalConstants() { var text = @" class C { void M() { const decimal d = (decimal)1.5; } } "; using (new CultureContext(new CultureInfo("en-US", useUserOverride: false))) { CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <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=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""d"" value=""1.5"" type=""Decimal"" /> </scope> </method> </methods> </symbols>"); } } } }
// 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.Globalization; using System.IO; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBConstantTests : CSharpTestBase { [Fact] public void StringsWithSurrogateChar() { var source = @" using System; public class T { public static void Main() { const string HighSurrogateCharacter = ""\uD800""; const string LowSurrogateCharacter = ""\uDC00""; const string MatchedSurrogateCharacters = ""\uD800\uDC00""; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Note: U+FFFD is the Unicode 'replacement character' point and is used to replace an incoming character // whose value is unknown or unrepresentable in Unicode. This is what our pdb writer does with // unpaired surrogates. c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <constant name=""HighSurrogateCharacter"" value=""\uFFFD"" type=""String"" /> <constant name=""LowSurrogateCharacter"" value=""\uFFFD"" type=""String"" /> <constant name=""MatchedSurrogateCharacters"" value=""\uD800\uDC00"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""HighSurrogateCharacter"" value=""\uD800"" type=""String"" /> <constant name=""LowSurrogateCharacter"" value=""\uDC00"" type=""String"" /> <constant name=""MatchedSurrogateCharacters"" value=""\uD800\uDC00"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(546862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546862")] [Fact] public void InvalidUnicodeString() { var source = @" using System; public class T { public static void Main() { const string invalidUnicodeString = ""\uD800\0\uDC00""; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Note: U+FFFD is the Unicode 'replacement character' point and is used to replace an incoming character // whose value is unknown or unrepresentable in Unicode. This is what our pdb writer does with // unpaired surrogates. c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <constant name=""invalidUnicodeString"" value=""\uFFFD\u0000\uFFFD"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""invalidUnicodeString"" value=""\uD800\u0000\uDC00"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [Fact] public void AllTypes() { var source = @" using System; using System.Collections.Generic; class X {} public class C<S> { enum EnumI1 : sbyte { A } enum EnumU1 : byte { A } enum EnumI2 : short { A } enum EnumU2 : ushort { A } enum EnumI4 : int { A } enum EnumU4 : uint { A } enum EnumI8 : long { A } enum EnumU8 : ulong { A } public static void F<T>() { const bool B = false; const char C = '\0'; const sbyte I1 = 0; const byte U1 = 0; const short I2 = 0; const ushort U2 = 0; const int I4 = 0; const uint U4 = 0; const long I8 = 0; const ulong U8 = 0; const float R4 = 0; const double R8 = 0; const C<int>.EnumI1 EI1 = 0; const C<int>.EnumU1 EU1 = 0; const C<int>.EnumI2 EI2 = 0; const C<int>.EnumU2 EU2 = 0; const C<int>.EnumI4 EI4 = 0; const C<int>.EnumU4 EU4 = 0; const C<int>.EnumI8 EI8 = 0; const C<int>.EnumU8 EU8 = 0; const string StrWithNul = ""\0""; const string EmptyStr = """"; const string NullStr = null; const object NullObject = null; const dynamic NullDynamic = null; const X NullTypeDef = null; const Action NullTypeRef = null; const Func<Dictionary<int, C<int>>, dynamic, T, List<S>> NullTypeSpec = null; const object[] Array1 = null; const object[,] Array2 = null; const object[][] Array3 = null; const decimal D = 0M; // DateTime const not expressible in C# } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C`1.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C`1"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""NullDynamic"" /> <bucket flags=""000001000"" slotId=""0"" localName=""NullTypeSpec"" /> </dynamicLocals> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""56"" startColumn=""5"" endLine=""56"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <constant name=""B"" value=""0"" type=""Boolean"" /> <constant name=""C"" value=""0"" type=""Char"" /> <constant name=""I1"" value=""0"" type=""SByte"" /> <constant name=""U1"" value=""0"" type=""Byte"" /> <constant name=""I2"" value=""0"" type=""Int16"" /> <constant name=""U2"" value=""0"" type=""UInt16"" /> <constant name=""I4"" value=""0"" type=""Int32"" /> <constant name=""U4"" value=""0"" type=""UInt32"" /> <constant name=""I8"" value=""0"" type=""Int64"" /> <constant name=""U8"" value=""0"" type=""UInt64"" /> <constant name=""R4"" value=""0x00000000"" type=""Single"" /> <constant name=""R8"" value=""0x0000000000000000"" type=""Double"" /> <constant name=""EI1"" value=""0"" signature=""EnumI1{Int32}"" /> <constant name=""EU1"" value=""0"" signature=""EnumU1{Int32}"" /> <constant name=""EI2"" value=""0"" signature=""EnumI2{Int32}"" /> <constant name=""EU2"" value=""0"" signature=""EnumU2{Int32}"" /> <constant name=""EI4"" value=""0"" signature=""EnumI4{Int32}"" /> <constant name=""EU4"" value=""0"" signature=""EnumU4{Int32}"" /> <constant name=""EI8"" value=""0"" signature=""EnumI8{Int32}"" /> <constant name=""EU8"" value=""0"" signature=""EnumU8{Int32}"" /> <constant name=""StrWithNul"" value=""\u0000"" type=""String"" /> <constant name=""EmptyStr"" value="""" type=""String"" /> <constant name=""NullStr"" value=""null"" type=""String"" /> <constant name=""NullObject"" value=""null"" type=""Object"" /> <constant name=""NullDynamic"" value=""null"" type=""Object"" /> <constant name=""NullTypeDef"" value=""null"" signature=""X"" /> <constant name=""NullTypeRef"" value=""null"" signature=""System.Action"" /> <constant name=""NullTypeSpec"" value=""null"" signature=""System.Func`4{System.Collections.Generic.Dictionary`2{Int32, C`1{Int32}}, Object, !!0, System.Collections.Generic.List`1{!0}}"" /> <constant name=""Array1"" value=""null"" signature=""Object[]"" /> <constant name=""Array2"" value=""null"" signature=""Object[,,]"" /> <constant name=""Array3"" value=""null"" signature=""Object[][]"" /> <constant name=""D"" value=""0"" type=""Decimal"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void SimpleLocalConstant() { var text = @" class C { void M() { const int x = 1; { const int y = 2; } } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <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=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <constant name=""x"" value=""1"" type=""Int32"" /> <scope startOffset=""0x1"" endOffset=""0x3""> <constant name=""y"" value=""2"" type=""Int32"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void LambdaLocalConstants() { var text = WithWindowsLineBreaks(@" using System; class C { void M(Action a) { const int x = 1; M(() => { const int y = 2; { const int z = 3; } }); } } "); var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""a""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""54"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""15"" endColumn=""12"" document=""1"" /> <entry offset=""0x27"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x28""> <namespace name=""System"" /> <constant name=""x"" value=""1"" type=""Int32"" /> </scope> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_0""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" parameterNames=""a"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x2"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x3"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <constant name=""y"" value=""2"" type=""Int32"" /> <scope startOffset=""0x1"" endOffset=""0x3""> <constant name=""z"" value=""3"" type=""Int32"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(543342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543342")] [Fact] public void IteratorLocalConstants() { var source = WithWindowsLineBreaks(@" using System.Collections.Generic; class C { IEnumerable<int> M() { const int x = 1; for (int i = 0; i < 10; i++) { const int y = 2; yield return x + y + i; } } } "); // NOTE: Roslyn's output is somewhat different than Dev10's in this case, but // all of the changes look reasonable. The main thing for this test is that // Dev10 creates fields for the locals in the iterator class. Roslyn doesn't // do that - the <constant> in the <scope> is sufficient. var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<>4__this", "<i>5__1" }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x20"" endOffset=""0x67"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> <slot kind=""1"" offset=""37"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x20"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x27"" hidden=""true"" document=""1"" /> <entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x2a"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""36"" document=""1"" /> <entry offset=""0x41"" hidden=""true"" document=""1"" /> <entry offset=""0x48"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x49"" startLine=""9"" startColumn=""33"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0x59"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""31"" document=""1"" /> <entry offset=""0x64"" hidden=""true"" document=""1"" /> <entry offset=""0x67"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x69""> <namespace name=""System.Collections.Generic"" /> <scope startOffset=""0x1f"" endOffset=""0x69""> <constant name=""x"" value=""1"" type=""Int32"" /> <scope startOffset=""0x29"" endOffset=""0x49""> <constant name=""y"" value=""2"" type=""Int32"" /> </scope> </scope> </scope> </method> </methods> </symbols>"); } [Fact] [WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")] public void LocalConstantsTypes() { var text = @" class C { void M() { const object o = null; const string s = ""hello""; const float f = float.MinValue; const double d = double.MaxValue; } } "; using (new CultureContext(new CultureInfo("en-US", useUserOverride: false))) { CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <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=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""o"" value=""null"" type=""Object"" /> <constant name=""s"" value=""hello"" type=""String"" /> <constant name=""f"" value=""0xFF7FFFFF"" type=""Single"" /> <constant name=""d"" value=""0x7FEFFFFFFFFFFFFF"" type=""Double"" /> </scope> </method> </methods> </symbols>"); } } [Fact] public void WRN_PDBConstantStringValueTooLong() { var longStringValue = new string('a', 2049); var source = @" using System; class C { static void Main() { const string goo = """ + longStringValue + @"""; Console.Write(goo); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); var exebits = new MemoryStream(); var pdbbits = new MemoryStream(); var result = compilation.Emit(exebits, pdbbits); result.Diagnostics.Verify(); // old behavior. This new warning was abandoned // // result.Diagnostics.Verify(// warning CS7063: Constant string value of 'goo' is too long to be used in a PDB file. Only the debug experience may be affected. // Diagnostic(ErrorCode.WRN_PDBConstantStringValueTooLong).WithArguments("goo", longStringValue.Substring(0, 20) + "...")); // // //make sure that this warning is suppressable // compilation = CreateCompilationWithMscorlib(text, compOptions: Options.Exe.WithDebugInformationKind(Common.DebugInformationKind.Full).WithOptimizations(false). // WithSpecificDiagnosticOptions(new Dictionary<int, ReportWarning>(){ {(int)ErrorCode.WRN_PDBConstantStringValueTooLong, ReportWarning.Suppress} })); // // result = compilation.Emit(exebits, null, "DontCare", pdbbits, null); // result.Diagnostics.Verify(); // // //make sure that this warning can be turned into an error. // compilation = CreateCompilationWithMscorlib(text, compOptions: Options.Exe.WithDebugInformationKind(Common.DebugInformationKind.Full).WithOptimizations(false). // WithSpecificDiagnosticOptions(new Dictionary<int, ReportWarning>() { { (int)ErrorCode.WRN_PDBConstantStringValueTooLong, ReportWarning.Error } })); // // result = compilation.Emit(exebits, null, "DontCare", pdbbits, null); // Assert.False(result.Success); // result.Diagnostics.Verify( // Diagnostic(ErrorCode.WRN_PDBConstantStringValueTooLong).WithArguments("goo", longStringValue.Substring(0, 20) + "...").WithWarningAsError(true)); } [Fact] public void StringConstantTooLong() { var text = WithWindowsLineBreaks(@" class C { void M() { const string text = @"" this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB""; } } "); var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <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=""43"" startColumn=""5"" endLine=""43"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""43"" startColumn=""5"" endLine=""43"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""text"" value=""\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(178988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/178988")] [Fact] public void StringWithNulCharacter_MaxSupportedLength() { const int length = 2031; string str = new string('x', 9) + "\0" + new string('x', length - 10); string text = @" class C { void M() { const string x = """ + str + @"""; } } "; var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <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=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""x"" value=""" + str.Replace("\0", @"\u0000") + @""" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""x"" value=""" + str.Replace("\0", @"\u0000") + @""" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(178988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/178988")] [Fact] public void StringWithNulCharacter_OverSupportedLength() { const int length = 2032; string str = new string('x', 9) + "\0" + new string('x', length - 10); string text = @" class C { void M() { const string x = """ + str + @"""; } } "; var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <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=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""x"" value=""" + str.Replace("\0", @"\u0000") + @""" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [Fact] public void DecimalLocalConstants() { var text = @" class C { void M() { const decimal d = (decimal)1.5; } } "; using (new CultureContext(new CultureInfo("en-US", useUserOverride: false))) { CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <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=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""d"" value=""1.5"" type=""Decimal"" /> </scope> </method> </methods> </symbols>"); } } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.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.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Diagnostics { /// <summary> /// Root type for both document and workspace diagnostic pull requests. /// </summary> internal abstract class AbstractPullDiagnosticHandler<TDiagnosticsParams, TReport> : IRequestHandler<TDiagnosticsParams, TReport[]?> where TReport : VSInternalDiagnosticReport { /// <summary> /// Special value we use to designate workspace diagnostics vs document diagnostics. Document diagnostics /// should always <see cref="VSInternalDiagnosticReport.Supersedes"/> a workspace diagnostic as the former are 'live' /// while the latter are cached and may be stale. /// </summary> protected const int WorkspaceDiagnosticIdentifier = 1; protected const int DocumentDiagnosticIdentifier = 2; protected readonly IDiagnosticService DiagnosticService; /// <summary> /// Lock to protect <see cref="_documentIdToLastResultId"/> and <see cref="_nextDocumentResultId"/>. /// </summary> private readonly object _gate = new(); /// <summary> /// Mapping of a document to the last result id we reported for it. /// </summary> private readonly Dictionary<(Workspace workspace, DocumentId documentId), string> _documentIdToLastResultId = new(); /// <summary> /// The next available id to label results with. Note that results are tagged on a per-document bases. That /// way we can update diagnostics with the client with per-doc granularity. /// </summary> private long _nextDocumentResultId; public abstract string Method { get; } public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; protected AbstractPullDiagnosticHandler( IDiagnosticService diagnosticService) { DiagnosticService = diagnosticService; DiagnosticService.DiagnosticsUpdated += OnDiagnosticsUpdated; } public abstract TextDocumentIdentifier? GetTextDocumentIdentifier(TDiagnosticsParams diagnosticsParams); /// <summary> /// Gets the progress object to stream results to. /// </summary> protected abstract IProgress<TReport[]>? GetProgress(TDiagnosticsParams diagnosticsParams); /// <summary> /// Retrieve the previous results we reported. Used so we can avoid resending data for unchanged files. Also /// used so we can report which documents were removed and can have all their diagnostics cleared. /// </summary> protected abstract VSInternalDiagnosticParams[]? GetPreviousResults(TDiagnosticsParams diagnosticsParams); /// <summary> /// Returns all the documents that should be processed in the desired order to process them in. /// </summary> protected abstract ImmutableArray<Document> GetOrderedDocuments(RequestContext context); /// <summary> /// Creates the <see cref="VSInternalDiagnosticReport"/> instance we'll report back to clients to let them know our /// progress. Subclasses can fill in data specific to their needs as appropriate. /// </summary> protected abstract TReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId); /// <summary> /// Produce the diagnostics for the specified document. /// </summary> protected abstract Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(RequestContext context, Document document, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken); /// <summary> /// Generate the right diagnostic tags for a particular diagnostic. /// </summary> protected abstract DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData); private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs updateArgs) { if (updateArgs.DocumentId == null) return; // Ensure we do not clear the cached results while the handler is reading (and possibly then writing) // to the cached results. lock (_gate) { // Whenever we hear about changes to a document, drop the data we've stored for it. We'll recompute it as // necessary on the next request. _documentIdToLastResultId.Remove((updateArgs.Workspace, updateArgs.DocumentId)); } } public async Task<TReport[]?> HandleRequestAsync( TDiagnosticsParams diagnosticsParams, RequestContext context, CancellationToken cancellationToken) { context.TraceInformation($"{this.GetType()} started getting diagnostics"); // The progress object we will stream reports to. using var progress = BufferedProgress.Create(GetProgress(diagnosticsParams)); // Get the set of results the request said were previously reported. We can use this to determine both // what to skip, and what files we have to tell the client have been removed. var previousResults = GetPreviousResults(diagnosticsParams) ?? Array.Empty<VSInternalDiagnosticParams>(); context.TraceInformation($"previousResults.Length={previousResults.Length}"); // First, let the client know if any workspace documents have gone away. That way it can remove those for // the user from squiggles or error-list. HandleRemovedDocuments(context, previousResults, progress); // Create a mapping from documents to the previous results the client says it has for them. That way as we // process documents we know if we should tell the client it should stay the same, or we can tell it what // the updated diagnostics are. var documentToPreviousDiagnosticParams = GetDocumentToPreviousDiagnosticParams(context, previousResults); // Next process each file in priority order. Determine if diagnostics are changed or unchanged since the // last time we notified the client. Report back either to the client so they can update accordingly. var orderedDocuments = GetOrderedDocuments(context); context.TraceInformation($"Processing {orderedDocuments.Length} documents"); foreach (var document in orderedDocuments) { context.TraceInformation($"Processing: {document.FilePath}"); if (!IncludeDocument(document, context.ClientName)) { context.TraceInformation($"Ignoring document '{document.FilePath}' because of razor/client-name mismatch"); continue; } if (HaveDiagnosticsChanged(documentToPreviousDiagnosticParams, document, out var newResultId)) { context.TraceInformation($"Diagnostics were changed for document: {document.FilePath}"); progress.Report(await ComputeAndReportCurrentDiagnosticsAsync(context, document, newResultId, cancellationToken).ConfigureAwait(false)); } else { context.TraceInformation($"Diagnostics were unchanged for document: {document.FilePath}"); // Nothing changed between the last request and this one. Report a (null-diagnostics, // same-result-id) response to the client as that means they should just preserve the current // diagnostics they have for this file. var previousParams = documentToPreviousDiagnosticParams[document]; progress.Report(CreateReport(previousParams.TextDocument, diagnostics: null, previousParams.PreviousResultId)); } } // If we had a progress object, then we will have been reporting to that. Otherwise, take what we've been // collecting and return that. context.TraceInformation($"{this.GetType()} finished getting diagnostics"); return progress.GetValues(); } private static bool IncludeDocument(Document document, string? clientName) { // Documents either belong to Razor or not. We can determine this by checking if the doc has a span-mapping // service or not. If we're not in razor, we do not include razor docs. If we are in razor, we only // include razor docs. var isRazorDoc = document.IsRazorDocument(); var wantsRazorDoc = clientName != null; return wantsRazorDoc == isRazorDoc; } private static Dictionary<Document, VSInternalDiagnosticParams> GetDocumentToPreviousDiagnosticParams( RequestContext context, VSInternalDiagnosticParams[] previousResults) { Contract.ThrowIfNull(context.Solution); var result = new Dictionary<Document, VSInternalDiagnosticParams>(); foreach (var diagnosticParams in previousResults) { if (diagnosticParams.TextDocument != null) { var document = context.Solution.GetDocument(diagnosticParams.TextDocument); if (document != null) result[document] = diagnosticParams; } } return result; } private async Task<TReport> ComputeAndReportCurrentDiagnosticsAsync( RequestContext context, Document document, string resultId, CancellationToken cancellationToken) { // Being asked about this document for the first time. Or being asked again and we have different // diagnostics. Compute and report the current diagnostics info for this document. // Razor has a separate option for determining if they should be in push or pull mode. var diagnosticMode = document.IsRazorDocument() ? InternalDiagnosticsOptions.RazorDiagnosticMode : InternalDiagnosticsOptions.NormalDiagnosticMode; var workspace = document.Project.Solution.Workspace; var isPull = workspace.IsPullDiagnostics(diagnosticMode); context.TraceInformation($"Getting '{(isPull ? "pull" : "push")}' diagnostics with mode '{diagnosticMode}'"); using var _ = ArrayBuilder<VSDiagnostic>.GetInstance(out var result); if (isPull) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var diagnostics = await GetDiagnosticsAsync(context, document, diagnosticMode, cancellationToken).ConfigureAwait(false); context.TraceInformation($"Got {diagnostics.Length} diagnostics"); foreach (var diagnostic in diagnostics) result.Add(ConvertDiagnostic(document, text, diagnostic)); } return CreateReport(ProtocolConversions.DocumentToTextDocumentIdentifier(document), result.ToArray(), resultId); } private void HandleRemovedDocuments(RequestContext context, VSInternalDiagnosticParams[] previousResults, BufferedProgress<TReport> progress) { Contract.ThrowIfNull(context.Solution); foreach (var previousResult in previousResults) { var textDocument = previousResult.TextDocument; if (textDocument != null) { var document = context.Solution.GetDocument(textDocument); if (document == null) { context.TraceInformation($"Clearing diagnostics for removed document: {textDocument.Uri}"); // Client is asking server about a document that no longer exists (i.e. was removed/deleted from // the workspace). Report a (null-diagnostics, null-result-id) response to the client as that // means they should just consider the file deleted and should remove all diagnostics // information they've cached for it. progress.Report(CreateReport(textDocument, diagnostics: null, resultId: null)); } } } } /// <summary> /// Returns true if diagnostics have changed since the last request and if so, /// calculates a new resultId to use for subsequent computation and caches it. /// </summary> /// <param name="documentToPreviousDiagnosticParams">the resultIds the client sent us.</param> /// <param name="document">the document we are currently calculating results for.</param> /// <param name="newResultId">the resultId to report new diagnostics with if changed.</param> private bool HaveDiagnosticsChanged( Dictionary<Document, VSInternalDiagnosticParams> documentToPreviousDiagnosticParams, Document document, [NotNullWhen(true)] out string? newResultId) { // Read and write the cached resultId to _documentIdToLastResultId in a single transaction // to prevent in-between updates to _documentIdToLastResultId triggered by OnDiagnosticsUpdated. lock (_gate) { var workspace = document.Project.Solution.Workspace; if (documentToPreviousDiagnosticParams.TryGetValue(document, out var previousParams) && _documentIdToLastResultId.TryGetValue((workspace, document.Id), out var lastReportedResultId) && lastReportedResultId == previousParams.PreviousResultId) { // Our cached resultId for the document matches the resultId the client passed to us. // This means the diagnostics have not changed and we do not need to re-compute. newResultId = null; return false; } // Keep track of the diagnostics we reported here so that we can short-circuit producing diagnostics for // the same diagnostic set in the future. Use a custom result-id per type (doc diagnostics or workspace // diagnostics) so that clients of one don't errantly call into the other. For example, a client // getting document diagnostics should not ask for workspace diagnostics with the result-ids it got for // doc-diagnostics. The two systems are different and cannot share results, or do things like report // what changed between each other. // // Note that we can safely update the map before computation as any cancellation or exception // during computation means that the client will never recieve this resultId and so cannot ask us for it. newResultId = $"{GetType().Name}:{_nextDocumentResultId++}"; _documentIdToLastResultId[(document.Project.Solution.Workspace, document.Id)] = newResultId; return true; } } private VSDiagnostic ConvertDiagnostic(Document document, SourceText text, DiagnosticData diagnosticData) { Contract.ThrowIfNull(diagnosticData.Message, $"Got a document diagnostic that did not have a {nameof(diagnosticData.Message)}"); Contract.ThrowIfNull(diagnosticData.DataLocation, $"Got a document diagnostic that did not have a {nameof(diagnosticData.DataLocation)}"); var project = document.Project; // We currently do not map diagnostics spans as // 1. Razor handles span mapping for razor files on their side. // 2. LSP does not allow us to report document pull diagnostics for a different file path. // 3. The VS LSP client does not support document pull diagnostics for files outside our content type. // 4. This matches classic behavior where we only squiggle the original location anyway. var useMappedSpan = false; return new VSDiagnostic { Source = GetType().Name, Code = diagnosticData.Id, CodeDescription = ProtocolConversions.HelpLinkToCodeDescription(diagnosticData.HelpLink), Message = diagnosticData.Message, Severity = ConvertDiagnosticSeverity(diagnosticData.Severity), Range = ProtocolConversions.LinePositionToRange(DiagnosticData.GetLinePositionSpan(diagnosticData.DataLocation, text, useMappedSpan)), Tags = ConvertTags(diagnosticData), DiagnosticType = diagnosticData.Category, Projects = new[] { new VSDiagnosticProjectInformation { ProjectIdentifier = project.Id.Id.ToString(), ProjectName = project.Name, }, }, }; } private static LSP.DiagnosticSeverity ConvertDiagnosticSeverity(DiagnosticSeverity severity) => severity switch { // Hidden is translated in ConvertTags to pass along appropriate _ms tags // that will hide the item in a client that knows about those tags. DiagnosticSeverity.Hidden => LSP.DiagnosticSeverity.Hint, DiagnosticSeverity.Info => LSP.DiagnosticSeverity.Hint, DiagnosticSeverity.Warning => LSP.DiagnosticSeverity.Warning, DiagnosticSeverity.Error => LSP.DiagnosticSeverity.Error, _ => throw ExceptionUtilities.UnexpectedValue(severity), }; /// <summary> /// If you make change in this method, please also update the corresponding file in /// src\VisualStudio\Xaml\Impl\Implementation\LanguageServer\Handler\Diagnostics\AbstractPullDiagnosticHandler.cs /// </summary> protected static DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData, bool potentialDuplicate) { using var _ = ArrayBuilder<DiagnosticTag>.GetInstance(out var result); if (diagnosticData.Severity == DiagnosticSeverity.Hidden) { result.Add(VSDiagnosticTags.HiddenInEditor); result.Add(VSDiagnosticTags.HiddenInErrorList); result.Add(VSDiagnosticTags.SuppressEditorToolTip); } else { result.Add(VSDiagnosticTags.VisibleInErrorList); } if (potentialDuplicate) result.Add(VSDiagnosticTags.PotentialDuplicate); result.Add(diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Build) ? VSDiagnosticTags.BuildError : VSDiagnosticTags.IntellisenseError); if (diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary)) result.Add(DiagnosticTag.Unnecessary); if (diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.EditAndContinue)) result.Add(VSDiagnosticTags.EditAndContinueError); return result.ToArray(); } } }
// 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.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Diagnostics { /// <summary> /// Root type for both document and workspace diagnostic pull requests. /// </summary> internal abstract class AbstractPullDiagnosticHandler<TDiagnosticsParams, TReport> : IRequestHandler<TDiagnosticsParams, TReport[]?> where TReport : VSInternalDiagnosticReport { /// <summary> /// Special value we use to designate workspace diagnostics vs document diagnostics. Document diagnostics /// should always <see cref="VSInternalDiagnosticReport.Supersedes"/> a workspace diagnostic as the former are 'live' /// while the latter are cached and may be stale. /// </summary> protected const int WorkspaceDiagnosticIdentifier = 1; protected const int DocumentDiagnosticIdentifier = 2; protected readonly IDiagnosticService DiagnosticService; /// <summary> /// Lock to protect <see cref="_documentIdToLastResultId"/> and <see cref="_nextDocumentResultId"/>. /// </summary> private readonly object _gate = new(); /// <summary> /// Mapping of a document to the last result id we reported for it. /// </summary> private readonly Dictionary<(Workspace workspace, DocumentId documentId), string> _documentIdToLastResultId = new(); /// <summary> /// The next available id to label results with. Note that results are tagged on a per-document bases. That /// way we can update diagnostics with the client with per-doc granularity. /// </summary> private long _nextDocumentResultId; public abstract string Method { get; } public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; protected AbstractPullDiagnosticHandler( IDiagnosticService diagnosticService) { DiagnosticService = diagnosticService; DiagnosticService.DiagnosticsUpdated += OnDiagnosticsUpdated; } public abstract TextDocumentIdentifier? GetTextDocumentIdentifier(TDiagnosticsParams diagnosticsParams); /// <summary> /// Gets the progress object to stream results to. /// </summary> protected abstract IProgress<TReport[]>? GetProgress(TDiagnosticsParams diagnosticsParams); /// <summary> /// Retrieve the previous results we reported. Used so we can avoid resending data for unchanged files. Also /// used so we can report which documents were removed and can have all their diagnostics cleared. /// </summary> protected abstract VSInternalDiagnosticParams[]? GetPreviousResults(TDiagnosticsParams diagnosticsParams); /// <summary> /// Returns all the documents that should be processed in the desired order to process them in. /// </summary> protected abstract ImmutableArray<Document> GetOrderedDocuments(RequestContext context); /// <summary> /// Creates the <see cref="VSInternalDiagnosticReport"/> instance we'll report back to clients to let them know our /// progress. Subclasses can fill in data specific to their needs as appropriate. /// </summary> protected abstract TReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId); /// <summary> /// Produce the diagnostics for the specified document. /// </summary> protected abstract Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(RequestContext context, Document document, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken); /// <summary> /// Generate the right diagnostic tags for a particular diagnostic. /// </summary> protected abstract DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData); private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs updateArgs) { if (updateArgs.DocumentId == null) return; // Ensure we do not clear the cached results while the handler is reading (and possibly then writing) // to the cached results. lock (_gate) { // Whenever we hear about changes to a document, drop the data we've stored for it. We'll recompute it as // necessary on the next request. _documentIdToLastResultId.Remove((updateArgs.Workspace, updateArgs.DocumentId)); } } public async Task<TReport[]?> HandleRequestAsync( TDiagnosticsParams diagnosticsParams, RequestContext context, CancellationToken cancellationToken) { context.TraceInformation($"{this.GetType()} started getting diagnostics"); // The progress object we will stream reports to. using var progress = BufferedProgress.Create(GetProgress(diagnosticsParams)); // Get the set of results the request said were previously reported. We can use this to determine both // what to skip, and what files we have to tell the client have been removed. var previousResults = GetPreviousResults(diagnosticsParams) ?? Array.Empty<VSInternalDiagnosticParams>(); context.TraceInformation($"previousResults.Length={previousResults.Length}"); // First, let the client know if any workspace documents have gone away. That way it can remove those for // the user from squiggles or error-list. HandleRemovedDocuments(context, previousResults, progress); // Create a mapping from documents to the previous results the client says it has for them. That way as we // process documents we know if we should tell the client it should stay the same, or we can tell it what // the updated diagnostics are. var documentToPreviousDiagnosticParams = GetDocumentToPreviousDiagnosticParams(context, previousResults); // Next process each file in priority order. Determine if diagnostics are changed or unchanged since the // last time we notified the client. Report back either to the client so they can update accordingly. var orderedDocuments = GetOrderedDocuments(context); context.TraceInformation($"Processing {orderedDocuments.Length} documents"); foreach (var document in orderedDocuments) { context.TraceInformation($"Processing: {document.FilePath}"); if (!IncludeDocument(document, context.ClientName)) { context.TraceInformation($"Ignoring document '{document.FilePath}' because of razor/client-name mismatch"); continue; } if (HaveDiagnosticsChanged(documentToPreviousDiagnosticParams, document, out var newResultId)) { context.TraceInformation($"Diagnostics were changed for document: {document.FilePath}"); progress.Report(await ComputeAndReportCurrentDiagnosticsAsync(context, document, newResultId, cancellationToken).ConfigureAwait(false)); } else { context.TraceInformation($"Diagnostics were unchanged for document: {document.FilePath}"); // Nothing changed between the last request and this one. Report a (null-diagnostics, // same-result-id) response to the client as that means they should just preserve the current // diagnostics they have for this file. var previousParams = documentToPreviousDiagnosticParams[document]; progress.Report(CreateReport(previousParams.TextDocument, diagnostics: null, previousParams.PreviousResultId)); } } // If we had a progress object, then we will have been reporting to that. Otherwise, take what we've been // collecting and return that. context.TraceInformation($"{this.GetType()} finished getting diagnostics"); return progress.GetValues(); } private static bool IncludeDocument(Document document, string? clientName) { // Documents either belong to Razor or not. We can determine this by checking if the doc has a span-mapping // service or not. If we're not in razor, we do not include razor docs. If we are in razor, we only // include razor docs. var isRazorDoc = document.IsRazorDocument(); var wantsRazorDoc = clientName != null; return wantsRazorDoc == isRazorDoc; } private static Dictionary<Document, VSInternalDiagnosticParams> GetDocumentToPreviousDiagnosticParams( RequestContext context, VSInternalDiagnosticParams[] previousResults) { Contract.ThrowIfNull(context.Solution); var result = new Dictionary<Document, VSInternalDiagnosticParams>(); foreach (var diagnosticParams in previousResults) { if (diagnosticParams.TextDocument != null) { var document = context.Solution.GetDocument(diagnosticParams.TextDocument); if (document != null) result[document] = diagnosticParams; } } return result; } private async Task<TReport> ComputeAndReportCurrentDiagnosticsAsync( RequestContext context, Document document, string resultId, CancellationToken cancellationToken) { // Being asked about this document for the first time. Or being asked again and we have different // diagnostics. Compute and report the current diagnostics info for this document. // Razor has a separate option for determining if they should be in push or pull mode. var diagnosticMode = document.IsRazorDocument() ? InternalDiagnosticsOptions.RazorDiagnosticMode : InternalDiagnosticsOptions.NormalDiagnosticMode; var workspace = document.Project.Solution.Workspace; var isPull = workspace.IsPullDiagnostics(diagnosticMode); context.TraceInformation($"Getting '{(isPull ? "pull" : "push")}' diagnostics with mode '{diagnosticMode}'"); using var _ = ArrayBuilder<VSDiagnostic>.GetInstance(out var result); if (isPull) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var diagnostics = await GetDiagnosticsAsync(context, document, diagnosticMode, cancellationToken).ConfigureAwait(false); context.TraceInformation($"Got {diagnostics.Length} diagnostics"); foreach (var diagnostic in diagnostics) result.Add(ConvertDiagnostic(document, text, diagnostic)); } return CreateReport(ProtocolConversions.DocumentToTextDocumentIdentifier(document), result.ToArray(), resultId); } private void HandleRemovedDocuments(RequestContext context, VSInternalDiagnosticParams[] previousResults, BufferedProgress<TReport> progress) { Contract.ThrowIfNull(context.Solution); foreach (var previousResult in previousResults) { var textDocument = previousResult.TextDocument; if (textDocument != null) { var document = context.Solution.GetDocument(textDocument); if (document == null) { context.TraceInformation($"Clearing diagnostics for removed document: {textDocument.Uri}"); // Client is asking server about a document that no longer exists (i.e. was removed/deleted from // the workspace). Report a (null-diagnostics, null-result-id) response to the client as that // means they should just consider the file deleted and should remove all diagnostics // information they've cached for it. progress.Report(CreateReport(textDocument, diagnostics: null, resultId: null)); } } } } /// <summary> /// Returns true if diagnostics have changed since the last request and if so, /// calculates a new resultId to use for subsequent computation and caches it. /// </summary> /// <param name="documentToPreviousDiagnosticParams">the resultIds the client sent us.</param> /// <param name="document">the document we are currently calculating results for.</param> /// <param name="newResultId">the resultId to report new diagnostics with if changed.</param> private bool HaveDiagnosticsChanged( Dictionary<Document, VSInternalDiagnosticParams> documentToPreviousDiagnosticParams, Document document, [NotNullWhen(true)] out string? newResultId) { // Read and write the cached resultId to _documentIdToLastResultId in a single transaction // to prevent in-between updates to _documentIdToLastResultId triggered by OnDiagnosticsUpdated. lock (_gate) { var workspace = document.Project.Solution.Workspace; if (documentToPreviousDiagnosticParams.TryGetValue(document, out var previousParams) && _documentIdToLastResultId.TryGetValue((workspace, document.Id), out var lastReportedResultId) && lastReportedResultId == previousParams.PreviousResultId) { // Our cached resultId for the document matches the resultId the client passed to us. // This means the diagnostics have not changed and we do not need to re-compute. newResultId = null; return false; } // Keep track of the diagnostics we reported here so that we can short-circuit producing diagnostics for // the same diagnostic set in the future. Use a custom result-id per type (doc diagnostics or workspace // diagnostics) so that clients of one don't errantly call into the other. For example, a client // getting document diagnostics should not ask for workspace diagnostics with the result-ids it got for // doc-diagnostics. The two systems are different and cannot share results, or do things like report // what changed between each other. // // Note that we can safely update the map before computation as any cancellation or exception // during computation means that the client will never recieve this resultId and so cannot ask us for it. newResultId = $"{GetType().Name}:{_nextDocumentResultId++}"; _documentIdToLastResultId[(document.Project.Solution.Workspace, document.Id)] = newResultId; return true; } } private VSDiagnostic ConvertDiagnostic(Document document, SourceText text, DiagnosticData diagnosticData) { Contract.ThrowIfNull(diagnosticData.Message, $"Got a document diagnostic that did not have a {nameof(diagnosticData.Message)}"); Contract.ThrowIfNull(diagnosticData.DataLocation, $"Got a document diagnostic that did not have a {nameof(diagnosticData.DataLocation)}"); var project = document.Project; // We currently do not map diagnostics spans as // 1. Razor handles span mapping for razor files on their side. // 2. LSP does not allow us to report document pull diagnostics for a different file path. // 3. The VS LSP client does not support document pull diagnostics for files outside our content type. // 4. This matches classic behavior where we only squiggle the original location anyway. var useMappedSpan = false; return new VSDiagnostic { Source = GetType().Name, Code = diagnosticData.Id, CodeDescription = ProtocolConversions.HelpLinkToCodeDescription(diagnosticData.HelpLink), Message = diagnosticData.Message, Severity = ConvertDiagnosticSeverity(diagnosticData.Severity), Range = ProtocolConversions.LinePositionToRange(DiagnosticData.GetLinePositionSpan(diagnosticData.DataLocation, text, useMappedSpan)), Tags = ConvertTags(diagnosticData), DiagnosticType = diagnosticData.Category, Projects = new[] { new VSDiagnosticProjectInformation { ProjectIdentifier = project.Id.Id.ToString(), ProjectName = project.Name, }, }, }; } private static LSP.DiagnosticSeverity ConvertDiagnosticSeverity(DiagnosticSeverity severity) => severity switch { // Hidden is translated in ConvertTags to pass along appropriate _ms tags // that will hide the item in a client that knows about those tags. DiagnosticSeverity.Hidden => LSP.DiagnosticSeverity.Hint, DiagnosticSeverity.Info => LSP.DiagnosticSeverity.Hint, DiagnosticSeverity.Warning => LSP.DiagnosticSeverity.Warning, DiagnosticSeverity.Error => LSP.DiagnosticSeverity.Error, _ => throw ExceptionUtilities.UnexpectedValue(severity), }; /// <summary> /// If you make change in this method, please also update the corresponding file in /// src\VisualStudio\Xaml\Impl\Implementation\LanguageServer\Handler\Diagnostics\AbstractPullDiagnosticHandler.cs /// </summary> protected static DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData, bool potentialDuplicate) { using var _ = ArrayBuilder<DiagnosticTag>.GetInstance(out var result); if (diagnosticData.Severity == DiagnosticSeverity.Hidden) { result.Add(VSDiagnosticTags.HiddenInEditor); result.Add(VSDiagnosticTags.HiddenInErrorList); result.Add(VSDiagnosticTags.SuppressEditorToolTip); } else { result.Add(VSDiagnosticTags.VisibleInErrorList); } if (potentialDuplicate) result.Add(VSDiagnosticTags.PotentialDuplicate); result.Add(diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Build) ? VSDiagnosticTags.BuildError : VSDiagnosticTags.IntellisenseError); if (diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary)) result.Add(DiagnosticTag.Unnecessary); if (diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.EditAndContinue)) result.Add(VSDiagnosticTags.EditAndContinueError); return result.ToArray(); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Analyzers/CSharp/CodeFixes/ConvertTypeOfToNameOf/CSharpConvertTypeOfToNameOfCodeFixProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.ConvertTypeOfToNameOf; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertTypeOfToNameOf { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertTypeOfToNameOf), Shared] internal class CSharpConvertTypeOfToNameOfCodeFixProvider : AbstractConvertTypeOfToNameOfCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertTypeOfToNameOfCodeFixProvider() { } protected override string GetCodeFixTitle() => CSharpCodeFixesResources.Convert_typeof_to_nameof; protected override SyntaxNode? GetSymbolTypeExpression(SemanticModel model, SyntaxNode node, CancellationToken cancellationToken) { if (node is MemberAccessExpressionSyntax { Expression: TypeOfExpressionSyntax typeOfExpression }) { var typeSymbol = model.GetSymbolInfo(typeOfExpression.Type, cancellationToken).Symbol.GetSymbolType(); return typeSymbol?.GenerateExpressionSyntax(); } 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. using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.ConvertTypeOfToNameOf; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertTypeOfToNameOf { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertTypeOfToNameOf), Shared] internal class CSharpConvertTypeOfToNameOfCodeFixProvider : AbstractConvertTypeOfToNameOfCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertTypeOfToNameOfCodeFixProvider() { } protected override string GetCodeFixTitle() => CSharpCodeFixesResources.Convert_typeof_to_nameof; protected override SyntaxNode? GetSymbolTypeExpression(SemanticModel model, SyntaxNode node, CancellationToken cancellationToken) { if (node is MemberAccessExpressionSyntax { Expression: TypeOfExpressionSyntax typeOfExpression }) { var typeSymbol = model.GetSymbolInfo(typeOfExpression.Type, cancellationToken).Symbol.GetSymbolType(); return typeSymbol?.GenerateExpressionSyntax(); } return null; } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Analyzers/VisualBasic/Analyzers/ConvertTypeofToNameof/VisualBasicConvertTypeOfToNameOfDiagnosticAnalyzer.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.ConvertTypeOfToNameOf Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertTypeOfToNameOf <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend NotInheritable Class VisualBasicConvertTypeOfToNameOfDiagnosticAnalyzer Inherits AbstractConvertTypeOfToNameOfDiagnosticAnalyzer Private Shared ReadOnly s_title As String = VisualBasicAnalyzersResources.GetType_can_be_converted_to_NameOf Public Sub New() MyBase.New(s_title, LanguageNames.VisualBasic) End Sub Protected Overrides Function IsValidTypeofAction(context As OperationAnalysisContext) As Boolean Dim node = context.Operation.Syntax Dim compilation = context.Compilation Dim isValidLanguage = DirectCast(compilation, VisualBasicCompilation).LanguageVersion >= LanguageVersion.VisualBasic14 Dim isValidType = node.IsKind(SyntaxKind.GetTypeExpression) Dim isParentValid = node.Parent.GetType() Is GetType(MemberAccessExpressionSyntax) Return isValidLanguage And isValidType And isParentValid 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 Imports Microsoft.CodeAnalysis.ConvertTypeOfToNameOf Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertTypeOfToNameOf <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend NotInheritable Class VisualBasicConvertTypeOfToNameOfDiagnosticAnalyzer Inherits AbstractConvertTypeOfToNameOfDiagnosticAnalyzer Private Shared ReadOnly s_title As String = VisualBasicAnalyzersResources.GetType_can_be_converted_to_NameOf Public Sub New() MyBase.New(s_title, LanguageNames.VisualBasic) End Sub Protected Overrides Function IsValidTypeofAction(context As OperationAnalysisContext) As Boolean Dim node = context.Operation.Syntax Dim compilation = context.Compilation Dim isValidLanguage = DirectCast(compilation, VisualBasicCompilation).LanguageVersion >= LanguageVersion.VisualBasic14 Dim isValidType = node.IsKind(SyntaxKind.GetTypeExpression) Dim isParentValid = node.Parent.GetType() Is GetType(MemberAccessExpressionSyntax) Return isValidLanguage And isValidType And isParentValid End Function End Class End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/VisualStudio/Core/Def/Implementation/LanguageService/AbstractLanguageService`2.IVsImmediateStatementCompletion2.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.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService { internal abstract partial class AbstractLanguageService<TPackage, TLanguageService> : IVsImmediateStatementCompletion2 { protected Dictionary<IVsTextView, DebuggerIntelliSenseFilter> filters = new(); int IVsImmediateStatementCompletion2.EnableStatementCompletion(int enable, int startIndex, int endIndex, IVsTextView textView) { if (filters.TryGetValue(textView, out var filter)) { if (enable != 0) { filter.EnableCompletion(); } else { filter.DisableCompletion(); } } // Debugger wants Roslyn to return OK in all cases, // for example, even if Rolsyn tried to enable the one already enabled. return VSConstants.S_OK; } int IVsImmediateStatementCompletion2.InstallStatementCompletion(int install, IVsTextView textView, int initialEnable) { // We'll install a filter whenever the debugger asks, but it won't do anything but call // the next filter until the context is set. To ensure that we correctly install and // uninstall from the many possible textviews we can work on, we maintain a dictionary // of textview->filters. if (install != 0) { DebuggerIntelliSenseFilter filter; if (!this.filters.ContainsKey(textView)) { filter = new DebuggerIntelliSenseFilter( this.EditorAdaptersFactoryService.GetWpfTextView(textView), this.Package.ComponentModel, this.Package.ComponentModel.GetService<IFeatureServiceFactory>()); this.filters[textView] = filter; Marshal.ThrowExceptionForHR(textView.AddCommandFilter(filter, out var nextFilter)); filter.SetNextFilter(nextFilter); } this.filters[textView].SetContentType(install: true); } else { Marshal.ThrowExceptionForHR(textView.RemoveCommandFilter(this.filters[textView])); this.filters[textView].SetContentType(install: false); this.filters[textView].Dispose(); this.filters.Remove(textView); } return VSConstants.S_OK; } int IVsImmediateStatementCompletion2.SetCompletionContext(string filePath, IVsTextLines buffer, TextSpan[] currentStatementSpan, object punkContext, IVsTextView textView) { // The immediate window is always marked read-only and the language service is // responsible for asking the buffer to make itself writable. We'll have to do that for // commit, so we need to drag the IVsTextLines around, too. Marshal.ThrowExceptionForHR(textView.GetBuffer(out var debuggerBuffer)); var view = EditorAdaptersFactoryService.GetWpfTextView(textView); // Sometimes, they give us a null context buffer. In that case, there's probably not any // work to do. if (buffer != null) { var contextBuffer = EditorAdaptersFactoryService.GetDataBuffer(buffer); if (!contextBuffer.ContentType.IsOfType(this.ContentTypeName)) { FatalError.ReportAndCatch( new ArgumentException($"Expected content type {this.ContentTypeName} " + $"but got buffer of content type {contextBuffer.ContentType}")); return VSConstants.E_FAIL; } // Clean the old context in any case upfront: // even if we fail to initialize, the old context must be cleaned. this.filters[textView].RemoveContext(); var context = CreateContext(view, textView, debuggerBuffer, contextBuffer, currentStatementSpan); if (context.TryInitialize()) { this.filters[textView].SetContext(context); } } return VSConstants.S_OK; } // Let our deriving language services build up an appropriate context. protected abstract AbstractDebuggerIntelliSenseContext CreateContext(IWpfTextView view, IVsTextView vsTextView, IVsTextLines debuggerBuffer, ITextBuffer contextBuffer, Microsoft.VisualStudio.TextManager.Interop.TextSpan[] currentStatementSpan); #region Methods that are never called int IVsImmediateStatementCompletion2.EnableStatementCompletion_Deprecated(int enable, int startIndex, int endIndex) { Debug.Assert(false); return VSConstants.S_OK; } int IVsImmediateStatementCompletion2.GetFilter(IVsTextView textView, out IVsTextViewFilter filter) { // They never even call this, so just make it compile Debug.Assert(false); filter = null; return VSConstants.S_OK; } int IVsImmediateStatementCompletion.EnableStatementCompletion_Deprecated(int enable, int startIndex, int endIndex) { Debug.Assert(false); return VSConstants.S_OK; } int IVsImmediateStatementCompletion.InstallStatementCompletion(int install, IVsTextView textView, int initialEnable) { Debug.Assert(false); return VSConstants.S_OK; } int IVsImmediateStatementCompletion.SetCompletionContext_Deprecated(string filePath, IVsTextLines buffer, TextSpan[] currentStatementSpan, object punkContext) { Debug.Assert(false); return VSConstants.S_OK; } int IVsImmediateStatementCompletion2.SetCompletionContext_Deprecated(string filepath, IVsTextLines buffer, TextSpan[] currentStatementSpan, object punkContext) { Debug.Assert(false); return VSConstants.S_OK; } #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; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService { internal abstract partial class AbstractLanguageService<TPackage, TLanguageService> : IVsImmediateStatementCompletion2 { protected Dictionary<IVsTextView, DebuggerIntelliSenseFilter> filters = new(); int IVsImmediateStatementCompletion2.EnableStatementCompletion(int enable, int startIndex, int endIndex, IVsTextView textView) { if (filters.TryGetValue(textView, out var filter)) { if (enable != 0) { filter.EnableCompletion(); } else { filter.DisableCompletion(); } } // Debugger wants Roslyn to return OK in all cases, // for example, even if Rolsyn tried to enable the one already enabled. return VSConstants.S_OK; } int IVsImmediateStatementCompletion2.InstallStatementCompletion(int install, IVsTextView textView, int initialEnable) { // We'll install a filter whenever the debugger asks, but it won't do anything but call // the next filter until the context is set. To ensure that we correctly install and // uninstall from the many possible textviews we can work on, we maintain a dictionary // of textview->filters. if (install != 0) { DebuggerIntelliSenseFilter filter; if (!this.filters.ContainsKey(textView)) { filter = new DebuggerIntelliSenseFilter( this.EditorAdaptersFactoryService.GetWpfTextView(textView), this.Package.ComponentModel, this.Package.ComponentModel.GetService<IFeatureServiceFactory>()); this.filters[textView] = filter; Marshal.ThrowExceptionForHR(textView.AddCommandFilter(filter, out var nextFilter)); filter.SetNextFilter(nextFilter); } this.filters[textView].SetContentType(install: true); } else { Marshal.ThrowExceptionForHR(textView.RemoveCommandFilter(this.filters[textView])); this.filters[textView].SetContentType(install: false); this.filters[textView].Dispose(); this.filters.Remove(textView); } return VSConstants.S_OK; } int IVsImmediateStatementCompletion2.SetCompletionContext(string filePath, IVsTextLines buffer, TextSpan[] currentStatementSpan, object punkContext, IVsTextView textView) { // The immediate window is always marked read-only and the language service is // responsible for asking the buffer to make itself writable. We'll have to do that for // commit, so we need to drag the IVsTextLines around, too. Marshal.ThrowExceptionForHR(textView.GetBuffer(out var debuggerBuffer)); var view = EditorAdaptersFactoryService.GetWpfTextView(textView); // Sometimes, they give us a null context buffer. In that case, there's probably not any // work to do. if (buffer != null) { var contextBuffer = EditorAdaptersFactoryService.GetDataBuffer(buffer); if (!contextBuffer.ContentType.IsOfType(this.ContentTypeName)) { FatalError.ReportAndCatch( new ArgumentException($"Expected content type {this.ContentTypeName} " + $"but got buffer of content type {contextBuffer.ContentType}")); return VSConstants.E_FAIL; } // Clean the old context in any case upfront: // even if we fail to initialize, the old context must be cleaned. this.filters[textView].RemoveContext(); var context = CreateContext(view, textView, debuggerBuffer, contextBuffer, currentStatementSpan); if (context.TryInitialize()) { this.filters[textView].SetContext(context); } } return VSConstants.S_OK; } // Let our deriving language services build up an appropriate context. protected abstract AbstractDebuggerIntelliSenseContext CreateContext(IWpfTextView view, IVsTextView vsTextView, IVsTextLines debuggerBuffer, ITextBuffer contextBuffer, Microsoft.VisualStudio.TextManager.Interop.TextSpan[] currentStatementSpan); #region Methods that are never called int IVsImmediateStatementCompletion2.EnableStatementCompletion_Deprecated(int enable, int startIndex, int endIndex) { Debug.Assert(false); return VSConstants.S_OK; } int IVsImmediateStatementCompletion2.GetFilter(IVsTextView textView, out IVsTextViewFilter filter) { // They never even call this, so just make it compile Debug.Assert(false); filter = null; return VSConstants.S_OK; } int IVsImmediateStatementCompletion.EnableStatementCompletion_Deprecated(int enable, int startIndex, int endIndex) { Debug.Assert(false); return VSConstants.S_OK; } int IVsImmediateStatementCompletion.InstallStatementCompletion(int install, IVsTextView textView, int initialEnable) { Debug.Assert(false); return VSConstants.S_OK; } int IVsImmediateStatementCompletion.SetCompletionContext_Deprecated(string filePath, IVsTextLines buffer, TextSpan[] currentStatementSpan, object punkContext) { Debug.Assert(false); return VSConstants.S_OK; } int IVsImmediateStatementCompletion2.SetCompletionContext_Deprecated(string filepath, IVsTextLines buffer, TextSpan[] currentStatementSpan, object punkContext) { Debug.Assert(false); return VSConstants.S_OK; } #endregion } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/Test/Directory.Build.props
<Project> <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" /> <PropertyGroup> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </PropertyGroup> </Project>
<Project> <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" /> <PropertyGroup> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </PropertyGroup> </Project>
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Workspaces/VisualBasic/Portable/Simplification/VisualBasicSimplificationService.NodesAndTokensToReduceComputer.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 Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicSimplificationService Inherits AbstractSimplificationService(Of ExpressionSyntax, ExecutableStatementSyntax, CrefReferenceSyntax) Private Class NodesAndTokensToReduceComputer Inherits VisualBasicSyntaxRewriter Private ReadOnly _nodesAndTokensToReduce As List(Of NodeOrTokenToReduce) Private ReadOnly _isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean) Private Shared ReadOnly s_containsAnnotations As Func(Of SyntaxNode, Boolean) = Function(n) n.ContainsAnnotations Private Shared ReadOnly s_hasSimplifierAnnotation As Func(Of SyntaxNodeOrToken, Boolean) = Function(n) n.HasAnnotation(Simplifier.Annotation) Private _simplifyAllDescendants As Boolean Private _insideSpeculatedNode As Boolean ''' <summary> ''' Computes a list of nodes and tokens that need to be reduced in the given syntax root. ''' </summary> Public Shared Function Compute(root As SyntaxNode, isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean)) As ImmutableArray(Of NodeOrTokenToReduce) Dim reduceNodeComputer = New NodesAndTokensToReduceComputer(isNodeOrTokenOutsideSimplifySpans) reduceNodeComputer.Visit(root) Return reduceNodeComputer._nodesAndTokensToReduce.ToImmutableArray() End Function Private Sub New(isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean)) MyBase.New(visitIntoStructuredTrivia:=True) Me._isNodeOrTokenOutsideSimplifySpans = isNodeOrTokenOutsideSimplifySpans Me._nodesAndTokensToReduce = New List(Of NodeOrTokenToReduce)() Me._simplifyAllDescendants = False Me._insideSpeculatedNode = False End Sub Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode If node Is Nothing Then Return node End If If Me._isNodeOrTokenOutsideSimplifySpans(node) Then If Me._simplifyAllDescendants Then ' One of the ancestor nodes is within a simplification span, but this node Is outside all simplification spans. ' Add DontSimplifyAnnotation to node to ensure it doesn't get simplified. Return node.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) Else Return node End If End If Dim savedSimplifyAllDescendants = Me._simplifyAllDescendants Me._simplifyAllDescendants = Me._simplifyAllDescendants OrElse node.HasAnnotation(Simplifier.Annotation) If Not Me._insideSpeculatedNode AndAlso SpeculationAnalyzer.CanSpeculateOnNode(node) Then If Me._simplifyAllDescendants OrElse node.DescendantNodesAndTokens(s_containsAnnotations, descendIntoTrivia:=True).Any(s_hasSimplifierAnnotation) Then Me._insideSpeculatedNode = True Dim rewrittenNode = MyBase.Visit(node) Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(rewrittenNode, _simplifyAllDescendants, node)) Me._insideSpeculatedNode = False End If ElseIf node.ContainsAnnotations OrElse savedSimplifyAllDescendants Then If Not Me._insideSpeculatedNode AndAlso IsNodeVariableDeclaratorOfFieldDeclaration(node) AndAlso Me._simplifyAllDescendants Then Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(node, False, node, False)) End If node = MyBase.Visit(node) End If Me._simplifyAllDescendants = savedSimplifyAllDescendants Return node End Function Private Shared Function IsNodeVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As Boolean Return node IsNot Nothing AndAlso node.Kind() = SyntaxKind.VariableDeclarator AndAlso node.Parent IsNot Nothing AndAlso node.Parent.Kind() = SyntaxKind.FieldDeclaration End Function Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken If Me._isNodeOrTokenOutsideSimplifySpans(token) Then If Me._simplifyAllDescendants Then ' One of the ancestor nodes is within a simplification span, but this token Is outside all simplification spans. ' Add DontSimplifyAnnotation to token to ensure it doesn't get simplified. Return token.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) Else Return token End If End If Dim savedSimplifyAllDescendants = Me._simplifyAllDescendants Me._simplifyAllDescendants = Me._simplifyAllDescendants OrElse token.HasAnnotation(Simplifier.Annotation) If Me._simplifyAllDescendants AndAlso Not Me._insideSpeculatedNode AndAlso token.Kind <> SyntaxKind.None Then Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(token, simplifyAllDescendants:=True, originalNodeOrToken:=token)) End If If token.ContainsAnnotations OrElse savedSimplifyAllDescendants Then token = MyBase.VisitToken(token) End If Me._simplifyAllDescendants = savedSimplifyAllDescendants Return token End Function Public Overrides Function VisitTrivia(trivia As SyntaxTrivia) As SyntaxTrivia If trivia.HasStructure Then Dim savedInsideSpeculatedNode = Me._insideSpeculatedNode Me._insideSpeculatedNode = False MyBase.VisitTrivia(trivia) Me._insideSpeculatedNode = savedInsideSpeculatedNode End If Return trivia End Function Public Overrides Function VisitMethodBlock(node As MethodBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, MethodBlockSyntax).Update(node.Kind, DirectCast(b, MethodStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Public Overrides Function VisitOperatorBlock(node As OperatorBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, OperatorBlockSyntax).Update(DirectCast(b, OperatorStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Public Overrides Function VisitConstructorBlock(node As ConstructorBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, ConstructorBlockSyntax).Update(DirectCast(b, SubNewStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Public Overrides Function VisitAccessorBlock(node As AccessorBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, AccessorBlockSyntax).Update(node.Kind, DirectCast(b, AccessorStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Private Function VisitMethodBlockBaseSyntax(node As MethodBlockBaseSyntax, updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax)) As MethodBlockBaseSyntax If Me._isNodeOrTokenOutsideSimplifySpans(node) Then If Me._simplifyAllDescendants Then ' One of the ancestor nodes Is within a simplification span, but this node Is outside all simplification spans. ' Add DontSimplifyAnnotation to node to ensure it doesn't get simplified. Return node.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) Else Return node End If End If Dim savedSimplifyAllDescendants = Me._simplifyAllDescendants Me._simplifyAllDescendants = Me._simplifyAllDescendants OrElse node.HasAnnotation(Simplifier.Annotation) Dim begin = DirectCast(Visit(node.BlockStatement), MethodBaseSyntax) Dim endStatement = DirectCast(Visit(node.EndBlockStatement), EndBlockStatementSyntax) ' Certain reducers for VB (escaping, parentheses) require to operate on the entire method body, rather than individual statements. ' Hence, we need to reduce the entire method body as a single unit. ' However, there is no SyntaxNode for the method body or statement list, hence we add the MethodBlockBaseSyntax to the list of nodes to be reduced. ' Subsequently, when the AbstractReducer is handed a MethodBlockBaseSyntax, it will reduce only the statement list inside it. If Me._simplifyAllDescendants OrElse node.Statements.Any(Function(s) s.DescendantNodesAndTokensAndSelf(s_containsAnnotations, descendIntoTrivia:=True).Any(s_hasSimplifierAnnotation)) Then Me._insideSpeculatedNode = True Dim statements = VisitList(node.Statements) Dim rewrittenNode = updateFunc(node, node.BlockStatement, statements, node.EndBlockStatement) Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(rewrittenNode, Me._simplifyAllDescendants, node)) Me._insideSpeculatedNode = False End If Me._simplifyAllDescendants = savedSimplifyAllDescendants Return node End Function 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 Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicSimplificationService Inherits AbstractSimplificationService(Of ExpressionSyntax, ExecutableStatementSyntax, CrefReferenceSyntax) Private Class NodesAndTokensToReduceComputer Inherits VisualBasicSyntaxRewriter Private ReadOnly _nodesAndTokensToReduce As List(Of NodeOrTokenToReduce) Private ReadOnly _isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean) Private Shared ReadOnly s_containsAnnotations As Func(Of SyntaxNode, Boolean) = Function(n) n.ContainsAnnotations Private Shared ReadOnly s_hasSimplifierAnnotation As Func(Of SyntaxNodeOrToken, Boolean) = Function(n) n.HasAnnotation(Simplifier.Annotation) Private _simplifyAllDescendants As Boolean Private _insideSpeculatedNode As Boolean ''' <summary> ''' Computes a list of nodes and tokens that need to be reduced in the given syntax root. ''' </summary> Public Shared Function Compute(root As SyntaxNode, isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean)) As ImmutableArray(Of NodeOrTokenToReduce) Dim reduceNodeComputer = New NodesAndTokensToReduceComputer(isNodeOrTokenOutsideSimplifySpans) reduceNodeComputer.Visit(root) Return reduceNodeComputer._nodesAndTokensToReduce.ToImmutableArray() End Function Private Sub New(isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean)) MyBase.New(visitIntoStructuredTrivia:=True) Me._isNodeOrTokenOutsideSimplifySpans = isNodeOrTokenOutsideSimplifySpans Me._nodesAndTokensToReduce = New List(Of NodeOrTokenToReduce)() Me._simplifyAllDescendants = False Me._insideSpeculatedNode = False End Sub Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode If node Is Nothing Then Return node End If If Me._isNodeOrTokenOutsideSimplifySpans(node) Then If Me._simplifyAllDescendants Then ' One of the ancestor nodes is within a simplification span, but this node Is outside all simplification spans. ' Add DontSimplifyAnnotation to node to ensure it doesn't get simplified. Return node.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) Else Return node End If End If Dim savedSimplifyAllDescendants = Me._simplifyAllDescendants Me._simplifyAllDescendants = Me._simplifyAllDescendants OrElse node.HasAnnotation(Simplifier.Annotation) If Not Me._insideSpeculatedNode AndAlso SpeculationAnalyzer.CanSpeculateOnNode(node) Then If Me._simplifyAllDescendants OrElse node.DescendantNodesAndTokens(s_containsAnnotations, descendIntoTrivia:=True).Any(s_hasSimplifierAnnotation) Then Me._insideSpeculatedNode = True Dim rewrittenNode = MyBase.Visit(node) Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(rewrittenNode, _simplifyAllDescendants, node)) Me._insideSpeculatedNode = False End If ElseIf node.ContainsAnnotations OrElse savedSimplifyAllDescendants Then If Not Me._insideSpeculatedNode AndAlso IsNodeVariableDeclaratorOfFieldDeclaration(node) AndAlso Me._simplifyAllDescendants Then Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(node, False, node, False)) End If node = MyBase.Visit(node) End If Me._simplifyAllDescendants = savedSimplifyAllDescendants Return node End Function Private Shared Function IsNodeVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As Boolean Return node IsNot Nothing AndAlso node.Kind() = SyntaxKind.VariableDeclarator AndAlso node.Parent IsNot Nothing AndAlso node.Parent.Kind() = SyntaxKind.FieldDeclaration End Function Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken If Me._isNodeOrTokenOutsideSimplifySpans(token) Then If Me._simplifyAllDescendants Then ' One of the ancestor nodes is within a simplification span, but this token Is outside all simplification spans. ' Add DontSimplifyAnnotation to token to ensure it doesn't get simplified. Return token.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) Else Return token End If End If Dim savedSimplifyAllDescendants = Me._simplifyAllDescendants Me._simplifyAllDescendants = Me._simplifyAllDescendants OrElse token.HasAnnotation(Simplifier.Annotation) If Me._simplifyAllDescendants AndAlso Not Me._insideSpeculatedNode AndAlso token.Kind <> SyntaxKind.None Then Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(token, simplifyAllDescendants:=True, originalNodeOrToken:=token)) End If If token.ContainsAnnotations OrElse savedSimplifyAllDescendants Then token = MyBase.VisitToken(token) End If Me._simplifyAllDescendants = savedSimplifyAllDescendants Return token End Function Public Overrides Function VisitTrivia(trivia As SyntaxTrivia) As SyntaxTrivia If trivia.HasStructure Then Dim savedInsideSpeculatedNode = Me._insideSpeculatedNode Me._insideSpeculatedNode = False MyBase.VisitTrivia(trivia) Me._insideSpeculatedNode = savedInsideSpeculatedNode End If Return trivia End Function Public Overrides Function VisitMethodBlock(node As MethodBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, MethodBlockSyntax).Update(node.Kind, DirectCast(b, MethodStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Public Overrides Function VisitOperatorBlock(node As OperatorBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, OperatorBlockSyntax).Update(DirectCast(b, OperatorStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Public Overrides Function VisitConstructorBlock(node As ConstructorBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, ConstructorBlockSyntax).Update(DirectCast(b, SubNewStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Public Overrides Function VisitAccessorBlock(node As AccessorBlockSyntax) As SyntaxNode Dim updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax) = Function(n, b, s, e) Return DirectCast(n, AccessorBlockSyntax).Update(node.Kind, DirectCast(b, AccessorStatementSyntax), s, e) End Function Return VisitMethodBlockBaseSyntax(node, updateFunc) End Function Private Function VisitMethodBlockBaseSyntax(node As MethodBlockBaseSyntax, updateFunc As Func(Of MethodBlockBaseSyntax, MethodBaseSyntax, SyntaxList(Of StatementSyntax), EndBlockStatementSyntax, MethodBlockBaseSyntax)) As MethodBlockBaseSyntax If Me._isNodeOrTokenOutsideSimplifySpans(node) Then If Me._simplifyAllDescendants Then ' One of the ancestor nodes Is within a simplification span, but this node Is outside all simplification spans. ' Add DontSimplifyAnnotation to node to ensure it doesn't get simplified. Return node.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) Else Return node End If End If Dim savedSimplifyAllDescendants = Me._simplifyAllDescendants Me._simplifyAllDescendants = Me._simplifyAllDescendants OrElse node.HasAnnotation(Simplifier.Annotation) Dim begin = DirectCast(Visit(node.BlockStatement), MethodBaseSyntax) Dim endStatement = DirectCast(Visit(node.EndBlockStatement), EndBlockStatementSyntax) ' Certain reducers for VB (escaping, parentheses) require to operate on the entire method body, rather than individual statements. ' Hence, we need to reduce the entire method body as a single unit. ' However, there is no SyntaxNode for the method body or statement list, hence we add the MethodBlockBaseSyntax to the list of nodes to be reduced. ' Subsequently, when the AbstractReducer is handed a MethodBlockBaseSyntax, it will reduce only the statement list inside it. If Me._simplifyAllDescendants OrElse node.Statements.Any(Function(s) s.DescendantNodesAndTokensAndSelf(s_containsAnnotations, descendIntoTrivia:=True).Any(s_hasSimplifierAnnotation)) Then Me._insideSpeculatedNode = True Dim statements = VisitList(node.Statements) Dim rewrittenNode = updateFunc(node, node.BlockStatement, statements, node.EndBlockStatement) Me._nodesAndTokensToReduce.Add(New NodeOrTokenToReduce(rewrittenNode, Me._simplifyAllDescendants, node)) Me._insideSpeculatedNode = False End If Me._simplifyAllDescendants = savedSimplifyAllDescendants Return node End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/EditorFeatures/Test/ValueTracking/VisualBasicValueTrackingTests.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.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.ValueTracking { [UseExportProvider] public class VisualBasicValueTrackingTests : AbstractBaseValueTrackingTests { protected override TestWorkspace CreateWorkspace(string code, TestComposition composition) => TestWorkspace.CreateVisualBasic(code, composition: composition); [Theory] [CombinatorialData] public async Task TestProperty(TestHost testHost) { var code = @" Class C Private _s As String Public Property $$S() As String Get Return _s End Get Set(ByVal value As String) _s = value End Set End Property Public Sub SetS(s As String) Me.S = s End Sub Public Function GetS() As String Return Me.S End Function End Class "; using var workspace = CreateWorkspace(code, testHost); var initialItems = await GetTrackedItemsAsync(workspace); // // property S // |> Me.S = s [Code.vb:14] // |> Public Property S() As String [Code.vb:3] // Assert.Equal(2, initialItems.Length); ValidateItem(initialItems[0], 14); ValidateItem(initialItems[1], 3); } [Theory] [CombinatorialData] public async Task TestField(TestHost testHost) { var code = @" Class C Private $$_s As String = """" Public Sub SetS(s As String) Me._s = s End Sub Public Function GetS() As String Return Me._s End Function End Class "; using var workspace = CreateWorkspace(code, testHost); var initialItems = await GetTrackedItemsAsync(workspace); // // field _s // |> Me._s = s [Code.vb:4] // |> Private _s As String = "" [Code.vb:2] // await ValidateItemsAsync( workspace, itemInfo: new[] { (5, "s"), (2, "_s") }); } [Theory] [CombinatorialData] public async Task TestLocal(TestHost testHost) { var code = @" Class C Public Function Add(x As Integer, y As Integer) As Integer Dim $$z = x z += y Return z End Function End Class "; using var workspace = CreateWorkspace(code, testHost); var initialItems = await GetTrackedItemsAsync(workspace); // // local variable z // |> z += y [Code.vb:4] // |> Dim z = x [Code.vb:3] // Assert.Equal(2, initialItems.Length); ValidateItem(initialItems[0], 4); ValidateItem(initialItems[1], 3); } [Theory] [CombinatorialData] public async Task TestParameter(TestHost testHost) { var code = @" Class C Public Function Add($$x As Integer, y As Integer) As Integer x += y Return x End Function End Class "; using var workspace = CreateWorkspace(code, testHost); var initialItems = await GetTrackedItemsAsync(workspace); // // parameter x // |> x += y [Code.vb:3] // |> Public Function Add(x As integer, y As Integer) As Integer [Code.vb:2] // Assert.Equal(2, initialItems.Length); ValidateItem(initialItems[0], 3); ValidateItem(initialItems[1], 2); } [Theory] [CombinatorialData] public async Task TestVariableReferenceStart(TestHost testHost) { var code = @" Class Test Public Sub M() Dim x = GetM() Console.Write(x) Dim y = $$x + 1 End Sub Public Function GetM() As Integer Dim x = 0 Return x End Function End Class"; // // |> Dim y = x + 1 [Code.vb:7] // |> Dim x = GetM() [Code.vb:5] // |> Return x; [Code.vb:13] // |> Dim x = 0; [Code.vb:12] using var workspace = CreateWorkspace(code, testHost); var items = await ValidateItemsAsync( workspace, itemInfo: new[] { (5, "x") // |> Dim y = [|x|] + 1; [Code.vb:7] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (3, "GetM()") // |> Dim x = [|GetM()|] [Code.vb:5] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (10, "x") // |> return [|x|]; [Code.vb:13] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (9, "0") // |> var x = [|0|]; [Code.vb:12] }); await ValidateChildrenEmptyAsync(workspace, items.Single()); } [Theory] [CombinatorialData] public async Task TestVariableReferenceStart2(TestHost testHost) { var code = @" Class Test Public Sub M() Dim x = GetM() Console.Write($$x) Dim y = x + 1 End Sub Public Function GetM() As Integer Dim x = 0 Return x End Function End Class"; // // |> Dim y = x + 1 [Code.vb:7] // |> Dim x = GetM() [Code.vb:5] // |> Return x; [Code.vb:13] // |> Dim x = 0; [Code.vb:12] using var workspace = CreateWorkspace(code, testHost); var items = await ValidateItemsAsync( workspace, itemInfo: new[] { (4, "x") // |> Dim y = [|x|] + 1; [Code.vb:7] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (3, "GetM()") // |> Dim x = [|GetM()|] [Code.vb:5] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (10, "x") // |> return [|x|]; [Code.vb:13] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (9, "0") // |> var x = [|0|]; [Code.vb:12] }); await ValidateChildrenEmptyAsync(workspace, items.Single()); } [Theory] [CombinatorialData] public async Task TestMultipleDeclarators(TestHost testHost) { var code = @" Imports System Class Test Public Sub M() Dim x = GetM(), z = 1, m As Boolean, n As Boolean, o As Boolean Console.Write(x) Dim y = $$x + 1 End Sub Public Function GetM() As Integer Dim x = 0 Return x End Function End Class"; // // |> Dim y = x + 1 [Code.vb:7] // |> Dim x = GetM(), z = 1, m As Boolean, n As Boolean, o As Boolean [Code.vb:5] // |> Return x; [Code.vb:12] // |> Dim x = 0; [Code.vb:11] using var workspace = CreateWorkspace(code, testHost); var items = await ValidateItemsAsync( workspace, itemInfo: new[] { (7, "x") // |> Dim y = [|x|] + 1; [Code.vb:7] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (5, "GetM()") // |> Dim x = [|GetM()|], z = 1, m As Boolean, n As Boolean, o As Boolean [Code.vb:5] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (12, "x") // |> return [|x|]; [Code.vb:12] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (11, "0") // |> var x = [|0|]; [Code.vb:11] }); await ValidateChildrenEmptyAsync(workspace, items.Single()); } } }
// 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.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.ValueTracking { [UseExportProvider] public class VisualBasicValueTrackingTests : AbstractBaseValueTrackingTests { protected override TestWorkspace CreateWorkspace(string code, TestComposition composition) => TestWorkspace.CreateVisualBasic(code, composition: composition); [Theory] [CombinatorialData] public async Task TestProperty(TestHost testHost) { var code = @" Class C Private _s As String Public Property $$S() As String Get Return _s End Get Set(ByVal value As String) _s = value End Set End Property Public Sub SetS(s As String) Me.S = s End Sub Public Function GetS() As String Return Me.S End Function End Class "; using var workspace = CreateWorkspace(code, testHost); var initialItems = await GetTrackedItemsAsync(workspace); // // property S // |> Me.S = s [Code.vb:14] // |> Public Property S() As String [Code.vb:3] // Assert.Equal(2, initialItems.Length); ValidateItem(initialItems[0], 14); ValidateItem(initialItems[1], 3); } [Theory] [CombinatorialData] public async Task TestField(TestHost testHost) { var code = @" Class C Private $$_s As String = """" Public Sub SetS(s As String) Me._s = s End Sub Public Function GetS() As String Return Me._s End Function End Class "; using var workspace = CreateWorkspace(code, testHost); var initialItems = await GetTrackedItemsAsync(workspace); // // field _s // |> Me._s = s [Code.vb:4] // |> Private _s As String = "" [Code.vb:2] // await ValidateItemsAsync( workspace, itemInfo: new[] { (5, "s"), (2, "_s") }); } [Theory] [CombinatorialData] public async Task TestLocal(TestHost testHost) { var code = @" Class C Public Function Add(x As Integer, y As Integer) As Integer Dim $$z = x z += y Return z End Function End Class "; using var workspace = CreateWorkspace(code, testHost); var initialItems = await GetTrackedItemsAsync(workspace); // // local variable z // |> z += y [Code.vb:4] // |> Dim z = x [Code.vb:3] // Assert.Equal(2, initialItems.Length); ValidateItem(initialItems[0], 4); ValidateItem(initialItems[1], 3); } [Theory] [CombinatorialData] public async Task TestParameter(TestHost testHost) { var code = @" Class C Public Function Add($$x As Integer, y As Integer) As Integer x += y Return x End Function End Class "; using var workspace = CreateWorkspace(code, testHost); var initialItems = await GetTrackedItemsAsync(workspace); // // parameter x // |> x += y [Code.vb:3] // |> Public Function Add(x As integer, y As Integer) As Integer [Code.vb:2] // Assert.Equal(2, initialItems.Length); ValidateItem(initialItems[0], 3); ValidateItem(initialItems[1], 2); } [Theory] [CombinatorialData] public async Task TestVariableReferenceStart(TestHost testHost) { var code = @" Class Test Public Sub M() Dim x = GetM() Console.Write(x) Dim y = $$x + 1 End Sub Public Function GetM() As Integer Dim x = 0 Return x End Function End Class"; // // |> Dim y = x + 1 [Code.vb:7] // |> Dim x = GetM() [Code.vb:5] // |> Return x; [Code.vb:13] // |> Dim x = 0; [Code.vb:12] using var workspace = CreateWorkspace(code, testHost); var items = await ValidateItemsAsync( workspace, itemInfo: new[] { (5, "x") // |> Dim y = [|x|] + 1; [Code.vb:7] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (3, "GetM()") // |> Dim x = [|GetM()|] [Code.vb:5] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (10, "x") // |> return [|x|]; [Code.vb:13] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (9, "0") // |> var x = [|0|]; [Code.vb:12] }); await ValidateChildrenEmptyAsync(workspace, items.Single()); } [Theory] [CombinatorialData] public async Task TestVariableReferenceStart2(TestHost testHost) { var code = @" Class Test Public Sub M() Dim x = GetM() Console.Write($$x) Dim y = x + 1 End Sub Public Function GetM() As Integer Dim x = 0 Return x End Function End Class"; // // |> Dim y = x + 1 [Code.vb:7] // |> Dim x = GetM() [Code.vb:5] // |> Return x; [Code.vb:13] // |> Dim x = 0; [Code.vb:12] using var workspace = CreateWorkspace(code, testHost); var items = await ValidateItemsAsync( workspace, itemInfo: new[] { (4, "x") // |> Dim y = [|x|] + 1; [Code.vb:7] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (3, "GetM()") // |> Dim x = [|GetM()|] [Code.vb:5] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (10, "x") // |> return [|x|]; [Code.vb:13] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (9, "0") // |> var x = [|0|]; [Code.vb:12] }); await ValidateChildrenEmptyAsync(workspace, items.Single()); } [Theory] [CombinatorialData] public async Task TestMultipleDeclarators(TestHost testHost) { var code = @" Imports System Class Test Public Sub M() Dim x = GetM(), z = 1, m As Boolean, n As Boolean, o As Boolean Console.Write(x) Dim y = $$x + 1 End Sub Public Function GetM() As Integer Dim x = 0 Return x End Function End Class"; // // |> Dim y = x + 1 [Code.vb:7] // |> Dim x = GetM(), z = 1, m As Boolean, n As Boolean, o As Boolean [Code.vb:5] // |> Return x; [Code.vb:12] // |> Dim x = 0; [Code.vb:11] using var workspace = CreateWorkspace(code, testHost); var items = await ValidateItemsAsync( workspace, itemInfo: new[] { (7, "x") // |> Dim y = [|x|] + 1; [Code.vb:7] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (5, "GetM()") // |> Dim x = [|GetM()|], z = 1, m As Boolean, n As Boolean, o As Boolean [Code.vb:5] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (12, "x") // |> return [|x|]; [Code.vb:12] }); items = await ValidateChildrenAsync( workspace, items.Single(), childInfo: new[] { (11, "0") // |> var x = [|0|]; [Code.vb:11] }); await ValidateChildrenEmptyAsync(workspace, items.Single()); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/DimKeywordRecommender.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.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Dim" keyword in all appropriate contexts. ''' </summary> Friend Class DimKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Dim", VBFeaturesResources.Declares_and_allocates_storage_space_for_one_or_more_variables_Dim_var_bracket_As_bracket_New_bracket_dataType_bracket_boundList_bracket_bracket_bracket_initializer_bracket_bracket_var2_bracket)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, CancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) ' It can start a statement If context.IsMultiLineStatementContext Then Return s_keywords End If If context.IsTypeMemberDeclarationKeywordContext Then Dim modifiers = context.ModifierCollectionFacts ' In Dev10, we don't show it after Const (but will after ReadOnly, even though the formatter removes it) If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Field) AndAlso modifiers.MutabilityOrWithEventsKeyword.Kind <> SyntaxKind.ConstKeyword AndAlso modifiers.DimKeyword.Kind = SyntaxKind.None Then Return s_keywords End If End If Return ImmutableArray(Of RecommendedKeyword).Empty 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.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Dim" keyword in all appropriate contexts. ''' </summary> Friend Class DimKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Dim", VBFeaturesResources.Declares_and_allocates_storage_space_for_one_or_more_variables_Dim_var_bracket_As_bracket_New_bracket_dataType_bracket_boundList_bracket_bracket_bracket_initializer_bracket_bracket_var2_bracket)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, CancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) ' It can start a statement If context.IsMultiLineStatementContext Then Return s_keywords End If If context.IsTypeMemberDeclarationKeywordContext Then Dim modifiers = context.ModifierCollectionFacts ' In Dev10, we don't show it after Const (but will after ReadOnly, even though the formatter removes it) If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Field) AndAlso modifiers.MutabilityOrWithEventsKeyword.Kind <> SyntaxKind.ConstKeyword AndAlso modifiers.DimKeyword.Kind = SyntaxKind.None Then Return s_keywords End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./docs/features/ref-reassignment.md
Ref Local and Parameter Reassignment ==================================== In C# 7.2, `ref` locals and parameters cannot be assigned new references, only assigned values which reassign the underlying storage to the given value. C# 7.3 introduces a new type of expression, a ref-assignment expression. The syntax is as follows ``` ref_assignment : identifier '=' 'ref' expression ``` The identifier on the left-hand side of a *ref_assignment* must be a `ref` or `ref readonly` local variable, or an `in`, `ref`, or `out` paramater. Ref assignments allow ref local variables or parameters, which represent references to storage locations, to be assigned different references. This does not include the `this` reference, even in structs. The expression on the right-hand side must have a storage location, i.e. it must be an "l-value." This l-value must be "ref-compatible" with the variable being ref-assigned, where ref-compatible means: * The type of left-hand side and the type of the right-hand side must have an identity conversion between them. * Writeable ref variables cannot be assigned read-only l-values. Readonly ref variables can be assigned either read-only or writeable l-values. The result of the ref-assignment expression is itself an "l-value" and the resulting storage location is read-only if and only if the left-hand side of the assignment is a read-only ref variable. The storage location for the right-hand side must be definitely assigned before it can be used in a ref-assignment expression. In addition, the storage location referenced by an `out` parameter must be definitely assigned before the `out` parameter is ref-reassigned to a new reference. The lifetime for a `ref` local or parameter is fixed on declaration and cannot be reassigned with ref-reassignment. The lifetime requirements for the right-hand expression are the same as for the right-hand expression in a variable assignment, identical to the lifetime for Span&lt;T> assignments.
Ref Local and Parameter Reassignment ==================================== In C# 7.2, `ref` locals and parameters cannot be assigned new references, only assigned values which reassign the underlying storage to the given value. C# 7.3 introduces a new type of expression, a ref-assignment expression. The syntax is as follows ``` ref_assignment : identifier '=' 'ref' expression ``` The identifier on the left-hand side of a *ref_assignment* must be a `ref` or `ref readonly` local variable, or an `in`, `ref`, or `out` paramater. Ref assignments allow ref local variables or parameters, which represent references to storage locations, to be assigned different references. This does not include the `this` reference, even in structs. The expression on the right-hand side must have a storage location, i.e. it must be an "l-value." This l-value must be "ref-compatible" with the variable being ref-assigned, where ref-compatible means: * The type of left-hand side and the type of the right-hand side must have an identity conversion between them. * Writeable ref variables cannot be assigned read-only l-values. Readonly ref variables can be assigned either read-only or writeable l-values. The result of the ref-assignment expression is itself an "l-value" and the resulting storage location is read-only if and only if the left-hand side of the assignment is a read-only ref variable. The storage location for the right-hand side must be definitely assigned before it can be used in a ref-assignment expression. In addition, the storage location referenced by an `out` parameter must be definitely assigned before the `out` parameter is ref-reassigned to a new reference. The lifetime for a `ref` local or parameter is fixed on declaration and cannot be reassigned with ref-reassignment. The lifetime requirements for the right-hand expression are the same as for the right-hand expression in a variable assignment, identical to the lifetime for Span&lt;T> assignments.
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/LanguageServer/ProtocolUnitTests/Ordering/FailingRequestHandler.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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.RequestOrdering { [Shared, ExportRoslynLanguagesLspRequestHandlerProvider, PartNotDiscoverable] [ProvidesMethod(FailingRequestHandler.MethodName)] internal class FailingRequestHandlerProvider : AbstractRequestHandlerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FailingRequestHandlerProvider() { } public override ImmutableArray<IRequestHandler> CreateRequestHandlers() { return ImmutableArray.Create<IRequestHandler>(new FailingRequestHandler()); } } internal class FailingRequestHandler : IRequestHandler<TestRequest, TestResponse> { public const string MethodName = nameof(FailingRequestHandler); private const int Delay = 100; public string Method => MethodName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public TextDocumentIdentifier GetTextDocumentIdentifier(TestRequest request) => null; public async Task<TestResponse> HandleRequestAsync(TestRequest request, RequestContext context, CancellationToken cancellationToken) { await Task.Delay(Delay, cancellationToken).ConfigureAwait(false); throw new InvalidOperationException(); } } }
// 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.RequestOrdering { [Shared, ExportRoslynLanguagesLspRequestHandlerProvider, PartNotDiscoverable] [ProvidesMethod(FailingRequestHandler.MethodName)] internal class FailingRequestHandlerProvider : AbstractRequestHandlerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FailingRequestHandlerProvider() { } public override ImmutableArray<IRequestHandler> CreateRequestHandlers() { return ImmutableArray.Create<IRequestHandler>(new FailingRequestHandler()); } } internal class FailingRequestHandler : IRequestHandler<TestRequest, TestResponse> { public const string MethodName = nameof(FailingRequestHandler); private const int Delay = 100; public string Method => MethodName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public TextDocumentIdentifier GetTextDocumentIdentifier(TestRequest request) => null; public async Task<TestResponse> HandleRequestAsync(TestRequest request, RequestContext context, CancellationToken cancellationToken) { await Task.Delay(Delay, cancellationToken).ConfigureAwait(false); throw new InvalidOperationException(); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/Server/VBCSCompilerTests/BuildServerConnectionTests.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 System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public sealed class BuildServerConnectionTests : IDisposable { internal TempRoot TempRoot { get; } = new TempRoot(); internal XunitCompilerServerLogger Logger { get; } public BuildServerConnectionTests(ITestOutputHelper testOutputHelper) { Logger = new XunitCompilerServerLogger(testOutputHelper); } public void Dispose() { TempRoot.Dispose(); } [Fact] public async Task OnlyStartOneServer() { ServerData? serverData = null; try { var pipeName = ServerUtil.GetPipeName(); var workingDirectory = TempRoot.CreateDirectory().Path; for (var i = 0; i < 5; i++) { var response = await BuildServerConnection.RunServerBuildRequestAsync( ProtocolUtil.CreateEmptyCSharp(workingDirectory), pipeName, timeoutOverride: Timeout.Infinite, tryCreateServerFunc: (pipeName, logger) => { Assert.Null(serverData); serverData = ServerData.Create(logger, pipeName); return true; }, Logger, cancellationToken: default); Assert.True(response is CompletedBuildResponse); } } finally { serverData?.Dispose(); } } [Fact] public async Task UseExistingServer() { using var serverData = await ServerUtil.CreateServer(Logger); var ran = false; var workingDirectory = TempRoot.CreateDirectory().Path; for (var i = 0; i < 5; i++) { var response = await BuildServerConnection.RunServerBuildRequestAsync( ProtocolUtil.CreateEmptyCSharp(workingDirectory), serverData.PipeName, timeoutOverride: Timeout.Infinite, tryCreateServerFunc: (_, _) => { ran = true; return false; }, Logger, cancellationToken: default); Assert.True(response is CompletedBuildResponse); } Assert.False(ran); } /// <summary> /// Simulate the case where the server process crashes or hangs on startup /// and make sure the client properly fails /// </summary> [Fact] public async Task SimulateServerCrashingOnStartup() { var pipeName = ServerUtil.GetPipeName(); var ran = false; var response = await BuildServerConnection.RunServerBuildRequestAsync( ProtocolUtil.CreateEmptyCSharp(TempRoot.CreateDirectory().Path), pipeName, timeoutOverride: (int)TimeSpan.FromSeconds(2).TotalMilliseconds, tryCreateServerFunc: (_, _) => { ran = true; // Correct this is a lie. The server did not start. But it also does a nice // job of simulating a hung or crashed server. return true; }, Logger, cancellationToken: default); Assert.True(response is RejectedBuildResponse); Assert.True(ran); } [Fact] public async Task FailedServer() { var pipeName = ServerUtil.GetPipeName(); var workingDirectory = TempRoot.CreateDirectory().Path; var count = 0; for (var i = 0; i < 5; i++) { var response = await BuildServerConnection.RunServerBuildRequestAsync( ProtocolUtil.CreateEmptyCSharp(workingDirectory), pipeName, timeoutOverride: Timeout.Infinite, tryCreateServerFunc: (_, _) => { count++; return false; }, Logger, cancellationToken: default); Assert.True(response is RejectedBuildResponse); } Assert.Equal(5, 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 System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public sealed class BuildServerConnectionTests : IDisposable { internal TempRoot TempRoot { get; } = new TempRoot(); internal XunitCompilerServerLogger Logger { get; } public BuildServerConnectionTests(ITestOutputHelper testOutputHelper) { Logger = new XunitCompilerServerLogger(testOutputHelper); } public void Dispose() { TempRoot.Dispose(); } [Fact] public async Task OnlyStartOneServer() { ServerData? serverData = null; try { var pipeName = ServerUtil.GetPipeName(); var workingDirectory = TempRoot.CreateDirectory().Path; for (var i = 0; i < 5; i++) { var response = await BuildServerConnection.RunServerBuildRequestAsync( ProtocolUtil.CreateEmptyCSharp(workingDirectory), pipeName, timeoutOverride: Timeout.Infinite, tryCreateServerFunc: (pipeName, logger) => { Assert.Null(serverData); serverData = ServerData.Create(logger, pipeName); return true; }, Logger, cancellationToken: default); Assert.True(response is CompletedBuildResponse); } } finally { serverData?.Dispose(); } } [Fact] public async Task UseExistingServer() { using var serverData = await ServerUtil.CreateServer(Logger); var ran = false; var workingDirectory = TempRoot.CreateDirectory().Path; for (var i = 0; i < 5; i++) { var response = await BuildServerConnection.RunServerBuildRequestAsync( ProtocolUtil.CreateEmptyCSharp(workingDirectory), serverData.PipeName, timeoutOverride: Timeout.Infinite, tryCreateServerFunc: (_, _) => { ran = true; return false; }, Logger, cancellationToken: default); Assert.True(response is CompletedBuildResponse); } Assert.False(ran); } /// <summary> /// Simulate the case where the server process crashes or hangs on startup /// and make sure the client properly fails /// </summary> [Fact] public async Task SimulateServerCrashingOnStartup() { var pipeName = ServerUtil.GetPipeName(); var ran = false; var response = await BuildServerConnection.RunServerBuildRequestAsync( ProtocolUtil.CreateEmptyCSharp(TempRoot.CreateDirectory().Path), pipeName, timeoutOverride: (int)TimeSpan.FromSeconds(2).TotalMilliseconds, tryCreateServerFunc: (_, _) => { ran = true; // Correct this is a lie. The server did not start. But it also does a nice // job of simulating a hung or crashed server. return true; }, Logger, cancellationToken: default); Assert.True(response is RejectedBuildResponse); Assert.True(ran); } [Fact] public async Task FailedServer() { var pipeName = ServerUtil.GetPipeName(); var workingDirectory = TempRoot.CreateDirectory().Path; var count = 0; for (var i = 0; i < 5; i++) { var response = await BuildServerConnection.RunServerBuildRequestAsync( ProtocolUtil.CreateEmptyCSharp(workingDirectory), pipeName, timeoutOverride: Timeout.Infinite, tryCreateServerFunc: (_, _) => { count++; return false; }, Logger, cancellationToken: default); Assert.True(response is RejectedBuildResponse); } Assert.Equal(5, count); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/Core/Portable/Completion/Providers/AbstractRecommendationServiceBasedCompletionProvider.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.Linq; using System.Threading; using System.Threading.Tasks; 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractRecommendationServiceBasedCompletionProvider<TSyntaxContext> : AbstractSymbolCompletionProvider<TSyntaxContext> where TSyntaxContext : SyntaxContext { protected abstract Task<bool> ShouldPreselectInferredTypesAsync(CompletionContext? completionContext, int position, OptionSet options, CancellationToken cancellationToken); protected abstract CompletionItemRules GetCompletionItemRules(ImmutableArray<(ISymbol symbol, bool preselect)> symbols, TSyntaxContext context); protected abstract CompletionItemSelectionBehavior PreselectedItemSelectionBehavior { get; } protected abstract bool IsInstrinsic(ISymbol symbol); protected abstract bool IsTriggerOnDot(SyntaxToken token, int characterPosition); protected sealed override bool ShouldCollectTelemetryForTargetTypeCompletion => true; protected sealed override async Task<ImmutableArray<(ISymbol symbol, bool preselect)>> GetSymbolsAsync( CompletionContext? completionContext, TSyntaxContext context, int position, OptionSet options, CancellationToken cancellationToken) { var recommender = context.GetLanguageService<IRecommendationService>(); var recommendedSymbols = recommender.GetRecommendedSymbolsAtPosition(context.Workspace, context.SemanticModel, position, options, cancellationToken); var shouldPreselectInferredTypes = await ShouldPreselectInferredTypesAsync(completionContext, position, options, cancellationToken).ConfigureAwait(false); if (!shouldPreselectInferredTypes) return recommendedSymbols.NamedSymbols.SelectAsArray(s => (s, preselect: false)); var inferredTypes = context.InferredTypes.Where(t => t.SpecialType != SpecialType.System_Void).ToSet(); using var _ = ArrayBuilder<(ISymbol symbol, bool preselect)>.GetInstance(out var result); foreach (var symbol in recommendedSymbols.NamedSymbols) { // Don't preselect intrinsic type symbols so we can preselect their keywords instead. We will also // ignore nullability for purposes of preselection -- if a method is returning a string? but we've // inferred we're assigning to a string or vice versa we'll still count those as the same. var preselect = inferredTypes.Contains(GetSymbolType(symbol), SymbolEqualityComparer.Default) && !IsInstrinsic(symbol); result.Add((symbol, preselect)); } return result.ToImmutable(); } private static ITypeSymbol? GetSymbolType(ISymbol symbol) => symbol is IMethodSymbol method ? method.ReturnType : symbol.GetSymbolType(); protected override CompletionItem CreateItem( CompletionContext completionContext, string displayText, string displayTextSuffix, string insertionText, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, TSyntaxContext context, SupportedPlatformData? supportedPlatformData) { var rules = GetCompletionItemRules(symbols, context); var preselect = symbols.Any(t => t.preselect); var matchPriority = preselect ? ComputeSymbolMatchPriority(symbols[0].symbol) : MatchPriority.Default; rules = rules.WithMatchPriority(matchPriority); if (ShouldSoftSelectInArgumentList(completionContext, context, preselect)) { rules = rules.WithSelectionBehavior(CompletionItemSelectionBehavior.SoftSelection); } else if (context.IsRightSideOfNumericType) { rules = rules.WithSelectionBehavior(CompletionItemSelectionBehavior.SoftSelection); } else if (preselect) { rules = rules.WithSelectionBehavior(PreselectedItemSelectionBehavior); } return SymbolCompletionItem.CreateWithNameAndKind( displayText: displayText, displayTextSuffix: displayTextSuffix, symbols: symbols.SelectAsArray(t => t.symbol), rules: rules, contextPosition: context.Position, insertionText: insertionText, filterText: GetFilterText(symbols[0].symbol, displayText, context), supportedPlatforms: supportedPlatformData); } private static bool ShouldSoftSelectInArgumentList(CompletionContext completionContext, TSyntaxContext context, bool preselect) { return !preselect && completionContext.Trigger.Kind == CompletionTriggerKind.Insertion && context.IsOnArgumentListBracketOrComma && IsArgumentListTriggerCharacter(completionContext.Trigger.Character); } private static bool IsArgumentListTriggerCharacter(char character) => character is ' ' or '(' or '['; private static int ComputeSymbolMatchPriority(ISymbol symbol) { if (symbol.MatchesKind(SymbolKind.Local, SymbolKind.Parameter, SymbolKind.RangeVariable)) { return SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable; } if (symbol.MatchesKind(SymbolKind.Field, SymbolKind.Property)) { return SymbolMatchPriority.PreferFieldOrProperty; } if (symbol.MatchesKind(SymbolKind.Event, SymbolKind.Method)) { return SymbolMatchPriority.PreferEventOrMethod; } return SymbolMatchPriority.PreferType; } protected sealed override async Task<CompletionDescription> GetDescriptionWorkerAsync( Document document, CompletionItem item, CancellationToken cancellationToken) { var position = SymbolCompletionItem.GetContextPosition(item); var name = SymbolCompletionItem.GetSymbolName(item); var kind = SymbolCompletionItem.GetKind(item); var isGeneric = SymbolCompletionItem.GetSymbolIsGeneric(item); var options = document.Project.Solution.Workspace.Options; var relatedDocumentIds = document.Project.Solution.GetRelatedDocumentIds(document.Id); var typeConvertibilityCache = new Dictionary<ITypeSymbol, bool>(SymbolEqualityComparer.Default); foreach (var relatedId in relatedDocumentIds) { var relatedDocument = document.Project.Solution.GetRequiredDocument(relatedId); var context = await CreateContextAsync(relatedDocument, position, cancellationToken).ConfigureAwait(false); var symbols = await TryGetSymbolsForContextAsync(completionContext: null, context, options, cancellationToken).ConfigureAwait(false); if (!symbols.IsDefault) { var bestSymbols = symbols.WhereAsArray(s => SymbolMatches(s, name, kind, isGeneric)); if (bestSymbols.Any()) { if (IsTargetTypeCompletionFilterExperimentEnabled(document.Project.Solution.Workspace) && TryFindFirstSymbolMatchesTargetTypes(_ => context, bestSymbols, typeConvertibilityCache, out var index) && index > 0) { // Since the first symbol is used to get the item description by default, // this would ensure the displayed one matches target types (if there's any). var firstMatch = bestSymbols[index]; bestSymbols = bestSymbols.RemoveAt(index); bestSymbols = bestSymbols.Insert(0, firstMatch); } return await SymbolCompletionItem.GetDescriptionAsync(item, bestSymbols.SelectAsArray(t => t.symbol), document, context.SemanticModel, cancellationToken).ConfigureAwait(false); } } } return CompletionDescription.Empty; static bool SymbolMatches((ISymbol symbol, bool preselect) tuple, string name, SymbolKind? kind, bool isGeneric) { return kind != null && tuple.symbol.Kind == kind && tuple.symbol.Name == name && isGeneric == tuple.symbol.GetArity() > 0; } } protected sealed override async Task<bool> IsSemanticTriggerCharacterAsync(Document document, int characterPosition, CancellationToken cancellationToken) { var result = await IsTriggerOnDotAsync(document, characterPosition, cancellationToken).ConfigureAwait(false); return result ?? true; } protected async Task<bool?> IsTriggerOnDotAsync(Document document, int characterPosition, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (text[characterPosition] != '.') return null; // don't want to trigger after a number. All other cases after dot are ok. var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(characterPosition); return IsTriggerOnDot(token, characterPosition); } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractRecommendationServiceBasedCompletionProvider<TSyntaxContext> : AbstractSymbolCompletionProvider<TSyntaxContext> where TSyntaxContext : SyntaxContext { protected abstract Task<bool> ShouldPreselectInferredTypesAsync(CompletionContext? completionContext, int position, OptionSet options, CancellationToken cancellationToken); protected abstract CompletionItemRules GetCompletionItemRules(ImmutableArray<(ISymbol symbol, bool preselect)> symbols, TSyntaxContext context); protected abstract CompletionItemSelectionBehavior PreselectedItemSelectionBehavior { get; } protected abstract bool IsInstrinsic(ISymbol symbol); protected abstract bool IsTriggerOnDot(SyntaxToken token, int characterPosition); protected sealed override bool ShouldCollectTelemetryForTargetTypeCompletion => true; protected sealed override async Task<ImmutableArray<(ISymbol symbol, bool preselect)>> GetSymbolsAsync( CompletionContext? completionContext, TSyntaxContext context, int position, OptionSet options, CancellationToken cancellationToken) { var recommender = context.GetLanguageService<IRecommendationService>(); var recommendedSymbols = recommender.GetRecommendedSymbolsAtPosition(context.Workspace, context.SemanticModel, position, options, cancellationToken); var shouldPreselectInferredTypes = await ShouldPreselectInferredTypesAsync(completionContext, position, options, cancellationToken).ConfigureAwait(false); if (!shouldPreselectInferredTypes) return recommendedSymbols.NamedSymbols.SelectAsArray(s => (s, preselect: false)); var inferredTypes = context.InferredTypes.Where(t => t.SpecialType != SpecialType.System_Void).ToSet(); using var _ = ArrayBuilder<(ISymbol symbol, bool preselect)>.GetInstance(out var result); foreach (var symbol in recommendedSymbols.NamedSymbols) { // Don't preselect intrinsic type symbols so we can preselect their keywords instead. We will also // ignore nullability for purposes of preselection -- if a method is returning a string? but we've // inferred we're assigning to a string or vice versa we'll still count those as the same. var preselect = inferredTypes.Contains(GetSymbolType(symbol), SymbolEqualityComparer.Default) && !IsInstrinsic(symbol); result.Add((symbol, preselect)); } return result.ToImmutable(); } private static ITypeSymbol? GetSymbolType(ISymbol symbol) => symbol is IMethodSymbol method ? method.ReturnType : symbol.GetSymbolType(); protected override CompletionItem CreateItem( CompletionContext completionContext, string displayText, string displayTextSuffix, string insertionText, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, TSyntaxContext context, SupportedPlatformData? supportedPlatformData) { var rules = GetCompletionItemRules(symbols, context); var preselect = symbols.Any(t => t.preselect); var matchPriority = preselect ? ComputeSymbolMatchPriority(symbols[0].symbol) : MatchPriority.Default; rules = rules.WithMatchPriority(matchPriority); if (ShouldSoftSelectInArgumentList(completionContext, context, preselect)) { rules = rules.WithSelectionBehavior(CompletionItemSelectionBehavior.SoftSelection); } else if (context.IsRightSideOfNumericType) { rules = rules.WithSelectionBehavior(CompletionItemSelectionBehavior.SoftSelection); } else if (preselect) { rules = rules.WithSelectionBehavior(PreselectedItemSelectionBehavior); } return SymbolCompletionItem.CreateWithNameAndKind( displayText: displayText, displayTextSuffix: displayTextSuffix, symbols: symbols.SelectAsArray(t => t.symbol), rules: rules, contextPosition: context.Position, insertionText: insertionText, filterText: GetFilterText(symbols[0].symbol, displayText, context), supportedPlatforms: supportedPlatformData); } private static bool ShouldSoftSelectInArgumentList(CompletionContext completionContext, TSyntaxContext context, bool preselect) { return !preselect && completionContext.Trigger.Kind == CompletionTriggerKind.Insertion && context.IsOnArgumentListBracketOrComma && IsArgumentListTriggerCharacter(completionContext.Trigger.Character); } private static bool IsArgumentListTriggerCharacter(char character) => character is ' ' or '(' or '['; private static int ComputeSymbolMatchPriority(ISymbol symbol) { if (symbol.MatchesKind(SymbolKind.Local, SymbolKind.Parameter, SymbolKind.RangeVariable)) { return SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable; } if (symbol.MatchesKind(SymbolKind.Field, SymbolKind.Property)) { return SymbolMatchPriority.PreferFieldOrProperty; } if (symbol.MatchesKind(SymbolKind.Event, SymbolKind.Method)) { return SymbolMatchPriority.PreferEventOrMethod; } return SymbolMatchPriority.PreferType; } protected sealed override async Task<CompletionDescription> GetDescriptionWorkerAsync( Document document, CompletionItem item, CancellationToken cancellationToken) { var position = SymbolCompletionItem.GetContextPosition(item); var name = SymbolCompletionItem.GetSymbolName(item); var kind = SymbolCompletionItem.GetKind(item); var isGeneric = SymbolCompletionItem.GetSymbolIsGeneric(item); var options = document.Project.Solution.Workspace.Options; var relatedDocumentIds = document.Project.Solution.GetRelatedDocumentIds(document.Id); var typeConvertibilityCache = new Dictionary<ITypeSymbol, bool>(SymbolEqualityComparer.Default); foreach (var relatedId in relatedDocumentIds) { var relatedDocument = document.Project.Solution.GetRequiredDocument(relatedId); var context = await CreateContextAsync(relatedDocument, position, cancellationToken).ConfigureAwait(false); var symbols = await TryGetSymbolsForContextAsync(completionContext: null, context, options, cancellationToken).ConfigureAwait(false); if (!symbols.IsDefault) { var bestSymbols = symbols.WhereAsArray(s => SymbolMatches(s, name, kind, isGeneric)); if (bestSymbols.Any()) { if (IsTargetTypeCompletionFilterExperimentEnabled(document.Project.Solution.Workspace) && TryFindFirstSymbolMatchesTargetTypes(_ => context, bestSymbols, typeConvertibilityCache, out var index) && index > 0) { // Since the first symbol is used to get the item description by default, // this would ensure the displayed one matches target types (if there's any). var firstMatch = bestSymbols[index]; bestSymbols = bestSymbols.RemoveAt(index); bestSymbols = bestSymbols.Insert(0, firstMatch); } return await SymbolCompletionItem.GetDescriptionAsync(item, bestSymbols.SelectAsArray(t => t.symbol), document, context.SemanticModel, cancellationToken).ConfigureAwait(false); } } } return CompletionDescription.Empty; static bool SymbolMatches((ISymbol symbol, bool preselect) tuple, string name, SymbolKind? kind, bool isGeneric) { return kind != null && tuple.symbol.Kind == kind && tuple.symbol.Name == name && isGeneric == tuple.symbol.GetArity() > 0; } } protected sealed override async Task<bool> IsSemanticTriggerCharacterAsync(Document document, int characterPosition, CancellationToken cancellationToken) { var result = await IsTriggerOnDotAsync(document, characterPosition, cancellationToken).ConfigureAwait(false); return result ?? true; } protected async Task<bool?> IsTriggerOnDotAsync(Document document, int characterPosition, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (text[characterPosition] != '.') return null; // don't want to trigger after a number. All other cases after dot are ok. var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(characterPosition); return IsTriggerOnDot(token, characterPosition); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/Core/Portable/InternalUtilities/TextKeyedCache.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 System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using System.Threading; namespace Roslyn.Utilities { internal class TextKeyedCache<T> where T : class { // immutable tuple - text and corresponding item // reference type because we want atomic assignments private class SharedEntryValue { public readonly string Text; public readonly T Item; public SharedEntryValue(string Text, T item) { this.Text = Text; this.Item = item; } } // TODO: Need to tweak the size with more scenarios. // for now this is what works well enough with // Roslyn C# compiler project // Size of local cache. private const int LocalSizeBits = 11; private const int LocalSize = (1 << LocalSizeBits); private const int LocalSizeMask = LocalSize - 1; // max size of shared cache. private const int SharedSizeBits = 16; private const int SharedSize = (1 << SharedSizeBits); private const int SharedSizeMask = SharedSize - 1; // size of bucket in shared cache. (local cache has bucket size 1). private const int SharedBucketBits = 4; private const int SharedBucketSize = (1 << SharedBucketBits); private const int SharedBucketSizeMask = SharedBucketSize - 1; // local cache // simple fast and not threadsafe cache // with limited size and "last add wins" expiration policy private readonly (string Text, int HashCode, T Item)[] _localTable = new (string Text, int HashCode, T Item)[LocalSize]; // shared threadsafe cache // slightly slower than local cache // we read this cache when having a miss in local cache // writes to local cache will update shared cache as well. private static readonly (int HashCode, SharedEntryValue Entry)[] s_sharedTable = new (int HashCode, SharedEntryValue Entry)[SharedSize]; // store a reference to shared cache locally // accessing a static field of a generic type could be nontrivial private readonly (int HashCode, SharedEntryValue Entry)[] _sharedTableInst = s_sharedTable; private readonly StringTable _strings; // random - used for selecting a victim in the shared cache. // TODO: consider whether a counter is random enough private Random? _random; internal TextKeyedCache() : this(null) { } // implement Poolable object pattern #region "Poolable" private TextKeyedCache(ObjectPool<TextKeyedCache<T>>? pool) { _pool = pool; _strings = new StringTable(); } private readonly ObjectPool<TextKeyedCache<T>>? _pool; private static readonly ObjectPool<TextKeyedCache<T>> s_staticPool = CreatePool(); private static ObjectPool<TextKeyedCache<T>> CreatePool() { var pool = new ObjectPool<TextKeyedCache<T>>( pool => new TextKeyedCache<T>(pool), Environment.ProcessorCount * 4); return pool; } public static TextKeyedCache<T> GetInstance() { return s_staticPool.Allocate(); } public void Free() { // leave cache content in the cache, just return it to the pool // Array.Clear(this.localTable, 0, this.localTable.Length); // Array.Clear(sharedTable, 0, sharedTable.Length); _pool?.Free(this); } #endregion // Poolable internal T? FindItem(char[] chars, int start, int len, int hashCode) { // get direct element reference to avoid extra range checks ref var localSlot = ref _localTable[LocalIdxFromHash(hashCode)]; var text = localSlot.Text; if (text != null && localSlot.HashCode == hashCode) { if (StringTable.TextEquals(text, chars.AsSpan(start, len))) { return localSlot.Item; } } SharedEntryValue? e = FindSharedEntry(chars, start, len, hashCode); if (e != null) { localSlot.HashCode = hashCode; localSlot.Text = e.Text; var tk = e.Item; localSlot.Item = tk; return tk; } return null!; } private SharedEntryValue? FindSharedEntry(char[] chars, int start, int len, int hashCode) { var arr = _sharedTableInst; int idx = SharedIdxFromHash(hashCode); SharedEntryValue? e = null; int hash; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { (hash, e) = arr[idx]; if (e != null) { if (hash == hashCode && StringTable.TextEquals(e.Text, chars.AsSpan(start, len))) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } internal void AddItem(char[] chars, int start, int len, int hashCode, T item) { var text = _strings.Add(chars, start, len); // add to the shared table first (in case someone looks for same item) var e = new SharedEntryValue(text, item); AddSharedEntry(hashCode, e); // add to the local table too ref var localSlot = ref _localTable[LocalIdxFromHash(hashCode)]; localSlot.HashCode = hashCode; localSlot.Text = text; localSlot.Item = item; } private void AddSharedEntry(int hashCode, SharedEntryValue e) { var arr = _sharedTableInst; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Entry == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = NextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Entry, e); } private static int LocalIdxFromHash(int hash) { return hash & LocalSizeMask; } private static int SharedIdxFromHash(int hash) { // we can afford to mix some more hash bits here return (hash ^ (hash >> LocalSizeBits)) & SharedSizeMask; } private int NextRandom() { var r = _random; if (r != null) { return r.Next(); } r = new Random(); _random = r; return r.Next(); } } }
// 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 System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using System.Threading; namespace Roslyn.Utilities { internal class TextKeyedCache<T> where T : class { // immutable tuple - text and corresponding item // reference type because we want atomic assignments private class SharedEntryValue { public readonly string Text; public readonly T Item; public SharedEntryValue(string Text, T item) { this.Text = Text; this.Item = item; } } // TODO: Need to tweak the size with more scenarios. // for now this is what works well enough with // Roslyn C# compiler project // Size of local cache. private const int LocalSizeBits = 11; private const int LocalSize = (1 << LocalSizeBits); private const int LocalSizeMask = LocalSize - 1; // max size of shared cache. private const int SharedSizeBits = 16; private const int SharedSize = (1 << SharedSizeBits); private const int SharedSizeMask = SharedSize - 1; // size of bucket in shared cache. (local cache has bucket size 1). private const int SharedBucketBits = 4; private const int SharedBucketSize = (1 << SharedBucketBits); private const int SharedBucketSizeMask = SharedBucketSize - 1; // local cache // simple fast and not threadsafe cache // with limited size and "last add wins" expiration policy private readonly (string Text, int HashCode, T Item)[] _localTable = new (string Text, int HashCode, T Item)[LocalSize]; // shared threadsafe cache // slightly slower than local cache // we read this cache when having a miss in local cache // writes to local cache will update shared cache as well. private static readonly (int HashCode, SharedEntryValue Entry)[] s_sharedTable = new (int HashCode, SharedEntryValue Entry)[SharedSize]; // store a reference to shared cache locally // accessing a static field of a generic type could be nontrivial private readonly (int HashCode, SharedEntryValue Entry)[] _sharedTableInst = s_sharedTable; private readonly StringTable _strings; // random - used for selecting a victim in the shared cache. // TODO: consider whether a counter is random enough private Random? _random; internal TextKeyedCache() : this(null) { } // implement Poolable object pattern #region "Poolable" private TextKeyedCache(ObjectPool<TextKeyedCache<T>>? pool) { _pool = pool; _strings = new StringTable(); } private readonly ObjectPool<TextKeyedCache<T>>? _pool; private static readonly ObjectPool<TextKeyedCache<T>> s_staticPool = CreatePool(); private static ObjectPool<TextKeyedCache<T>> CreatePool() { var pool = new ObjectPool<TextKeyedCache<T>>( pool => new TextKeyedCache<T>(pool), Environment.ProcessorCount * 4); return pool; } public static TextKeyedCache<T> GetInstance() { return s_staticPool.Allocate(); } public void Free() { // leave cache content in the cache, just return it to the pool // Array.Clear(this.localTable, 0, this.localTable.Length); // Array.Clear(sharedTable, 0, sharedTable.Length); _pool?.Free(this); } #endregion // Poolable internal T? FindItem(char[] chars, int start, int len, int hashCode) { // get direct element reference to avoid extra range checks ref var localSlot = ref _localTable[LocalIdxFromHash(hashCode)]; var text = localSlot.Text; if (text != null && localSlot.HashCode == hashCode) { if (StringTable.TextEquals(text, chars.AsSpan(start, len))) { return localSlot.Item; } } SharedEntryValue? e = FindSharedEntry(chars, start, len, hashCode); if (e != null) { localSlot.HashCode = hashCode; localSlot.Text = e.Text; var tk = e.Item; localSlot.Item = tk; return tk; } return null!; } private SharedEntryValue? FindSharedEntry(char[] chars, int start, int len, int hashCode) { var arr = _sharedTableInst; int idx = SharedIdxFromHash(hashCode); SharedEntryValue? e = null; int hash; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { (hash, e) = arr[idx]; if (e != null) { if (hash == hashCode && StringTable.TextEquals(e.Text, chars.AsSpan(start, len))) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } internal void AddItem(char[] chars, int start, int len, int hashCode, T item) { var text = _strings.Add(chars, start, len); // add to the shared table first (in case someone looks for same item) var e = new SharedEntryValue(text, item); AddSharedEntry(hashCode, e); // add to the local table too ref var localSlot = ref _localTable[LocalIdxFromHash(hashCode)]; localSlot.HashCode = hashCode; localSlot.Text = text; localSlot.Item = item; } private void AddSharedEntry(int hashCode, SharedEntryValue e) { var arr = _sharedTableInst; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Entry == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = NextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Entry, e); } private static int LocalIdxFromHash(int hash) { return hash & LocalSizeMask; } private static int SharedIdxFromHash(int hash) { // we can afford to mix some more hash bits here return (hash ^ (hash >> LocalSizeBits)) & SharedSizeMask; } private int NextRandom() { var r = _random; if (r != null) { return r.Next(); } r = new Random(); _random = r; return r.Next(); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/Server/VBCSCompiler/MemoryHelper.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.Runtime.InteropServices; using Microsoft.CodeAnalysis.CommandLine; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CompilerServer { /// <summary> /// Uses p/invoke to gain access to information about how much memory this process is using /// and how much is still available. /// </summary> [StructLayout(LayoutKind.Sequential)] internal sealed class MemoryHelper { private MemoryHelper() { this.Length = (int)Marshal.SizeOf(this); } // The length field must be set to the size of this data structure. public int Length; public int PercentPhysicalUsed; public ulong MaxPhysical; public ulong AvailablePhysical; public ulong MaxPageFile; public ulong AvailablePageFile; public ulong MaxVirtual; public ulong AvailableVirtual; public ulong Reserved; //always 0 public static bool IsMemoryAvailable(ICompilerServerLogger logger) { if (!PlatformInformation.IsWindows) { // assume we have enough memory on non-Windows machines return true; } MemoryHelper status = new MemoryHelper(); GlobalMemoryStatusEx(status); ulong max = status.MaxVirtual; ulong free = status.AvailableVirtual; int shift = 20; string unit = "MB"; if (free >> shift == 0) { shift = 10; unit = "KB"; } logger.Log("Free memory: {1}{0} of {2}{0}.", unit, free >> shift, max >> shift); return free >= 800 << 20; // Value (500MB) is arbitrary; feel free to improve. } [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GlobalMemoryStatusEx([In, Out] MemoryHelper buffer); } }
// 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.Runtime.InteropServices; using Microsoft.CodeAnalysis.CommandLine; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CompilerServer { /// <summary> /// Uses p/invoke to gain access to information about how much memory this process is using /// and how much is still available. /// </summary> [StructLayout(LayoutKind.Sequential)] internal sealed class MemoryHelper { private MemoryHelper() { this.Length = (int)Marshal.SizeOf(this); } // The length field must be set to the size of this data structure. public int Length; public int PercentPhysicalUsed; public ulong MaxPhysical; public ulong AvailablePhysical; public ulong MaxPageFile; public ulong AvailablePageFile; public ulong MaxVirtual; public ulong AvailableVirtual; public ulong Reserved; //always 0 public static bool IsMemoryAvailable(ICompilerServerLogger logger) { if (!PlatformInformation.IsWindows) { // assume we have enough memory on non-Windows machines return true; } MemoryHelper status = new MemoryHelper(); GlobalMemoryStatusEx(status); ulong max = status.MaxVirtual; ulong free = status.AvailableVirtual; int shift = 20; string unit = "MB"; if (free >> shift == 0) { shift = 10; unit = "KB"; } logger.Log("Free memory: {1}{0} of {2}{0}.", unit, free >> shift, max >> shift); return free >= 800 << 20; // Value (500MB) is arbitrary; feel free to improve. } [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GlobalMemoryStatusEx([In, Out] MemoryHelper buffer); } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Compilers/Core/CodeAnalysisTest/Text/StringText_LineTest.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 Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class StringText_LineTest { [Fact] public void FromSpanNotIncludingBreaks() { string newLine = Environment.NewLine; var text = SourceText.From("goo" + newLine); var span = new TextSpan(0, 3); var line = TextLine.FromSpan(text, span); Assert.Equal(span, line.Span); Assert.Equal(3 + newLine.Length, line.EndIncludingLineBreak); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanIncludingBreaksAtEnd() { var text = SourceText.From("goo" + Environment.NewLine); var span = TextSpan.FromBounds(0, text.Length); var line = TextLine.FromSpan(text, span); Assert.Equal(span, line.SpanIncludingLineBreak); Assert.Equal(3, line.End); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanIncludingBreaks() { var text = SourceText.From("goo" + Environment.NewLine + "bar"); var span = TextSpan.FromBounds(0, text.Length); var line = TextLine.FromSpan(text, span); Assert.Equal(span, line.SpanIncludingLineBreak); Assert.Equal(text.Length, line.End); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanNoBreaksBeforeOrAfter() { var text = SourceText.From("goo"); var line = TextLine.FromSpan(text, new TextSpan(0, 3)); Assert.Equal("goo", line.ToString()); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanZeroLengthNotEndOfLineThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(0, 0))); } [Fact] public void FromSpanNotEndOfLineThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(0, 3))); } [Fact] public void FromSpanNotStartOfLineThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(1, 5))); } [Fact] public void FromSpanZeroLengthAtEnd() { var text = SourceText.From("goo" + Environment.NewLine); var start = text.Length; var line = TextLine.FromSpan(text, new TextSpan(start, 0)); Assert.Equal("", line.ToString()); Assert.Equal(0, line.Span.Length); Assert.Equal(0, line.SpanIncludingLineBreak.Length); Assert.Equal(start, line.Start); Assert.Equal(start, line.Span.Start); Assert.Equal(start, line.SpanIncludingLineBreak.Start); Assert.Equal(1, line.LineNumber); } [Fact] public void FromSpanZeroLengthWithLineBreak() { var text = SourceText.From(Environment.NewLine); var line = TextLine.FromSpan(text, new TextSpan(0, 0)); Assert.Equal("", line.ToString()); Assert.Equal(Environment.NewLine.Length, line.SpanIncludingLineBreak.Length); } [Fact] public void FromSpanLengthGreaterThanTextThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(1, 10))); } [Fact] public void FromSpanStartsBeforeZeroThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(-1, 2))); } [Fact] public void FromSpanZeroLengthBeyondEndThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(7, 0))); } [Fact] public void FromSpanTextNullThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentNullException>(() => TextLine.FromSpan(null, new TextSpan(0, 2))); } } }
// 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 Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class StringText_LineTest { [Fact] public void FromSpanNotIncludingBreaks() { string newLine = Environment.NewLine; var text = SourceText.From("goo" + newLine); var span = new TextSpan(0, 3); var line = TextLine.FromSpan(text, span); Assert.Equal(span, line.Span); Assert.Equal(3 + newLine.Length, line.EndIncludingLineBreak); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanIncludingBreaksAtEnd() { var text = SourceText.From("goo" + Environment.NewLine); var span = TextSpan.FromBounds(0, text.Length); var line = TextLine.FromSpan(text, span); Assert.Equal(span, line.SpanIncludingLineBreak); Assert.Equal(3, line.End); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanIncludingBreaks() { var text = SourceText.From("goo" + Environment.NewLine + "bar"); var span = TextSpan.FromBounds(0, text.Length); var line = TextLine.FromSpan(text, span); Assert.Equal(span, line.SpanIncludingLineBreak); Assert.Equal(text.Length, line.End); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanNoBreaksBeforeOrAfter() { var text = SourceText.From("goo"); var line = TextLine.FromSpan(text, new TextSpan(0, 3)); Assert.Equal("goo", line.ToString()); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanZeroLengthNotEndOfLineThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(0, 0))); } [Fact] public void FromSpanNotEndOfLineThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(0, 3))); } [Fact] public void FromSpanNotStartOfLineThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(1, 5))); } [Fact] public void FromSpanZeroLengthAtEnd() { var text = SourceText.From("goo" + Environment.NewLine); var start = text.Length; var line = TextLine.FromSpan(text, new TextSpan(start, 0)); Assert.Equal("", line.ToString()); Assert.Equal(0, line.Span.Length); Assert.Equal(0, line.SpanIncludingLineBreak.Length); Assert.Equal(start, line.Start); Assert.Equal(start, line.Span.Start); Assert.Equal(start, line.SpanIncludingLineBreak.Start); Assert.Equal(1, line.LineNumber); } [Fact] public void FromSpanZeroLengthWithLineBreak() { var text = SourceText.From(Environment.NewLine); var line = TextLine.FromSpan(text, new TextSpan(0, 0)); Assert.Equal("", line.ToString()); Assert.Equal(Environment.NewLine.Length, line.SpanIncludingLineBreak.Length); } [Fact] public void FromSpanLengthGreaterThanTextThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(1, 10))); } [Fact] public void FromSpanStartsBeforeZeroThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(-1, 2))); } [Fact] public void FromSpanZeroLengthBeyondEndThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(7, 0))); } [Fact] public void FromSpanTextNullThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentNullException>(() => TextLine.FromSpan(null, new TextSpan(0, 2))); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/VisualStudio/CSharp/Impl/Options/AutomationObject/AutomationObject.SymbolSearch.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.SymbolSearch; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { public partial class AutomationObject { public int AddImport_SuggestForTypesInReferenceAssemblies { get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies); } set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, value); } } public int AddImport_SuggestForTypesInNuGetPackages { get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages); } set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, 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 Microsoft.CodeAnalysis.SymbolSearch; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { public partial class AutomationObject { public int AddImport_SuggestForTypesInReferenceAssemblies { get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies); } set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, value); } } public int AddImport_SuggestForTypesInNuGetPackages { get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages); } set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, value); } } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationMethodInfo.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 System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationMethodInfo { private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationMethodInfo> s_methodToInfoMap = new(); private readonly bool _isNew; private readonly bool _isUnsafe; private readonly bool _isPartial; private readonly bool _isAsync; private readonly ImmutableArray<SyntaxNode> _statements; private readonly ImmutableArray<SyntaxNode> _handlesExpressions; private CodeGenerationMethodInfo( bool isNew, bool isUnsafe, bool isPartial, bool isAsync, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> handlesExpressions) { _isNew = isNew; _isUnsafe = isUnsafe; _isPartial = isPartial; _isAsync = isAsync; _statements = statements.NullToEmpty(); _handlesExpressions = handlesExpressions.NullToEmpty(); } public static void Attach( IMethodSymbol method, bool isNew, bool isUnsafe, bool isPartial, bool isAsync, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> handlesExpressions) { var info = new CodeGenerationMethodInfo(isNew, isUnsafe, isPartial, isAsync, statements, handlesExpressions); s_methodToInfoMap.Add(method, info); } private static CodeGenerationMethodInfo GetInfo(IMethodSymbol method) { s_methodToInfoMap.TryGetValue(method, out var info); return info; } public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol method) => GetStatements(GetInfo(method)); public static ImmutableArray<SyntaxNode> GetHandlesExpressions(IMethodSymbol method) => GetHandlesExpressions(GetInfo(method)); public static bool GetIsNew(IMethodSymbol method) => GetIsNew(GetInfo(method)); public static bool GetIsUnsafe(IMethodSymbol method) => GetIsUnsafe(GetInfo(method)); public static bool GetIsPartial(IMethodSymbol method) => GetIsPartial(GetInfo(method)); public static bool GetIsAsyncMethod(IMethodSymbol method) => GetIsAsyncMethod(GetInfo(method)); private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationMethodInfo info) => info?._statements ?? ImmutableArray<SyntaxNode>.Empty; private static ImmutableArray<SyntaxNode> GetHandlesExpressions(CodeGenerationMethodInfo info) => info?._handlesExpressions ?? ImmutableArray<SyntaxNode>.Empty; private static bool GetIsNew(CodeGenerationMethodInfo info) => info != null && info._isNew; private static bool GetIsUnsafe(CodeGenerationMethodInfo info) => info != null && info._isUnsafe; private static bool GetIsPartial(CodeGenerationMethodInfo info) => info != null && info._isPartial; private static bool GetIsAsyncMethod(CodeGenerationMethodInfo info) => info != null && info._isAsync; } }
// 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 System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationMethodInfo { private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationMethodInfo> s_methodToInfoMap = new(); private readonly bool _isNew; private readonly bool _isUnsafe; private readonly bool _isPartial; private readonly bool _isAsync; private readonly ImmutableArray<SyntaxNode> _statements; private readonly ImmutableArray<SyntaxNode> _handlesExpressions; private CodeGenerationMethodInfo( bool isNew, bool isUnsafe, bool isPartial, bool isAsync, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> handlesExpressions) { _isNew = isNew; _isUnsafe = isUnsafe; _isPartial = isPartial; _isAsync = isAsync; _statements = statements.NullToEmpty(); _handlesExpressions = handlesExpressions.NullToEmpty(); } public static void Attach( IMethodSymbol method, bool isNew, bool isUnsafe, bool isPartial, bool isAsync, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> handlesExpressions) { var info = new CodeGenerationMethodInfo(isNew, isUnsafe, isPartial, isAsync, statements, handlesExpressions); s_methodToInfoMap.Add(method, info); } private static CodeGenerationMethodInfo GetInfo(IMethodSymbol method) { s_methodToInfoMap.TryGetValue(method, out var info); return info; } public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol method) => GetStatements(GetInfo(method)); public static ImmutableArray<SyntaxNode> GetHandlesExpressions(IMethodSymbol method) => GetHandlesExpressions(GetInfo(method)); public static bool GetIsNew(IMethodSymbol method) => GetIsNew(GetInfo(method)); public static bool GetIsUnsafe(IMethodSymbol method) => GetIsUnsafe(GetInfo(method)); public static bool GetIsPartial(IMethodSymbol method) => GetIsPartial(GetInfo(method)); public static bool GetIsAsyncMethod(IMethodSymbol method) => GetIsAsyncMethod(GetInfo(method)); private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationMethodInfo info) => info?._statements ?? ImmutableArray<SyntaxNode>.Empty; private static ImmutableArray<SyntaxNode> GetHandlesExpressions(CodeGenerationMethodInfo info) => info?._handlesExpressions ?? ImmutableArray<SyntaxNode>.Empty; private static bool GetIsNew(CodeGenerationMethodInfo info) => info != null && info._isNew; private static bool GetIsUnsafe(CodeGenerationMethodInfo info) => info != null && info._isUnsafe; private static bool GetIsPartial(CodeGenerationMethodInfo info) => info != null && info._isPartial; private static bool GetIsAsyncMethod(CodeGenerationMethodInfo info) => info != null && info._isAsync; } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/EditorFeatures/CSharpTest/Structure/InterpolatedStringExpressionStructureTests.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.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class InterpolatedStringExpressionStructureTests : AbstractCSharpSyntaxNodeStructureTests<InterpolatedStringExpressionSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new InterpolatedStringExpressionStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultiLineStringLiteral() { await VerifyBlockSpansAsync( @" class C { void M() { var v = {|hint:{|textspan:$$$@"" {123} ""|}|}; } }", Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMissingOnIncompleteStringLiteral() { await VerifyNoBlockSpansAsync( @" class C { void M() { var v = $$$""; } }"); } } }
// 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.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class InterpolatedStringExpressionStructureTests : AbstractCSharpSyntaxNodeStructureTests<InterpolatedStringExpressionSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new InterpolatedStringExpressionStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultiLineStringLiteral() { await VerifyBlockSpansAsync( @" class C { void M() { var v = {|hint:{|textspan:$$$@"" {123} ""|}|}; } }", Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMissingOnIncompleteStringLiteral() { await VerifyNoBlockSpansAsync( @" class C { void M() { var v = $$$""; } }"); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/DuplicatedGuidLibrary1.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>{C71872E2-0D54-4C4E-B6A9-8C1726B7B78C}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Library1</RootNamespace> <AssemblyName>Library1</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.Data.DataSetExtensions" /> <Reference Include="System.Xml" /> <Reference Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="Class1.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </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>{C71872E2-0D54-4C4E-B6A9-8C1726B7B78C}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Library1</RootNamespace> <AssemblyName>Library1</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.Data.DataSetExtensions" /> <Reference Include="System.Xml" /> <Reference Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="Class1.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </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,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ForEachKeywordRecommender.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.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ForEachKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ForEachKeywordRecommender() : base(SyntaxKind.ForEachKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsStatementContext || context.IsGlobalStatementContext || context.IsAwaitStatementContext(position, 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.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ForEachKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ForEachKeywordRecommender() : base(SyntaxKind.ForEachKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsStatementContext || context.IsGlobalStatementContext || context.IsAwaitStatementContext(position, cancellationToken); } } }
-1